ctb_formats_eite/util/
array.rs

1// SPDX-License-Identifier: AGPL-3.0-or-later
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
7This program is free software: you can redistribute it and/or modify it under
8the terms of the GNU Affero General Public License as published by the Free
9Software Foundation, either version 3 of the License, or (at your option) any
10later version.
11
12This program is distributed in the hope that it will be useful, but WITHOUT ANY
13WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
14A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more details.
15
16You should have received a copy of the GNU Affero General Public License along
17with this program.  If not, see <https://www.gnu.org/licenses/>.
18*/
19
20//! Array utilities
21
22#[allow(
23    unused_imports,
24    clippy::wildcard_imports,
25    reason = "Standard workspace module prelude"
26)]
27use crate::utilities::*;
28
29pub fn arr_empty<T>(a: &[T]) -> bool {
30    a.is_empty()
31}
32pub fn arr_nonempty<T>(a: &[T]) -> bool {
33    !a.is_empty()
34}
35
36pub fn arr_eq<T: PartialEq>(a: &[T], b: &[T]) -> bool {
37    if a.len() != b.len() {
38        return false;
39    }
40    a.iter().zip(b).all(|(x, y)| x == y)
41}
42
43/// count(array)
44pub fn count<T>(a: &[T]) -> usize {
45    a.len()
46}
47
48pub fn append_vec<T: Clone>(a: &[T], b: &[T]) -> Vec<T> {
49    let mut out = Vec::with_capacity(a.len().saturating_add(b.len()));
50    out.extend_from_slice(a);
51    out.extend_from_slice(b);
52    out
53}
54
55pub fn js_compat_array_slice<T: Clone>(
56    a: &[T],
57    start: i64,
58    end_exclusive: i64,
59) -> Result<Option<Vec<T>>> {
60    let len =
61        i64::try_from(a.len()).context("Array length exceeds i64::MAX")?;
62
63    // Convert negative indices relative to length
64    let mut s = if start < 0 {
65        len.saturating_add(start)
66    } else {
67        start
68    };
69    let mut e = if end_exclusive < 0 {
70        len.saturating_add(end_exclusive)
71    } else {
72        end_exclusive
73    };
74
75    // Clamp to [0, len]
76    if s < 0 {
77        s = 0;
78    }
79    if e < 0 {
80        e = 0;
81    }
82    if s > len {
83        s = len;
84    }
85    if e > len {
86        e = len;
87    }
88
89    // If end <= start return empty vec (JS slice returns empty array)
90    if e <= s {
91        return Ok(None);
92    }
93
94    let s_u =
95        usize::try_from(s).context("Start index failed conversion to usize")?;
96    let e_u =
97        usize::try_from(e).context("End index failed conversion to usize")?;
98    let slice = a.get(s_u..e_u).context("Slice range out of bounds")?;
99
100    Ok(Some(slice.to_vec()))
101}
102
103/// Close translation of StageL anSubset.
104pub fn subset<T: Clone>(
105    a: &[T],
106    mut start: i64,
107    mut end: i64,
108) -> Result<Option<Vec<T>>> {
109    let count_len =
110        i64::try_from(a.len()).context("Array length exceeds i64::MAX")?;
111
112    if start < 0 {
113        start = start.saturating_add(count_len);
114    }
115    if end < 0 {
116        end = end.saturating_add(count_len);
117    }
118
119    /* Copilot suggests:
120       if start < 0 || end > len || start > end {
121           return None;
122       }
123
124       let mut res = Vec::new();
125       let mut i = start;
126
127       while i < end {
128           // Safe to call `a.get(i as usize)` because of the bounds check above.
129           if let Some(item) = a.get(i as usize) {
130               res.push(item.clone());
131           } else {
132               // This should not happen because of the bounds check, but just in case
133               return None;
134           }
135           i += 1;
136       }
137
138       Some(res)
139    */
140
141    let end_count = end;
142    let mut res: Vec<T> = Vec::new();
143
144    let mut i = i128::from(start);
145    let count_i128 = i128::from(end_count);
146    while i <= count_i128 {
147        let u_idx =
148            usize::try_from(i).context("Index failed conversion to usize")?;
149        if let Some(item) = a.get(u_idx) {
150            res.push(item.clone());
151        } else {
152            return Ok(None);
153        }
154        i = i.saturating_add(1);
155    }
156
157    Ok(Some(res))
158}
159
160/// JS pop(array) -> subset(array, 0, -2) meaning drop last element.
161/// We replicate safe behavior (no negative wrap).
162#[expect(
163    clippy::expect_used,
164    reason = "non-empty slice check guarantees a.len() - 1 is within slice bounds"
165)]
166pub fn pop<T: Clone>(a: &[T]) -> Vec<T> {
167    if a.is_empty() {
168        Vec::new()
169    } else {
170        a.get(..a.len().saturating_sub(1))
171            .expect("non-empty slice guarantees a.len() - 1 is in bounds")
172            .to_vec()
173    }
174}
175
176/// shift(array) -> subset(array, 1, -1) => drop first element
177#[expect(
178    clippy::expect_used,
179    reason = "slice length check > 1 guarantees index 1 is within slice bounds"
180)]
181pub fn shift<T: Clone>(a: &[T]) -> Vec<T> {
182    if a.len() <= 1 {
183        Vec::new()
184    } else {
185        a.get(1..)
186            .expect("slice length > 1 guarantees index 1 is in bounds")
187            .to_vec()
188    }
189}
190
191/// first(array)
192pub fn first<T: Clone>(a: &[T]) -> Option<T> {
193    a.first().cloned()
194}
195
196/// last(array)
197pub fn last<T: Clone>(a: &[T]) -> Option<T> {
198    a.last().cloned()
199}
200
201/// setElement(array, index, value) – panics if out of range except allowing
202/// index == len (append) in the original? JS code forbade index > length.
203/// If index == len we append.
204pub fn set_element<T: Clone>(
205    a: &mut Vec<T>,
206    index: isize,
207    value: T,
208) -> Result<()> {
209    let len =
210        isize::try_from(a.len()).context("Array length exceeds isize::MAX")?;
211    let mut idx = index;
212    if idx < 0 {
213        idx = idx.saturating_add(len);
214    }
215    if idx < 0 || idx > len {
216        bail!(
217            "Cannot insert at position {index} greater than appending to the length of the array."
218        );
219    }
220    if idx == len {
221        a.push(value);
222    } else {
223        let u_idx = usize::try_from(idx).context("Index is negative")?;
224        let elem = a.get_mut(u_idx).context("Index out of bounds")?;
225        *elem = value;
226    }
227    Ok(())
228}
229
230// ===============
231// SUBSET HELPERS (abSubset / anSubset / asSubset)
232// These treat the end as inclusive, and allow negative indexes.
233// ===============
234
235fn normalize_bounds(
236    len: usize,
237    start: isize,
238    end: isize,
239) -> Result<(usize, usize)> {
240    let l = isize::try_from(len).context("Array length exceeds isize::MAX")?;
241    let s = if start < 0 {
242        l.saturating_add(start)
243    } else {
244        start
245    };
246    let e = if end < 0 { l.saturating_add(end) } else { end };
247    let s = s.clamp(0, l.max(0));
248    let e = e.clamp(0, l.max(0));
249    let s_u =
250        usize::try_from(s).context("Start index failed conversion to usize")?;
251    let e_u =
252        usize::try_from(e).context("End index failed conversion to usize")?;
253    Ok((s_u, e_u))
254}
255
256pub fn slice_inclusive_bool(
257    a: &[bool],
258    start: isize,
259    end: isize,
260) -> Result<Vec<bool>> {
261    if a.is_empty() {
262        return Ok(Vec::new());
263    }
264    let (s, e) = normalize_bounds(a.len(), start, end)?;
265    if e < s {
266        return Ok(Vec::new());
267    }
268    let slice = a
269        .get(s..=e.min(a.len().saturating_sub(1)))
270        .context("Slice range out of bounds")?;
271    Ok(slice.to_vec())
272}
273
274pub fn slice_inclusive_i32(
275    a: &[i32],
276    start: isize,
277    end: isize,
278) -> Result<Vec<i32>> {
279    if a.is_empty() {
280        return Ok(Vec::new());
281    }
282    let (s, e) = normalize_bounds(a.len(), start, end)?;
283    if e < s {
284        return Ok(Vec::new());
285    }
286    let slice = a
287        .get(s..=e.min(a.len().saturating_sub(1)))
288        .context("Slice range out of bounds")?;
289    Ok(slice.to_vec())
290}
291
292pub fn slice_inclusive_string(
293    a: &[String],
294    start: isize,
295    end: isize,
296) -> Result<Vec<String>> {
297    if a.is_empty() {
298        return Ok(Vec::new());
299    }
300    let (s, e) = normalize_bounds(a.len(), start, end)?;
301    if e < s {
302        return Ok(Vec::new());
303    }
304    let slice = a
305        .get(s..=e.min(a.len().saturating_sub(1)))
306        .context("Slice range out of bounds")?;
307    Ok(slice.to_vec())
308}
309
310/// Convert a single primitive into a one-element array (abFromB / anFromN / asFromS).
311pub fn one_bool(b: bool) -> Vec<bool> {
312    vec![b]
313}
314pub fn one_i32(n: i32) -> Vec<i32> {
315    vec![n]
316}
317pub fn one_string(s: impl Into<String>) -> Vec<String> {
318    vec![s.into()]
319}
320
321/// contains(genericArrayIn, genericValue) – specialized to strings & ints for now.
322/// For a more dynamic approach we'd pass `Vec<Value>` and a Value.
323/// We implement a generic helper where T: `PartialEq`.
324pub fn contains<T: PartialEq>(a: &[T], needle: &T) -> bool {
325    a.iter().any(|v| v == needle)
326}
327
328pub fn index_of<T: PartialEq>(a: &[T], needle: &T) -> Result<isize> {
329    for (i, v) in a.iter().enumerate() {
330        if v == needle {
331            return isize::try_from(i).context("Index exceeds isize::MAX");
332        }
333    }
334    Ok(-1)
335}
336
337// ---------------
338// Printing arrays (space-delimited)
339// ---------------
340
341pub fn str_print_arr<T: ToString>(arr: &[T]) -> String {
342    arr.iter()
343        .map(std::string::ToString::to_string)
344        .collect::<Vec<_>>()
345        .join(" ")
346}
347
348/// Wrapper kept for compatibility: `print_array` -> `str_print_arr`
349pub fn print_array<T: ToString>(arr: &[T]) -> String {
350    str_print_arr(arr)
351}
352
353/// Wrapper kept for compatibility: `str_print_array` -> `str_print_arr`
354pub fn str_print_array<T: ToString>(arr: &[T]) -> String {
355    str_print_arr(arr)
356}
357
358/// Wrapper kept for compatibility: `print_arr` -> `str_print_arr`
359pub fn print_arr<T: ToString>(arr: &[T]) -> String {
360    str_print_arr(arr)
361}
362
363// ---------------
364// Summation
365// ---------------
366
367pub fn sum_array(a: &[i32]) -> i32 {
368    a.iter().copied().sum()
369}
370
371#[cfg(test)]
372#[allow(
373    clippy::panic,
374    clippy::expect_used,
375    clippy::unwrap_used,
376    clippy::unwrap_in_result,
377    clippy::panic_in_result_fn,
378    clippy::indexing_slicing,
379    clippy::arithmetic_side_effects,
380    reason = "Standard repository test boilerplate"
381)]
382mod tests {
383    use super::*;
384
385    #[crate::ctb_test]
386    fn test_slice_inclusive() -> Result<()> {
387        let v = vec![1, 2, 3, 4, 5];
388        assert_eq!(slice_inclusive_i32(&v, 1, 3)?, vec![2, 3, 4]);
389        assert_eq!(slice_inclusive_i32(&v, -3, -1)?, vec![3, 4, 5]);
390        assert_eq!(slice_inclusive_i32(&v, 0, 0)?, vec![1]);
391        Ok(())
392    }
393
394    #[crate::ctb_test]
395    fn test_contains() {
396        let v = vec![String::from("a"), String::from("b")];
397        assert!(contains(&v, &"a".to_string()));
398        assert!(!contains(&v, &"c".to_string()));
399    }
400
401    // PART 2
402
403    #[crate::ctb_test]
404    fn test_index_of() -> Result<()> {
405        let v = vec![1, 2, 3];
406        assert_eq!(index_of(&v, &2)?, 1);
407        assert_eq!(index_of(&v, &4)?, -1);
408        Ok(())
409    }
410
411    #[crate::ctb_test]
412    fn test_arr_eq() {
413        assert!(arr_eq(&[1, 2, 3], &[1, 2, 3]));
414        assert!(!arr_eq(&[1, 2], &[1, 2, 3]));
415    }
416
417    #[crate::ctb_test]
418    fn test_sum_array() {
419        assert_eq!(sum_array(&[1, 2, 3, 4]), 10);
420    }
421}