ctb_formats_pan/
array.rs

1/* SPDX-License-Identifier: MIT */
2/*
3This file is part of Collective Toolbox, a database and document workspace and utilities.
4Copyright (C) 2026 Collective Toolbox Developers
5Contact: info@collectivetoolbox.com
6
7Permission is hereby granted, free of charge, to any person obtaining a copy of
8this software and associated documentation files (the “Software”), to deal in
9the Software without restriction, including without limitation the rights to
10use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
11the Software, and to permit persons to whom the Software is furnished to do so,
12subject to the following conditions:
13
14The above copyright notice and this permission notice shall be included in all
15copies or substantial portions of the Software.
16
17THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
23SOFTWARE.
24*/
25
26//! Pan-style array manipulation helpers.
27
28#[allow(
29    unused_imports,
30    clippy::wildcard_imports,
31    reason = "Standard workspace module prelude"
32)]
33use crate::utilities::*;
34
35use std::cmp::Ordering;
36use std::collections::{BTreeSet, HashSet};
37
38/// Returns the 1-based `item` from `text` split by `sep`.
39///
40/// Returns an empty string when the item is out of range.
41pub fn array(text: &str, item: usize, sep: char) -> Result<String> {
42    if item == 0 {
43        bail!("array item numbers start at 1");
44    }
45
46    let idx = item.saturating_sub(1);
47    // Reason for fallback: out of bounds item index in separator split defaults to empty string per Pan documentation.
48    Ok(text.split(sep).nth(idx).unwrap_or("").to_string())
49}
50
51/// Alias for `array`.
52pub fn arrayitem(text: &str, item: usize, sep: char) -> Result<String> {
53    array(text, item, sep)
54}
55
56/// Returns elements from `text` that correspond to non-empty elements in `selection`.
57pub fn arrayselected(text: &str, selection: &str, sep: char) -> Result<String> {
58    let mut out = Vec::new();
59    for (t, s) in text.split(sep).zip(selection.split(sep)) {
60        if !s.trim().is_empty() && s.trim() != "0" {
61            out.push(t);
62        }
63    }
64    Ok(join_parts(&out, sep))
65}
66
67/// Returns true if any element equals `needle`.
68pub fn arraycontains(text: &str, needle: &str, sep: char) -> Result<bool> {
69    Ok(text.split(sep).any(|el| el == needle))
70}
71
72/// Replaces the 1-based `item` with `value` when it exists.
73pub fn arraychange(
74    text: &str,
75    value: &str,
76    item: usize,
77    sep: char,
78) -> Result<String> {
79    if item == 0 {
80        bail!("array item numbers start at 1");
81    }
82
83    let mut parts: Vec<&str> = text.split(sep).collect();
84    let idx = item.saturating_sub(1);
85    let Some(slot) = parts.get_mut(idx) else {
86        return Ok(text.to_string());
87    };
88
89    *slot = value;
90    Ok(join_parts(&parts, sep))
91}
92
93/// Deletes `count` items starting at the 1-based `item` index.
94pub fn arraydelete(
95    text: &str,
96    item: usize,
97    count: usize,
98    sep: char,
99) -> Result<String> {
100    if item == 0 {
101        bail!("array item numbers start at 1");
102    }
103    if count == 0 {
104        return Ok(text.to_string());
105    }
106
107    let mut parts: Vec<&str> = text.split(sep).collect();
108    let start = item.saturating_sub(1);
109    if start >= parts.len() {
110        return Ok(text.to_string());
111    }
112
113    let end_exclusive = start.saturating_add(count).min(parts.len());
114    parts.drain(start..end_exclusive);
115    Ok(join_parts(&parts, sep))
116}
117
118/// Removes duplicate elements and returns a sorted array.
119pub fn arraydeduplicate(text: &str, sep: char) -> Result<String> {
120    let set: BTreeSet<String> = text.split(sep).map(str::to_string).collect();
121    let parts: Vec<&str> = set.iter().map(String::as_str).collect();
122    Ok(join_parts(&parts, sep))
123}
124
125/// Returns unique elements present in both arrays.
126///
127/// The result preserves the order of `a1` and ignores empty elements.
128pub fn arrayboth(a1: &str, a2: &str, sep: char) -> Result<String> {
129    let b: HashSet<&str> = a2.split(sep).filter(|s| !s.is_empty()).collect();
130
131    let mut out: Vec<&str> = Vec::new();
132    let mut seen: HashSet<&str> = HashSet::new();
133    for el in a1.split(sep).filter(|s| !s.is_empty()) {
134        if b.contains(el) && seen.insert(el) {
135            out.push(el);
136        }
137    }
138
139    Ok(join_parts(&out, sep))
140}
141
142/// Returns unique elements in `a1` that are not in `a2`.
143///
144/// The result preserves the order of `a1` and ignores empty elements.
145pub fn arraydifference(a1: &str, a2: &str, sep: char) -> Result<String> {
146    let b: HashSet<&str> = a2.split(sep).filter(|s| !s.is_empty()).collect();
147
148    let mut out: Vec<&str> = Vec::new();
149    let mut seen: HashSet<&str> = HashSet::new();
150    for el in a1.split(sep).filter(|s| !s.is_empty()) {
151        if !b.contains(el) && seen.insert(el) {
152            out.push(el);
153        }
154    }
155
156    Ok(join_parts(&out, sep))
157}
158
159/// Returns the 1-based element index containing `position`.
160///
161/// The `position` is 1-based in character indices.
162pub fn arrayelement(text: &str, position: usize, sep: char) -> Result<usize> {
163    if position == 0 {
164        bail!("character positions start at 1");
165    }
166
167    let mut elem_no: usize = 1;
168    let mut char_pos: usize = 0;
169
170    for ch in text.chars() {
171        char_pos = char_pos.saturating_add(1);
172
173        if char_pos == position {
174            if ch == sep {
175                return Ok(elem_no.saturating_add(1));
176            }
177            return Ok(elem_no);
178        }
179
180        if ch == sep {
181            elem_no = elem_no.saturating_add(1);
182        }
183    }
184
185    Ok(elem_no)
186}
187
188/// Extracts a column from a row/column delimited table.
189///
190/// # Errors
191/// Returns an error if `colnum == 0` (column numbers are 1-based) or if any row
192/// contains fewer columns than `colnum`.
193pub fn arraycolumn(
194    text: &str,
195    colnum: usize,
196    rowsep: char,
197    colsep: char,
198) -> Result<String> {
199    if colnum == 0 {
200        bail!("array column numbers start at 1");
201    }
202
203    let idx = colnum.saturating_sub(1);
204
205    let mut out: Vec<String> = Vec::new();
206    for row in text.split(rowsep) {
207        let cell = row.split(colsep).nth(idx).ok_or_else(|| {
208            anyhow::anyhow!(
209                "Row contains fewer columns than requested column {colnum}"
210            )
211        })?;
212        out.push(cell.to_string());
213    }
214
215    let parts: Vec<&str> = out.iter().map(String::as_str).collect();
216    Ok(join_parts(&parts, rowsep))
217}
218
219/// Removes alternating matches of `value`.
220///
221/// Consecutive matches preserve every second element.
222pub fn arraydeletevalue(text: &str, value: &str, sep: char) -> Result<String> {
223    let mut out: Vec<&str> = Vec::new();
224
225    // When matches are consecutive, leave the second occurrence behind.
226    let mut deleted_previous_match = false;
227
228    for el in text.split(sep) {
229        if el == value {
230            if deleted_previous_match {
231                out.push(el);
232                deleted_previous_match = false;
233            } else {
234                deleted_previous_match = true;
235            }
236            continue;
237        }
238
239        out.push(el);
240        deleted_previous_match = false;
241    }
242
243    Ok(join_parts(&out, sep))
244}
245
246/// Returns a slice from `first` to `last` (inclusive), 1-based.
247pub fn arrayrange(
248    text: &str,
249    first: usize,
250    last: usize,
251    sep: char,
252) -> Result<String> {
253    if first == 0 || last == 0 {
254        bail!("array item numbers start at 1");
255    }
256    if first > last {
257        return Ok(String::new());
258    }
259
260    let parts: Vec<&str> = text.split(sep).collect();
261
262    let start = first.saturating_sub(1);
263    if start >= parts.len() {
264        return Ok(String::new());
265    }
266
267    let last_idx = last.saturating_sub(1);
268    let end_exclusive = last_idx.saturating_add(1).min(parts.len());
269
270    Ok(join_parts(
271        parts
272            .get(start..end_exclusive)
273            .context("Invalid slice range")?,
274        sep,
275    ))
276}
277
278/// Returns the first element in the array.
279pub fn arrayfirst(text: &str, sep: char) -> Result<String> {
280    array(text, 1, sep)
281}
282
283/// Returns the last element in the array.
284pub fn arraylast(text: &str, sep: char) -> Result<String> {
285    // Reason for fallback: empty array string defaults last element to empty string
286    Ok(text.split(sep).next_back().unwrap_or("").to_string())
287}
288
289/// Inserts `count` empty elements at the 1-based `item` position.
290pub fn arrayinsert(
291    text: &str,
292    item: usize,
293    count: usize,
294    sep: char,
295) -> Result<String> {
296    if item == 0 {
297        bail!("array item numbers start at 1");
298    }
299    if count == 0 {
300        return Ok(text.to_string());
301    }
302
303    let mut parts: Vec<String> = text.split(sep).map(str::to_string).collect();
304    let insert_at = (item.saturating_sub(1)).min(parts.len());
305    for _ in 0..count {
306        parts.insert(insert_at, String::new());
307    }
308
309    Ok(join_strings(&parts, sep))
310}
311
312/// Removes `count` elements from the start of the array.
313pub fn arraylefttrim(text: &str, count: usize, sep: char) -> Result<String> {
314    if count == 0 {
315        return Ok(text.to_string());
316    }
317
318    let mut parts: Vec<&str> = text.split(sep).collect();
319    let end_exclusive = count.min(parts.len());
320    parts.drain(0..end_exclusive);
321    Ok(join_parts(&parts, sep))
322}
323
324/// Removes `count` elements from the end of the array.
325pub fn arraytrim(text: &str, count: usize, sep: char) -> Result<String> {
326    if count == 0 {
327        return Ok(text.to_string());
328    }
329
330    let mut parts: Vec<&str> = text.split(sep).collect();
331    let len = parts.len();
332    let start = len.saturating_sub(count);
333    parts.drain(start..len);
334    Ok(join_parts(&parts, sep))
335}
336
337/// Looks up `key` in key/value rows and returns its value.
338///
339/// Rows are split by `mainsep`, keys and values by `subsep`.
340pub fn arraylookup(
341    text: &str,
342    key: &str,
343    mainsep: char,
344    subsep: char,
345    default: &str,
346) -> Result<String> {
347    for line in text.split(mainsep) {
348        let (k, v) = split_kv(line, subsep);
349        if k == key {
350            return Ok(v.to_string());
351        }
352    }
353    Ok(default.to_string())
354}
355
356/// Looks up `key` as a value and returns its row key.
357///
358/// Rows are split by `mainsep`, keys and values by `subsep`.
359pub fn arrayreverselookup(
360    text: &str,
361    key: &str,
362    mainsep: char,
363    subsep: char,
364    default: &str,
365) -> Result<String> {
366    for line in text.split(mainsep) {
367        let (k, v) = split_kv(line, subsep);
368        if v == key {
369            return Ok(k.to_string());
370        }
371    }
372    Ok(default.to_string())
373}
374
375/// Zips two arrays, joining corresponding elements with `joiner`.
376///
377/// # Errors
378/// Returns an error if `joiner` is empty or longer than 10 characters, or if
379/// `array1` and `array2` have unequal element counts.
380pub fn arraymerge(
381    array1: &str,
382    array2: &str,
383    separator: char,
384    joiner: &str,
385) -> Result<String> {
386    let joiner_len = joiner.chars().count();
387    if joiner_len == 0 || joiner_len > 10 {
388        bail!("arraymerge joiner must be 1 to 10 characters");
389    }
390
391    let a1: Vec<&str> = array1.split(separator).collect();
392    let a2: Vec<&str> = array2.split(separator).collect();
393    if a1.len() != a2.len() {
394        bail!(
395            "arraymerge arrays must have equal length: array1 has {}, array2 has {}",
396            a1.len(),
397            a2.len()
398        );
399    }
400
401    let mut out: Vec<String> = Vec::with_capacity(a1.len());
402    for (left, right) in a1.into_iter().zip(a2) {
403        out.push(format!("{left}{joiner}{right}"));
404    }
405
406    Ok(join_strings(&out, separator))
407}
408
409/// Returns true if no element equals `needle`.
410pub fn arraynotcontains(text: &str, needle: &str, sep: char) -> Result<bool> {
411    Ok(!text.split(sep).any(|el| el == needle))
412}
413
414/// Returns the array sorted lexicographically.
415pub fn arraysort(text: &str, separator: char) -> Result<String> {
416    let mut parts: Vec<&str> = text.split(separator).collect();
417    parts.sort_unstable();
418    Ok(join_parts(&parts, separator))
419}
420
421/// Returns the array sorted by numeric value.
422///
423/// Returns an error if any element is non-numeric or non-finite.
424pub fn arraynumericsort(text: &str, separator: char) -> Result<String> {
425    let mut parts: Vec<(f64, &str)> = Vec::new();
426    for el in text.split(separator) {
427        let n: f64 = el.parse().with_context(|| {
428            format!("arraynumericsort element is not numeric: {el:?}")
429        })?;
430        if !n.is_finite() {
431            bail!("arraynumericsort element is not finite: {el:?}");
432        }
433        parts.push((n, el));
434    }
435
436    parts.sort_by(|a, b| a.0.total_cmp(&b.0));
437
438    let out: Vec<&str> = parts.into_iter().map(|(_, s)| s).collect();
439    Ok(join_parts(&out, separator))
440}
441
442/// Sums numeric elements of the array.
443///
444/// Returns an error if any element is non-numeric or non-finite.
445pub fn arraynumerictotal(text: &str, separator: char) -> Result<f64> {
446    let mut sum = 0.0f64;
447    for el in text.split(separator) {
448        let n: f64 = el.parse().with_context(|| {
449            format!("arraynumerictotal element is not numeric: {el:?}")
450        })?;
451        if !n.is_finite() {
452            bail!("arraynumerictotal element is not finite: {el:?}");
453        }
454        sum += n;
455    }
456    Ok(sum)
457}
458
459/// Deterministically shuffles elements based on the input.
460pub fn arrayrandomize(text: &str, separator: char) -> Result<String> {
461    let mut parts: Vec<String> =
462        text.split(separator).map(str::to_string).collect();
463    if parts.len() <= 1 {
464        return Ok(text.to_string());
465    }
466
467    let seed = stable_hash64(text) ^ stable_hash64(&separator.to_string());
468    shuffle_deterministic(&mut parts, seed)?;
469
470    // Avoid an unhelpful "randomization" that returns the original order.
471    if join_strings(&parts, separator) == text {
472        parts.rotate_left(1);
473    }
474
475    Ok(join_strings(&parts, separator))
476}
477
478/// Replaces alternating matches of `oldvalue` with `newvalue`.
479///
480/// Consecutive matches preserve every second element.
481pub fn arrayreplacevalue(
482    text: &str,
483    oldvalue: &str,
484    newvalue: &str,
485    sep: char,
486) -> Result<String> {
487    let mut out: Vec<&str> = Vec::new();
488
489    let mut replaced_previous_match = false;
490    for el in text.split(sep) {
491        if el == oldvalue {
492            if replaced_previous_match {
493                out.push(el);
494                replaced_previous_match = false;
495            } else {
496                out.push(newvalue);
497                replaced_previous_match = true;
498            }
499            continue;
500        }
501
502        out.push(el);
503        replaced_previous_match = false;
504    }
505
506    Ok(join_parts(&out, sep))
507}
508
509/// Reverses the order of the array elements.
510pub fn arrayreverse(text: &str, sep: char) -> Result<String> {
511    let mut parts: Vec<&str> = text.split(sep).collect();
512    parts.reverse();
513    Ok(join_parts(&parts, sep))
514}
515
516/// Searches for a wildcard pattern and returns a 1-based index.
517///
518/// Returns 0 when no match is found.
519pub fn arraysearch(
520    array: &str,
521    pattern: &str,
522    start: usize,
523    sep: char,
524) -> Result<usize> {
525    if start == 0 {
526        bail!("array item numbers start at 1");
527    }
528
529    let parts: Vec<&str> = array.split(sep).collect();
530    let start_idx = start.saturating_sub(1);
531    if start_idx >= parts.len() {
532        return Ok(0);
533    }
534
535    for (i, el) in parts.iter().enumerate().skip(start_idx) {
536        if wildcard_match(pattern, el) {
537            return Ok(i.saturating_add(1));
538        }
539    }
540
541    Ok(0)
542}
543
544/// Removes empty elements from the array.
545pub fn arraystrip(text: &str, sep: char) -> Result<String> {
546    let out: Vec<&str> = text.split(sep).filter(|s| !s.is_empty()).collect();
547    Ok(join_parts(&out, sep))
548}
549
550/// Replaces consecutive duplicates with empty elements.
551pub fn arrayunpropagate(text: &str, separator: char) -> Result<String> {
552    let parts: Vec<&str> = text.split(separator).collect();
553    let mut out: Vec<&str> = Vec::with_capacity(parts.len());
554
555    let mut prev: Option<&str> = None;
556    for el in parts {
557        if prev == Some(el) {
558            out.push("");
559        } else {
560            out.push(el);
561            prev = Some(el);
562        }
563    }
564
565    Ok(join_parts(&out, separator))
566}
567
568/// Returns the number of elements, including empty ones.
569pub fn arraysize(text: &str, sep: char) -> Result<usize> {
570    Ok(text.split(sep).count())
571}
572
573/// Returns the value for `key` or the next greater table key.
574pub fn arraytableceiling(
575    array: &str,
576    key: &str,
577    sep: char,
578    subsep: char,
579    default: &str,
580) -> Result<String> {
581    arraytable_bound(array, key, sep, subsep, default, BoundDir::Ceiling)
582}
583
584/// Returns the value for `key` or the next lesser table key.
585pub fn arraytablefloor(
586    array: &str,
587    key: &str,
588    sep: char,
589    subsep: char,
590    default: &str,
591) -> Result<String> {
592    arraytable_bound(array, key, sep, subsep, default, BoundDir::Floor)
593}
594
595/// Builds a separator-joined sequence from `start` to `end` (inclusive).
596pub fn makenumberedarray(sep: char, start: i64, end: i64) -> Result<String> {
597    let mut out: Vec<String> = Vec::new();
598
599    if start <= end {
600        let mut n = start;
601        while n <= end {
602            out.push(n.to_string());
603            n = n.saturating_add(1);
604        }
605    } else {
606        let mut n = start;
607        while n >= end {
608            out.push(n.to_string());
609            n = n.saturating_sub(1);
610        }
611    }
612
613    Ok(join_strings(&out, sep))
614}
615
616/// Placeholder that requires export/arraybuild iteration context.
617pub fn arrayscan(_field: &str, _sep: char) -> Result<String> {
618    bail!("arrayscan requires export/arraybuild iteration context")
619}
620
621/// Placeholder that requires database scanning and formula evaluation.
622pub fn arrayselectedbuild(
623    _sep: char,
624    _db: &str,
625    _formula: &str,
626) -> Result<String> {
627    bail!(
628        "arrayselectedbuild requires database scanning and formula evaluation"
629    )
630}
631
632/// Placeholder that requires database field context.
633pub fn lineitemarray(_field: &str, _separator: char) -> Result<String> {
634    bail!("lineitemarray requires database field context")
635}
636
637/// Joins iterator items with `sep` into a single array string.
638pub fn arraybuild_from_iter<I, S>(sep: char, items: I) -> Result<String>
639where
640    I: IntoIterator<Item = S>,
641    S: AsRef<str>,
642{
643    let mut out = String::new();
644    let mut first = true;
645    for item in items {
646        if !first {
647            out.push(sep);
648        }
649        first = false;
650        out.push_str(item.as_ref());
651    }
652    Ok(out)
653}
654
655/// Placeholder that requires database scanning and formula evaluation.
656pub fn arraybuild(_sep: char, _db: &str, _formula: &str) -> Result<String> {
657    bail!("arraybuild requires database scanning and formula evaluation")
658}
659
660fn join_parts(parts: &[&str], sep: char) -> String {
661    let mut out = String::new();
662    let mut first = true;
663    for p in parts {
664        if !first {
665            out.push(sep);
666        }
667        first = false;
668        out.push_str(p);
669    }
670    out
671}
672
673fn join_strings(parts: &[String], sep: char) -> String {
674    let parts: Vec<&str> = parts.iter().map(String::as_str).collect();
675    join_parts(&parts, sep)
676}
677
678fn split_kv(line: &str, subsep: char) -> (&str, &str) {
679    if subsep == '\0' {
680        return (line, line);
681    }
682
683    let mut it = line.splitn(2, subsep);
684    // Reason for fallback: subseparator line split missing key or value defaults missing part to empty string
685    let k = it.next().unwrap_or("");
686    // Reason for fallback: subseparator line split missing key or value defaults missing part to empty string
687    let v = it.next().unwrap_or("");
688    (k, v)
689}
690
691fn stable_hash64(s: &str) -> u64 {
692    // 64-bit FNV-1a.
693    let mut h = 0xcbf29ce484222325u64;
694    for b in s.as_bytes() {
695        h ^= u64::from(*b);
696        h = h.wrapping_mul(0x100000001b3u64);
697    }
698    h
699}
700
701fn xorshift64(state: &mut u64) -> u64 {
702    let mut x = *state;
703    if x == 0 {
704        x = 0x9e3779b97f4a7c15u64;
705    }
706    x ^= x << 13;
707    x ^= x >> 7;
708    x ^= x << 17;
709    *state = x;
710    x
711}
712
713fn shuffle_deterministic(parts: &mut [String], seed: u64) -> Result<()> {
714    let len = parts.len();
715    let len_u64 =
716        u64::try_from(len).context("arrayrandomize length overflow")?;
717    if len <= 1 {
718        return Ok(());
719    }
720
721    let mut state = seed;
722    let mut i = len.saturating_sub(1);
723    while i > 0 {
724        let i1_u64 = u64::try_from(i.saturating_add(1))
725            .context("arrayrandomize index overflow")?;
726        let r = xorshift64(&mut state);
727        let j_u64 = r
728            .checked_rem(i1_u64)
729            .context("modulo by zero in arrayrandomize")?;
730        let j = usize::try_from(j_u64)
731            .context("arrayrandomize index conversion failed")?;
732        parts.swap(i, j);
733
734        i = i.saturating_sub(1);
735    }
736
737    // Use len_u64 so it is referenced (helps keep this code obviously correct).
738    let _ = len_u64;
739    Ok(())
740}
741
742fn wildcard_match(pattern: &str, text: &str) -> bool {
743    let p: Vec<char> = pattern.chars().collect();
744    let t: Vec<char> = text.chars().collect();
745
746    let mut pi = 0usize;
747    let mut ti = 0usize;
748    let mut star: Option<usize> = None;
749    let mut match_ti = 0usize;
750
751    while ti < t.len() {
752        if pi < p.len() && (p.get(pi) == Some(&'?') || p.get(pi) == t.get(ti)) {
753            pi = pi.saturating_add(1);
754            ti = ti.saturating_add(1);
755            continue;
756        }
757
758        if pi < p.len() && p.get(pi) == Some(&'*') {
759            star = Some(pi);
760            pi = pi.saturating_add(1);
761            match_ti = ti;
762            continue;
763        }
764
765        let Some(star_pi) = star else {
766            return false;
767        };
768
769        pi = star_pi.saturating_add(1);
770        match_ti = match_ti.saturating_add(1);
771        ti = match_ti;
772    }
773
774    while pi < p.len() && p.get(pi) == Some(&'*') {
775        pi = pi.saturating_add(1);
776    }
777
778    pi == p.len()
779}
780
781#[derive(Clone, Copy)]
782enum BoundDir {
783    Ceiling,
784    Floor,
785}
786
787fn is_all_numeric(s: &str) -> bool {
788    if s.is_empty() {
789        return false;
790    }
791
792    let mut saw_digit = false;
793    for ch in s.chars() {
794        if ch.is_ascii_digit() {
795            saw_digit = true;
796            continue;
797        }
798        if ch == '.' || ch == '-' || ch == '+' {
799            continue;
800        }
801        return false;
802    }
803
804    saw_digit
805}
806
807fn arraytable_bound(
808    array: &str,
809    key: &str,
810    sep: char,
811    subsep: char,
812    default: &str,
813    dir: BoundDir,
814) -> Result<String> {
815    let key_num = if is_all_numeric(key) {
816        let n: f64 = key.parse().with_context(|| {
817            format!("arraytable key is not numeric: {key:?}")
818        })?;
819        if !n.is_finite() {
820            bail!("arraytable key is not finite: {key:?}");
821        }
822        Some(n)
823    } else {
824        None
825    };
826
827    let mut best_key_num: Option<f64> = None;
828    let mut best_key_txt: Option<&str> = None;
829    let mut best_val: Option<&str> = None;
830
831    for line in array.split(sep) {
832        let (k, v) = split_kv(line, subsep);
833
834        if let Some(kn) = key_num {
835            let Ok(kf) = k.parse::<f64>() else {
836                // If numeric mode is chosen, ignore non-numeric table rows.
837                continue;
838            };
839            if !kf.is_finite() {
840                continue;
841            }
842
843            if kf == kn {
844                return Ok(v.to_string());
845            }
846
847            let better = match dir {
848                BoundDir::Ceiling => {
849                    kf > kn && best_key_num.is_none_or(|bk| kf < bk)
850                }
851                BoundDir::Floor => {
852                    kf < kn && best_key_num.is_none_or(|bk| kf > bk)
853                }
854            };
855
856            if better {
857                best_key_num = Some(kf);
858                best_val = Some(v);
859            }
860        } else {
861            if k == key {
862                return Ok(v.to_string());
863            }
864
865            let ord = k.cmp(key);
866            let better = match dir {
867                BoundDir::Ceiling => {
868                    ord == Ordering::Greater
869                        && best_key_txt.is_none_or(|bk| k < bk)
870                }
871                BoundDir::Floor => {
872                    ord == Ordering::Less
873                        && best_key_txt.is_none_or(|bk| k > bk)
874                }
875            };
876
877            if better {
878                best_key_txt = Some(k);
879                best_val = Some(v);
880            }
881        }
882    }
883
884    // Reason for fallback: per docblock (returning default when no floor/ceiling key matches is specified by Pan array contract)
885    Ok(best_val.unwrap_or(default).to_string())
886}
887
888#[cfg(test)]
889#[allow(
890    clippy::panic,
891    clippy::expect_used,
892    clippy::unwrap_used,
893    clippy::unwrap_in_result,
894    clippy::panic_in_result_fn,
895    clippy::indexing_slicing,
896    clippy::arithmetic_side_effects,
897    reason = "Standard repository test boilerplate"
898)]
899mod tests {
900    use super::*;
901
902    #[crate::ctb_test]
903    fn test_array() -> Result<()> {
904        let list = ",ABCD,,EFGH,IJKL,,MNOP,,QRST,,UVWX,,YZZZ";
905        assert_eq!(array(list, 7, ',')?, "MNOP");
906        assert_eq!(array(list, 999, ',')?, "");
907        array(list, 0, ',').unwrap_err();
908        Ok(())
909    }
910
911    #[crate::ctb_test]
912    fn test_arraycontains_exact_match() -> Result<()> {
913        let colors = "it;was;a;dark;and;stormy;night";
914        assert!(arraycontains(colors, "and", ';')?);
915        assert!(!arraycontains(colors, "And", ';')?);
916        Ok(())
917    }
918
919    #[crate::ctb_test]
920    fn test_arraychange_existing_only() -> Result<()> {
921        let colors = "it;was;a;dark;and;stormy;night";
922        let changed = arraychange(colors, "Very Fun", 6, ';')?;
923        assert_eq!(changed, "it;was;a;dark;and;Very Fun;night");
924
925        let unchanged = arraychange(colors, "X", 99, ';')?;
926        assert_eq!(unchanged, colors);
927
928        arraychange(colors, "X", 0, ';').unwrap_err();
929        Ok(())
930    }
931
932    #[crate::ctb_test]
933    fn test_arraydelete_preserves_empties() -> Result<()> {
934        let s = ",a,,b,";
935        // Elements are ["", "a", "", "b", ""]. Delete item 1 => ["a", "", "b", ""].
936        assert_eq!(arraydelete(s, 1, 1, ',')?, "a,,b,");
937        assert_eq!(arraydelete("a;b;c;d", 3, 1, ';')?, "a;b;d");
938
939        // No-op cases.
940        assert_eq!(arraydelete("a;b", 9, 1, ';')?, "a;b");
941        assert_eq!(arraydelete("a;b", 1, 0, ';')?, "a;b");
942        arraydelete("a;b", 0, 1, ';').unwrap_err();
943        Ok(())
944    }
945
946    #[crate::ctb_test]
947    fn test_arraydeduplicate_sorts() -> Result<()> {
948        assert_eq!(arraydeduplicate("b;a;b", ';')?, "a;b");
949        Ok(())
950    }
951
952    #[crate::ctb_test]
953    fn test_arrayboth_and_difference_ignore_empty() -> Result<()> {
954        let a1 = "a;;b";
955        let a2 = "b;c;";
956        assert_eq!(arrayboth(a1, a2, ';')?, "b");
957        assert_eq!(arraydifference(a1, a2, ';')?, "a");
958        Ok(())
959    }
960
961    #[crate::ctb_test]
962    fn test_arrayelement_position_to_element() -> Result<()> {
963        let s = "dark;and;stormy";
964        // Position 7 is 'n' in "and" => element 2.
965        assert_eq!(arrayelement(s, 7, ';')?, 2);
966        // If position is a separator, result is the element to the right.
967        assert_eq!(arrayelement(s, 5, ';')?, 2);
968        // Out of range positions clamp to the last element.
969        assert_eq!(arrayelement(s, 999, ';')?, 3);
970        arrayelement(s, 0, ';').unwrap_err();
971        Ok(())
972    }
973
974    #[crate::ctb_test]
975    fn test_arraycolumn() -> Result<()> {
976        let t = "a,b,c|d,e,f";
977        assert_eq!(arraycolumn(t, 2, '|', ',')?, "b|e");
978        arraycolumn(t, 0, '|', ',').unwrap_err();
979        arraycolumn("a,b|d", 2, '|', ',').unwrap_err();
980        Ok(())
981    }
982
983    #[crate::ctb_test]
984    fn test_arraydeletevalue_deletes_with_consecutive_quirk() -> Result<()> {
985        assert_eq!(arraydeletevalue("a;b;a", "a", ';')?, "b");
986        assert_eq!(arraydeletevalue("a;a", "a", ';')?, "a");
987        assert_eq!(arraydeletevalue("a;a;a", "a", ';')?, "a");
988        // Deleting the empty element removes it, collapsing the array.
989        assert_eq!(arraydeletevalue("x;;x", "", ';')?, "x;x");
990        Ok(())
991    }
992
993    #[crate::ctb_test]
994    fn test_arrayrange_inclusive_1_based() -> Result<()> {
995        assert_eq!(arrayrange("a;b;c;d", 2, 3, ';')?, "b;c");
996        assert_eq!(arrayrange("a;b;c;d", 1, 999, ';')?, "a;b;c;d");
997        assert_eq!(arrayrange("a;b;c;d", 5, 6, ';')?, "");
998        assert_eq!(arrayrange("a;b;c;d", 3, 2, ';')?, "");
999        arrayrange("a;b", 0, 1, ';').unwrap_err();
1000        Ok(())
1001    }
1002
1003    #[crate::ctb_test]
1004    fn test_arrayfirst_and_last() -> Result<()> {
1005        assert_eq!(arrayfirst(",a", ',')?, "");
1006        assert_eq!(arraylast(",a,", ',')?, "");
1007        assert_eq!(arraylast("x;y;z", ';')?, "z");
1008        Ok(())
1009    }
1010
1011    #[crate::ctb_test]
1012    fn test_arrayinsert_inserts_blanks() -> Result<()> {
1013        assert_eq!(arrayinsert("a;b;c", 3, 2, ';')?, "a;b;;;c");
1014        assert_eq!(arrayinsert("a;b", 1, 1, ';')?, ";a;b");
1015        assert_eq!(arrayinsert("a;b", 99, 2, ';')?, "a;b;;");
1016        arrayinsert("a;b", 0, 1, ';').unwrap_err();
1017        Ok(())
1018    }
1019
1020    #[crate::ctb_test]
1021    fn test_arraylefttrim_and_trim() -> Result<()> {
1022        assert_eq!(arraylefttrim("a;b;c", 2, ';')?, "c");
1023        assert_eq!(arraylefttrim("a;b", 99, ';')?, "");
1024        assert_eq!(arraytrim("a;b;c;d", 2, ';')?, "a;b");
1025        assert_eq!(arraytrim("a;b", 99, ';')?, "");
1026        Ok(())
1027    }
1028
1029    #[crate::ctb_test]
1030    fn test_arraylookup_and_reverselookup() -> Result<()> {
1031        let t = "NJ.NEW JERSEY;NY.NEW YORK;MD.MARYLAND";
1032        assert_eq!(arraylookup(t, "NY", ';', '.', "")?, "NEW YORK");
1033        assert_eq!(arraylookup(t, "ZZ", ';', '.', "X")?, "X");
1034        assert_eq!(arrayreverselookup(t, "MARYLAND", ';', '.', "")?, "MD");
1035
1036        let single = "10;20;30";
1037        assert_eq!(arraylookup(single, "20", ';', '\0', "")?, "20");
1038        Ok(())
1039    }
1040
1041    #[crate::ctb_test]
1042    fn test_arraymerge() -> Result<()> {
1043        assert_eq!(arraymerge("a;b;c", "1;2;3", ';', ":")?, "a:1;b:2;c:3");
1044        arraymerge("a;b;c", "1;2", ';', ":").unwrap_err();
1045        arraymerge("a", "b", ';', "").unwrap_err();
1046        Ok(())
1047    }
1048
1049    #[crate::ctb_test]
1050    fn test_arraynotcontains() -> Result<()> {
1051        assert!(arraynotcontains("a;b;c", "x", ';')?);
1052        assert!(!arraynotcontains("a;b;c", "b", ';')?);
1053        Ok(())
1054    }
1055
1056    #[crate::ctb_test]
1057    fn test_arraysort_and_strip_and_size() -> Result<()> {
1058        assert_eq!(arraysort("b;a;b", ';')?, "a;b;b");
1059        assert_eq!(arraystrip("a;;b;", ';')?, "a;b");
1060        assert_eq!(arraysize("", ';')?, 1);
1061        assert_eq!(arraysize("a;b", ';')?, 2);
1062        assert_eq!(arraysize(",", ',')?, 2);
1063        Ok(())
1064    }
1065
1066    #[crate::ctb_test]
1067    fn test_arraynumericsort_and_total() -> Result<()> {
1068        assert_eq!(arraynumericsort("10;2;1", ';')?, "1;2;10");
1069        assert_eq!(arraynumerictotal("1;2.5;-1", ';')?, 2.5);
1070        Ok(())
1071    }
1072
1073    #[crate::ctb_test]
1074    fn test_arrayrandomize_is_permutation() -> Result<()> {
1075        let input = "a;b;c;d;e";
1076        let out = arrayrandomize(input, ';')?;
1077        assert_ne!(out, input);
1078
1079        let mut a: Vec<&str> = input.split(';').collect();
1080        let mut b: Vec<&str> = out.split(';').collect();
1081        a.sort_unstable();
1082        b.sort_unstable();
1083        assert_eq!(a, b);
1084        Ok(())
1085    }
1086
1087    #[crate::ctb_test]
1088    fn test_arrayreplacevalue_consecutive_quirk() -> Result<()> {
1089        assert_eq!(arrayreplacevalue("a;a", "a", "x", ';')?, "x;a");
1090        assert_eq!(arrayreplacevalue("a;b;a", "a", "x", ';')?, "x;b;x");
1091        assert_eq!(arrayreplacevalue("x;;x", "", "_", ';')?, "x;_;x");
1092        Ok(())
1093    }
1094
1095    #[crate::ctb_test]
1096    fn test_arrayreverse() -> Result<()> {
1097        assert_eq!(arrayreverse("1;2;3;4", ';')?, "4;3;2;1");
1098        Ok(())
1099    }
1100
1101    #[crate::ctb_test]
1102    fn test_arraysearch_wildcards() -> Result<()> {
1103        let s = "Luisa Lee;Jack Chan;Hattie Tyler";
1104        assert_eq!(arraysearch(s, "Susan*", 1, ';')?, 0);
1105        assert_eq!(arraysearch(s, "*Tyl*", 1, ';')?, 3);
1106        assert_eq!(arraysearch(s, "L?isa Lee", 1, ';')?, 1);
1107        assert_eq!(arraysearch(s, "Nope*", 1, ';')?, 0);
1108        arraysearch(s, "*", 0, ';').unwrap_err();
1109        Ok(())
1110    }
1111
1112    #[crate::ctb_test]
1113    fn test_arraytableceiling_and_floor_numeric() -> Result<()> {
1114        let t = "10.A;20.B;30.C";
1115        assert_eq!(arraytableceiling(t, "15", ';', '.', "")?, "B");
1116        assert_eq!(arraytablefloor(t, "15", ';', '.', "")?, "A");
1117        assert_eq!(arraytableceiling(t, "20", ';', '.', "")?, "B");
1118        assert_eq!(arraytablefloor(t, "5", ';', '.', "D")?, "D");
1119        assert_eq!(arraytableceiling(t, "99", ';', '.', "D")?, "D");
1120
1121        let single = "10;20;30";
1122        assert_eq!(arraytableceiling(single, "15", ';', '\0', "")?, "20");
1123        assert_eq!(arraytablefloor(single, "15", ';', '\0', "")?, "10");
1124        Ok(())
1125    }
1126
1127    #[crate::ctb_test]
1128    fn test_arrayunpropagate() -> Result<()> {
1129        assert_eq!(arrayunpropagate("a;a;a;b;b;c", ';')?, "a;;;b;;c");
1130        Ok(())
1131    }
1132
1133    #[crate::ctb_test]
1134    fn test_makenumberedarray() -> Result<()> {
1135        assert_eq!(makenumberedarray(',', 1, 5)?, "1,2,3,4,5");
1136        assert_eq!(makenumberedarray(',', 5, 3)?, "5,4,3");
1137        Ok(())
1138    }
1139}