ctb_formats_eite/util/
string.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//! Character and string manipulation helpers for EITE formats.
21
22// ---------------
23// String char access / mutation
24// ---------------
25
26use crate::utilities::*;
27
28use anyhow::{Result, anyhow, bail};
29
30use crate::{
31    encoding::ascii::stagel_char_from_byte, util::ascii::ascii_is_digit,
32};
33
34pub fn str_char(s: &str, index: usize) -> String {
35    // Reason for fallback: when index is past the end of the string, str_char returns an empty string.
36    s.chars()
37        .nth(index)
38        .map(|c| c.to_string())
39        .unwrap_or_default()
40}
41pub fn str_char_at_pos(s: &str, index: usize) -> String {
42    str_char(s, index)
43}
44pub fn char_at_pos(s: &str, index: usize) -> String {
45    str_char(s, index)
46}
47pub fn char_at(s: &str, index: usize) -> String {
48    str_char(s, index)
49}
50
51pub fn set_char_at(s: &str, index: usize, ch: &str) -> String {
52    assert!(ch.chars().count() == 1, "Replacement must be single char");
53    let Some(replacement) = ch.chars().next() else {
54        return s.to_string();
55    };
56    s.chars()
57        .enumerate()
58        .map(|(i, c)| if i == index { replacement } else { c })
59        .collect()
60}
61
62pub fn reverse_str(s: &str) -> String {
63    s.chars().rev().collect()
64}
65
66pub fn char_to_upper(ch: &str) -> String {
67    assert!(ch.chars().count() == 1);
68    ch.to_ascii_uppercase()
69}
70
71pub fn str_to_upper(s: &str) -> String {
72    s.chars().map(|c| c.to_ascii_uppercase()).collect()
73}
74
75pub fn char_to_lower(ch: &str) -> String {
76    assert!(ch.chars().count() == 1);
77    ch.to_ascii_lowercase()
78}
79
80pub fn str_to_lower(s: &str) -> String {
81    s.chars().map(|c| c.to_ascii_lowercase()).collect()
82}
83
84pub fn str_empty(s: &str) -> bool {
85    s.is_empty()
86}
87pub fn str_nonempty(s: &str) -> bool {
88    !s.is_empty()
89}
90
91pub fn str_contains_only_int(s: &str) -> bool {
92    if s.is_empty() {
93        return true;
94    }
95    s.chars().all(|c| c.is_ascii_digit())
96}
97
98/// Index into a substring by start and lengths. Supports negative indices, but
99/// replicates an off-by-one error from the original StageL implementation: the
100/// length has to be one more than seems intuitive.
101/// `substring_bug_compatible("test", 0, -2)` would return "tes".
102pub fn substring_bug_compatible(
103    s: &str,
104    start: usize,
105    length: isize,
106) -> Result<String> {
107    if length < 0 {
108        // Negative length: JS code adjusts to (str.length + 1 + length)
109        // Example: length = -1 => take (len + 1 - 1) = len chars (effectively whole string)
110        let len_isize = isize::try_from(s.len())
111            .context("String length exceeds isize::MAX")?;
112        let adj = usize::try_from(
113            len_isize.saturating_add(1).saturating_add(length).max(0),
114        )
115        .context("Adjusted length failed conversion to usize")?;
116        Ok(s.chars().skip(start).take(adj).collect())
117    } else {
118        let take_len = usize::try_from(length)
119            .context("Length failed conversion to usize")?;
120        Ok(s.chars().skip(start).take(take_len).collect())
121    }
122}
123
124pub fn len_str(s: &str) -> usize {
125    s.len()
126}
127
128/// strReplace(str, find, replace) – JS version used String.replace with first occurrence.
129/// We replicate first occurrence behavior.
130pub fn str_replace_once(haystack: &str, find: &str, replace: &str) -> String {
131    if find.is_empty() {
132        // JS would replace empty string at position 0; we mimic inserting replace at start.
133        format!("{replace}{haystack}")
134    } else if let Some(pos) = haystack.find(find) {
135        let mut out = String::with_capacity(
136            haystack
137                .len()
138                .saturating_sub(find.len())
139                .saturating_add(replace.len()),
140        );
141        // Reason for fallback: pos returned by find() is a valid char boundary within haystack.
142        out.push_str(haystack.get(..pos).unwrap_or(""));
143        out.push_str(replace);
144        // Reason for fallback: pos + find.len() is a valid char boundary within haystack.
145        out.push_str(
146            haystack.get(pos.saturating_add(find.len())..).unwrap_or(""),
147        );
148        out
149    } else {
150        haystack.to_string()
151    }
152}
153
154// ---------------
155// Percentage formatting (3 decimals)
156// ---------------
157
158pub fn format_percentage(a: i32, b: i32) -> Result<String> {
159    if b == 0 {
160        bail!("Division by zero in percentage");
161    }
162    if a == 0 {
163        return Ok("0.000".into());
164    }
165    let pct = (f64::from(a) / f64::from(b)) * 100.0;
166    Ok(format!("{pct:.3}"))
167}
168
169/// Basic (non-escaped) split replicating the original StageL strSplit.
170/// Unlike `str.split(sep)` in many languages, this custom implementation:
171/// - Does not collapse consecutive separators
172/// - Returns trailing empty element if the input ends with the separator
173pub fn str_split(input: &str, separator: &str) -> Vec<String> {
174    if separator.is_empty() {
175        // Degenerate: behave like every char boundary (mimic original loop semantics)
176        return input.chars().map(|c| c.to_string()).collect();
177    }
178
179    let mut out = Vec::new();
180    let mut remaining = input;
181    let sep_len = separator.len();
182
183    while !remaining.is_empty() {
184        if remaining.starts_with(separator) {
185            // Push current collected (could be empty), then remove the separator
186            out.push(String::new());
187            // Reason for fallback: starts_with check on line 161 guarantees remaining length >= sep_len.
188            remaining = remaining.get(sep_len..).unwrap_or("");
189        } else {
190            // Consume one character
191            let mut char_indices = remaining.char_indices();
192            let Some((_, _first_char)) = char_indices.next() else {
193                // I don't think we could ever hit this branch because it's in a !remaining.is_empty() loop.
194                unreachable!();
195            };
196            // Reason for fallback: next_index is bounded by remaining.len() from char_indices iteration.
197            let next_index =
198                char_indices.next().map_or(remaining.len(), |(i, _)| i);
199            // Reason for fallback: next_index is a valid char boundary within remaining.
200            let ch_str = remaining.get(..next_index).unwrap_or("");
201            // We append the char to a "current" token: emulate original incremental building.
202            if let Some(last_token) = out.last_mut() {
203                last_token.push_str(ch_str);
204            } else {
205                out.push(ch_str.to_string());
206            }
207            // Reason for fallback: next_index is a valid char boundary within remaining.
208            remaining = remaining.get(next_index..).unwrap_or("");
209        }
210    }
211
212    // Ensure leading separator case:
213    if input.starts_with(separator) {
214        out.insert(0, String::new());
215    }
216
217    out
218}
219
220/// Escape-aware split:
221///
222/// Original logic (strSplitEscaped):
223/// - First performs a plain split.
224/// - Iterates segments; if a segment ends with a backslash (escape char) and there
225///   is a following segment, it replaces the trailing backslash with the separator
226///   and concatenates the next segment to it, continuing (effectively treating the
227///   separator as a literal).
228/// - A dangling trailing backslash (no following segment) is preserved as-is.
229pub fn str_split_escaped(input: &str, separator: &str) -> Vec<String> {
230    ctb_utilities::string::split_escaped(input, separator)
231}
232
233/// Convenience wrappers retained for compatibility naming.
234pub fn str_split_esc(input: &str, separator: &str) -> Vec<String> {
235    str_split_escaped(input, separator)
236}
237
238pub fn explode_esc(input: &str, separator: &str) -> Vec<String> {
239    str_split_escaped(input, separator)
240}
241pub fn explode_escaped(input: &str, separator: &str) -> Vec<String> {
242    str_split_escaped(input, separator)
243}
244
245/// Join with escaping: occurrences of the separator in any element are preceded
246/// by a backslash. A separator is appended after each element (trailing).
247pub fn str_join_escaped(parts: &[String], separator: &str) -> String {
248    if parts.is_empty() {
249        return String::new();
250    }
251    let mut out = String::new();
252    for p in parts {
253        let escaped = p.replace(separator, &format!("\\{separator}"));
254        out.push_str(&escaped);
255        out.push_str(separator);
256    }
257    out
258}
259
260/// Convenience wrapper.
261pub fn str_join_esc(parts: &[String], separator: &str) -> String {
262    str_join_escaped(parts, separator)
263}
264
265/// Join escaped but remove trailing separator.
266pub fn str_join_esc_no_trailing(parts: &[String], separator: &str) -> String {
267    let joined = str_join_escaped(parts, separator);
268    if joined.ends_with(separator) {
269        let cut = joined.len().saturating_sub(separator.len());
270        // Reason for fallback: ends_with check on line 241 guarantees cut is a valid boundary.
271        joined.get(..cut).unwrap_or("").to_string()
272    } else {
273        joined
274    }
275}
276
277/// Parse a space-delimited string of decimal integers (the inverse of `str_print_arr<int>`).
278/// Accepts optional trailing space. Rejects any non-digit / non-space characters.
279pub fn int_arr_from_str_printed_arr(s: &str) -> Result<Vec<u32>> {
280    let mut current = String::new();
281    let mut out = Vec::new();
282
283    for b in s.bytes() {
284        if b == b' ' {
285            if !current.is_empty() {
286                out.push(
287                    current
288                        .parse::<u32>()
289                        .map_err(|e| anyhow!("parse int: {e}"))?,
290                );
291                current.clear();
292            }
293        } else if ascii_is_digit(b) {
294            let char = stagel_char_from_byte(b)?;
295            current.push_str(&char.clone());
296        } else {
297            return Err(anyhow!(
298                "Unexpected character (byte {b}) in int_arr_from_str_printed_arr"
299            ));
300        }
301    }
302    if !current.is_empty() {
303        out.push(
304            current
305                .parse::<u32>()
306                .map_err(|e| anyhow!("parse int: {e}"))?,
307        );
308    }
309    Ok(out)
310}
311
312/// Convert string to vector of raw bytes (0..=255) treating each char's codepoint (0..=255).
313/// For bytes above ASCII range, the direct low-byte value of the char is used (mirroring JS charCodeAt & 0xFF).
314pub fn str_to_byte_array(s: &str) -> Result<Vec<u8>> {
315    s.chars()
316        .map(|c| {
317            u8::try_from(u32::from(c) & 0xFF)
318                .context("Failed to convert character codepoint to u8")
319        })
320        .collect()
321}
322
323/// Build a string from raw bytes (each byte -> U+00XX).
324pub fn str_from_byte_array(bytes: &[u8]) -> String {
325    bytes.iter().map(|b| char::from(*b)).collect()
326}
327
328#[cfg(test)]
329#[allow(
330    clippy::panic,
331    clippy::expect_used,
332    clippy::unwrap_used,
333    clippy::unwrap_in_result,
334    clippy::panic_in_result_fn,
335    clippy::indexing_slicing,
336    clippy::arithmetic_side_effects,
337    reason = "Standard repository test boilerplate"
338)]
339mod tests {
340    use super::*;
341
342    #[crate::ctb_test]
343    fn test_substring_bug_compatible_behavior() -> Result<()> {
344        let s = "abcdef";
345        assert_eq!(substring_bug_compatible(s, 0, 3)?, "abc");
346        assert_eq!(substring_bug_compatible(s, 2, 2)?, "cd");
347        // Negative length example (len=6): length=-1 => take len+1-1 = 5 chars from start
348        assert_eq!(substring_bug_compatible(s, 0, -1)?, "abcdef");
349        assert_eq!(substring_bug_compatible(s, 0, -2)?, "abcde");
350        Ok(())
351    }
352
353    #[crate::ctb_test]
354    fn test_char_mutation() {
355        let s = "hello";
356        let s2 = set_char_at(s, 1, "A");
357        assert_eq!(s2, "hAllo");
358        assert_eq!(reverse_str("abc"), "cba");
359    }
360
361    #[crate::ctb_test]
362    fn test_case_conversion() {
363        assert_eq!(char_to_upper("a"), "A");
364        assert_eq!(str_to_upper("Abc!"), "ABC!");
365        assert_eq!(char_to_lower("Q"), "q");
366        assert_eq!(str_to_lower("AbC"), "abc");
367    }
368
369    #[crate::ctb_test]
370    fn test_str_contains_only_int() {
371        assert!(str_contains_only_int("12345"));
372        assert!(!str_contains_only_int("12a45"));
373    }
374
375    #[crate::ctb_test]
376    fn test_format_percentage() {
377        let p = format_percentage(1, 2).unwrap();
378        assert_eq!(p, "50.000"); // 1/2 * 100
379        let p = format_percentage(1, 3).unwrap();
380        assert_eq!(p, "33.333"); // 1/3 * 100
381        let p = format_percentage(2, 3).unwrap();
382        assert_eq!(p, "66.667"); // 2/3 * 100
383    }
384
385    #[crate::ctb_test]
386    fn test_str_split_basic() {
387        assert_eq!(
388            str_split("a,b,c", ","),
389            Vec::<String>::from(vec!["a".into(), "b".into(), "c".into()])
390        );
391        assert_eq!(
392            str_split("a,b,c,", ","),
393            Vec::<String>::from(vec![
394                "a".into(),
395                "b".into(),
396                "c".into(),
397                "".into()
398            ])
399        );
400        assert_eq!(str_split("", ","), Vec::<String>::new());
401
402        assert_eq!(
403            str_split("aabbabc", "ab"),
404            Vec::<String>::from(vec!["a".into(), "b".into(), "c".into()])
405        );
406        assert_eq!(
407            str_split("aabbabcab", "ab"),
408            Vec::<String>::from(vec![
409                "a".into(),
410                "b".into(),
411                "c".into(),
412                "".into()
413            ])
414        );
415        assert_eq!(
416            str_split("abc", "ab"),
417            Vec::<String>::from(vec!["".into(), "c".into()])
418        );
419        assert_eq!(
420            str_split("ababbaa", "ab"),
421            Vec::<String>::from(vec!["".into(), "".into(), "baa".into()])
422        );
423        assert_eq!(
424            str_split("aab", "ab"),
425            Vec::<String>::from(vec!["a".into(), "".into()])
426        );
427        assert_eq!(
428            str_split("abaab", "ab"),
429            Vec::<String>::from(vec!["".into(), "a".into(), "".into()])
430        );
431        assert_eq!(
432            str_split("abaabab", "ab"),
433            Vec::<String>::from(vec![
434                "".into(),
435                "a".into(),
436                "".into(),
437                "".into()
438            ])
439        );
440        assert_eq!(
441            str_split("abab", "ab"),
442            Vec::<String>::from(vec!["".into(), "".into(), "".into()])
443        );
444        assert_eq!(
445            str_split("ab", "ab"),
446            Vec::<String>::from(vec!["".into(), "".into()])
447        );
448        assert_eq!(
449            str_split(str_split("abab", "ab").join("ab").as_str(), "ab"),
450            Vec::<String>::from(vec!["".into(), "".into(), "".into()])
451        );
452    }
453
454    #[crate::ctb_test]
455    fn test_str_split_escaped() {
456        // "a\,b" should decode to ["a,b"]
457        let v = str_split_escaped(r"a\,b", ",");
458        assert_eq!(v, vec!["a,b".to_string()]);
459        // Mixed
460        let v2 = str_split_escaped(r"a\,b,c", ",");
461        assert_eq!(v2, vec!["a,b".to_string(), "c".to_string()]);
462        // Escaped separator joining multiple times
463        let v3 = str_split_escaped(r"a\,b\,c,d", ",");
464        assert_eq!(v3, vec!["a,b,c".to_string(), "d".to_string()]);
465    }
466
467    #[crate::ctb_test]
468    fn test_str_join_escaped() {
469        let joined = str_join_escaped(&["a,b".into(), "c".into()], ",");
470        // trailing comma per design
471        assert_eq!(joined, r"a\,b,c,");
472
473        let no_trailing =
474            str_join_esc_no_trailing(&["a,b".into(), "c".into()], ",");
475        assert_eq!(no_trailing, r"a\,b,c");
476    }
477
478    #[crate::ctb_test]
479    fn test_int_arr_from_str_printed_arr() {
480        let v = int_arr_from_str_printed_arr("1 2 3 ").unwrap();
481        assert_eq!(v, vec![1, 2, 3]);
482
483        let v2 = int_arr_from_str_printed_arr("10 20 30").unwrap();
484        assert_eq!(v2, vec![10, 20, 30]);
485
486        // invalid char
487        assert!(int_arr_from_str_printed_arr("1 a 3").is_err());
488    }
489
490    #[crate::ctb_test]
491    fn test_str_to_from_byte_array_roundtrip() -> Result<()> {
492        let s = "ABC";
493        let bytes = str_to_byte_array(s)?;
494        assert_eq!(bytes, vec![65, 66, 67]);
495        let s2 = str_from_byte_array(&bytes);
496        assert_eq!(s2, s);
497        Ok(())
498    }
499}