ctb_formats_pan/
string.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 string formatting and slicing helpers.
27
28#[allow(
29    unused_imports,
30    clippy::wildcard_imports,
31    reason = "Standard workspace module prelude"
32)]
33use crate::utilities::*;
34
35/// Funnel-style substring extraction helpers.
36pub mod funnel;
37/// Numeric string helpers.
38pub mod numeric;
39/// Numeric formatting with Pan pattern syntax.
40pub mod pattern;
41/// Additional string manipulation helpers.
42pub mod stringmod;
43
44/// Concatenates two strings.
45pub fn cat(left: &str, right: &str) -> String {
46    let mut out = String::with_capacity(left.len().saturating_add(right.len()));
47    out.push_str(left);
48    out.push_str(right);
49    out
50}
51
52/// Wraps `root` with `prefix` and `suffix` when `root` is non-empty.
53/// For example: a, b, c -> "abc"; a, "", c -> "".
54pub fn sandwich(prefix: &str, root: &str, suffix: &str) -> String {
55    if root.is_empty() {
56        return String::new();
57    }
58
59    let mut out = String::with_capacity(
60        prefix
61            .len()
62            .saturating_add(root.len())
63            .saturating_add(suffix.len()),
64    );
65    out.push_str(prefix);
66    out.push_str(root);
67    out.push_str(suffix);
68    out
69}
70
71/// Repeats `text` `count` times.
72pub fn rep(text: &str, count: usize) -> String {
73    let mut out = String::with_capacity(text.len().saturating_mul(count));
74    for _ in 0..count {
75        out.push_str(text);
76    }
77    out
78}
79
80fn byte_index_at_char(s: &str, char_pos: usize) -> usize {
81    let mut it = s.char_indices();
82    if let Some((idx, _)) = it.nth(char_pos) {
83        return idx;
84    }
85    s.len()
86}
87
88#[expect(
89    clippy::expect_used,
90    reason = "start_b and end_b are valid character boundary byte indices <= s.len()"
91)]
92fn slice_chars(s: &str, start_char: usize, len_chars: usize) -> String {
93    if len_chars == 0 {
94        return String::new();
95    }
96
97    let start_b = byte_index_at_char(s, start_char);
98    let end_b = byte_index_at_char(s, start_char.saturating_add(len_chars));
99    s.get(start_b..end_b)
100        .expect("start_b and end_b are valid char boundaries <= s.len()")
101        .to_string()
102}
103
104#[expect(
105    clippy::expect_used,
106    reason = "start_b is a valid character boundary byte index <= s.len()"
107)]
108fn slice_chars_from(s: &str, start_char: usize) -> String {
109    let start_b = byte_index_at_char(s, start_char);
110    s.get(start_b..)
111        .expect("start_b is a valid char boundary <= s.len()")
112        .to_string()
113}
114
115#[expect(
116    clippy::expect_used,
117    reason = "end_b is a valid character boundary byte index <= s.len()"
118)]
119fn slice_chars_to(s: &str, end_char: usize) -> String {
120    let end_b = byte_index_at_char(s, end_char);
121    s.get(..end_b)
122        .expect("end_b is a valid char boundary <= s.len()")
123        .to_string()
124}
125
126/// Returns the substring after the first occurrence of `tag`.
127///
128/// Returns an empty string if `tag` is empty or not found.
129#[expect(
130    clippy::expect_used,
131    reason = "start = pos + tag.len() is a valid character boundary byte index <= text.len()"
132)]
133pub fn after(text: &str, tag: &str) -> String {
134    if tag.is_empty() {
135        return String::new();
136    }
137    let Some(pos) = text.find(tag) else {
138        return String::new();
139    };
140    let start = pos.saturating_add(tag.len());
141    text.get(start..)
142        .expect("start is a valid char boundary <= text.len()")
143        .to_string()
144}
145
146#[expect(
147    clippy::expect_used,
148    reason = "pos from text.find(tag) is a valid character boundary byte index <= text.len()"
149)]
150pub fn before(text: &str, tag: &str) -> String {
151    if tag.is_empty() {
152        return String::new();
153    }
154    let Some(pos) = text.find(tag) else {
155        return String::new();
156    };
157    text.get(..pos)
158        .expect("pos is a valid char boundary <= text.len()")
159        .to_string()
160}
161
162/// Returns the first line split by `\n`.
163pub fn firstline(text: &str) -> String {
164    let mut it = text.split('\n');
165    if let Some(first) = it.next() {
166        return first.to_string();
167    }
168    String::new()
169}
170
171/// Returns the last line split by `\n`.
172pub fn lastline(text: &str) -> String {
173    let mut it = text.rsplit('\n');
174    if let Some(last) = it.next() {
175        return last.to_string();
176    }
177    String::new()
178}
179
180/// Returns the last whitespace-delimited word.
181pub fn lastword(text: &str) -> String {
182    let mut it = text.split_whitespace();
183    if let Some(last) = it.next_back() {
184        return last.to_string();
185    }
186    String::new()
187}
188
189/// Returns the leftmost `len` characters.
190pub fn left(text: &str, len: usize) -> String {
191    let total = text.chars().count();
192    slice_chars(text, 0, len.min(total))
193}
194
195/// Returns `len` characters starting at the 1-based `start` position.
196pub fn mid(text: &str, start: usize, len: usize) -> String {
197    let Some(start0) = start.checked_sub(1) else {
198        return String::new();
199    };
200    let total = text.chars().count();
201    if start0 >= total {
202        return String::new();
203    }
204    slice_chars(text, start0, len.min(total.saturating_sub(start0)))
205}
206
207/// Returns the 1-based line number `num`, or empty if missing.
208pub fn nthline(text: &str, num: usize) -> String {
209    if num == 0 {
210        return String::new();
211    }
212    let mut it = text.split('\n');
213    let idx = num.saturating_sub(1);
214    if let Some(line) = it.nth(idx) {
215        return line.to_string();
216    }
217    String::new()
218}
219
220/// Returns the 1-based word number `num`, or empty if missing.
221pub fn nthword(text: &str, num: usize) -> String {
222    if num == 0 {
223        return String::new();
224    }
225    let mut it = text.split_whitespace();
226    let idx = num.saturating_sub(1);
227    if let Some(word) = it.nth(idx) {
228        return word.to_string();
229    }
230    String::new()
231}
232
233/// Removes `prefix` when present.
234pub fn removeprefix(text: &str, prefix: &str) -> String {
235    if let Some(rest) = text.strip_prefix(prefix) {
236        return rest.to_string();
237    }
238    text.to_string()
239}
240
241/// Removes `suffix` when present.
242pub fn removesuffix(text: &str, suffix: &str) -> String {
243    if let Some(rest) = text.strip_suffix(suffix) {
244        return rest.to_string();
245    }
246    text.to_string()
247}
248
249/// Returns the rightmost `len` characters.
250pub fn right(text: &str, len: usize) -> String {
251    let total = text.chars().count();
252    if len >= total {
253        return text.to_string();
254    }
255    let start = total.saturating_sub(len);
256    slice_chars_from(text, start)
257}
258
259/// Removes a slice starting at the 0-based `startposition`.
260///
261/// A `count` of -1 removes to the end; non-positive counts are no-ops.
262pub fn snip(text: &str, startposition: usize, count: i64) -> String {
263    let total = text.chars().count();
264    if startposition >= total {
265        return text.to_string();
266    }
267
268    if count == -1 {
269        return slice_chars_to(text, startposition);
270    }
271    if count <= 0 {
272        return text.to_string();
273    }
274
275    let Ok(count_usize) = usize::try_from(count) else {
276        return text.to_string();
277    };
278
279    let prefix = slice_chars_to(text, startposition);
280    let suffix =
281        slice_chars_from(text, startposition.saturating_add(count_usize));
282    cat(&prefix, &suffix)
283}
284
285/// Returns the substring after `tag`, or `text` when not found.
286#[expect(
287    clippy::expect_used,
288    reason = "start = pos + tag.len() is a valid character boundary byte index <= text.len()"
289)]
290pub fn textafter(text: &str, tag: &str) -> String {
291    if tag.is_empty() {
292        return text.to_string();
293    }
294    let Some(pos) = text.find(tag) else {
295        return text.to_string();
296    };
297    let start = pos.saturating_add(tag.len());
298    text.get(start..)
299        .expect("start is a valid char boundary <= text.len()")
300        .to_string()
301}
302
303#[expect(
304    clippy::expect_used,
305    reason = "pos from text.find(tag) is a valid character boundary byte index <= text.len()"
306)]
307pub fn textbefore(text: &str, tag: &str) -> String {
308    if tag.is_empty() {
309        return text.to_string();
310    }
311    let Some(pos) = text.find(tag) else {
312        return text.to_string();
313    };
314    text.get(..pos)
315        .expect("pos is a valid char boundary <= text.len()")
316        .to_string()
317}
318
319/// Removes `len` characters from the end of `text`.
320pub fn trim(text: &str, len: usize) -> String {
321    let total = text.chars().count();
322    if len >= total {
323        return String::new();
324    }
325    slice_chars(text, 0, total.saturating_sub(len))
326}
327
328/// Removes `len` characters from the start of `text`.
329pub fn trimleft(text: &str, len: usize) -> String {
330    let total = text.chars().count();
331    if len >= total {
332        return String::new();
333    }
334    slice_chars_from(text, len)
335}
336
337/// Returns the number of Unicode scalar values in `text`.
338pub fn length(text: &str) -> usize {
339    text.chars().count()
340}
341
342/// Returns the number of `\n`-delimited lines.
343pub fn linecount(text: &str) -> usize {
344    if text.is_empty() {
345        return 0;
346    }
347    text.split('\n').count()
348}
349
350fn parse_ranges(therange: &str) -> Vec<(char, char)> {
351    let mut out = Vec::new();
352    let mut it = therange.chars();
353    loop {
354        let Some(a) = it.next() else { break };
355        let Some(b) = it.next() else { break };
356        if a <= b {
357            out.push((a, b));
358        } else {
359            out.push((b, a));
360        }
361    }
362    out
363}
364
365/// Returns true if any character is within the range pairs.
366/// For instance, "`AZaz`" means 'A'..='Z' and 'a'..='z'.
367pub fn rangecontains(thetext: &str, therange: &str) -> bool {
368    let ranges = parse_ranges(therange);
369    for ch in thetext.chars() {
370        for (lo, hi) in ranges.iter().copied() {
371            if ch >= lo && ch <= hi {
372                return true;
373            }
374        }
375    }
376    false
377}
378
379/// Returns true if every character is within the range pairs.
380/// For instance, "`AZaz`" means 'A'..='Z' and 'a'..='z'.
381pub fn rangematch(text: &str, therange: &str) -> bool {
382    let ranges = parse_ranges(therange);
383    for ch in text.chars() {
384        let mut ok = false;
385        for (lo, hi) in ranges.iter().copied() {
386            if ch >= lo && ch <= hi {
387                ok = true;
388                break;
389            }
390        }
391        if !ok {
392            return false;
393        }
394    }
395    true
396}
397
398/// Returns the 1-based character index of `phrase`, or 0 if missing.
399#[expect(
400    clippy::expect_used,
401    reason = "byte_pos from text.find(phrase) is a valid character boundary byte index <= text.len()"
402)]
403pub fn search(text: &str, phrase: &str) -> usize {
404    if phrase.is_empty() {
405        return 0;
406    }
407    let Some(byte_pos) = text.find(phrase) else {
408        return 0;
409    };
410
411    let prefix = text
412        .get(..byte_pos)
413        .expect("byte_pos is a valid char boundary <= text.len()");
414    prefix.chars().count().saturating_add(1)
415}
416
417/// Returns the number of whitespace-delimited words.
418pub fn wordcount(text: &str) -> usize {
419    text.split_whitespace().count()
420}
421
422/// Returns true if `substring` is present in `text`.
423pub fn contains(text: &str, substring: &str) -> bool {
424    text.contains(substring)
425}
426
427#[cfg(test)]
428#[allow(
429    clippy::panic,
430    clippy::expect_used,
431    clippy::unwrap_used,
432    clippy::unwrap_in_result,
433    clippy::panic_in_result_fn,
434    clippy::indexing_slicing,
435    clippy::arithmetic_side_effects,
436    reason = "Standard repository test boilerplate"
437)]
438mod tests {
439    use super::*;
440
441    #[crate::ctb_test]
442    fn test_string_utils() {
443        // basic concatenation and repeat
444        let result = cat("Hello, ", "world!");
445        assert_eq!(result, "Hello, world!");
446        assert_eq!("*****", rep("*", 5));
447
448        // sandwich behavior
449        assert_eq!(", foo", sandwich(", ", "foo", ""));
450        assert_eq!("", sandwich(", ", "", ""));
451        assert_eq!(" (foo)", sandwich(" (", "foo", ")"));
452        assert_eq!("", sandwich(" (", "", ")"));
453
454        // slices and lines
455        assert_eq!("ef", after("abcdef", "cd"));
456        assert_eq!("", after("abcdef", "")); // empty tag -> empty string
457        assert_eq!("ab", before("abcdef", "cd"));
458        assert_eq!("", before("abcdef", "")); // empty tag -> empty string
459        assert_eq!("abc", firstline("abc\ndef\nghi"));
460        assert_eq!("ghi", lastline("abc\ndef\nghi"));
461        assert_eq!("ghi", lastword("abc\nde f\nghi"));
462
463        // aware character operations
464        assert_eq!("аб", left("абвг", 2)); // Cyrillic characters
465        assert_eq!("fghi", mid("abcdefghijk", 6, 4));
466        assert_eq!("", mid("abc", 0, 2)); // start is 1-based
467        assert_eq!("def", nthline("abc\ndef\nghi", 2));
468        assert_eq!("def", nthword("abc def ghi", 2));
469        assert_eq!("c", removeprefix("abc", "ab"));
470        assert_eq!("abc", removeprefix("abc", "f"));
471        assert_eq!("ab", removesuffix("abc", "c"));
472        assert_eq!("abc", removesuffix("abc", "f"));
473        assert_eq!("bc", right("abc", 2));
474
475        // snip behavior
476        assert_eq!("abef", snip("abcdef", 2, 2));
477        assert_eq!("ab", snip("abcdef", 2, -1)); // -1 removes to end
478        assert_eq!("abcdef", snip("abcdef", 99, 2)); // start beyond end -> unchanged
479        assert_eq!("abcdef", snip("abcdef", 2, 0)); // non-positive count -> unchanged
480
481        // textafter/textbefore keep original if tag absent
482        assert_eq!("abcdef", textafter("abcdef", "xx"));
483        assert_eq!("abcdef", textbefore("abcdef", "xx"));
484        assert_eq!("ef", textafter("abcdef", "cd"));
485        assert_eq!("ab", textbefore("abcdef", "cd"));
486
487        // trimming and counts
488        assert_eq!("abcd", trim("abcdef", 2));
489        assert_eq!("cdef", trimleft("abcdef", 2));
490        assert_eq!(6, length("abcdef"));
491        assert_eq!(3, linecount("abc\ndef\nghi"));
492
493        // range parsing and matching
494        assert!(rangecontains("AB1234CD", "AZaz"));
495        assert!(rangecontains("AB1234CD", "09"));
496        assert!(!rangematch("AB1234CD", "09"));
497        assert!(rangematch("1234", "09"));
498        // odd-length range string ignores trailing char
499        assert!(rangecontains("a", "azb")); // parsed as ('a','z') and ('b',?) -> last ignored
500
501        // search and wordcount
502        assert_eq!(3, search("ABCD", "C"));
503        assert_eq!(0, search("ABCD", "")); // empty phrase -> 0
504        assert_eq!(3, wordcount("abc def ghi"));
505
506        // contains helper
507        assert!(contains("hello world", "world"));
508        assert!(!contains("hello", "bye"));
509
510        // internal helper coverage (private functions)
511        assert_eq!(byte_index_at_char("aβc", 0), 0);
512        assert!(byte_index_at_char("aβc", 99) >= "aβc".len().saturating_sub(1)); // out of range -> len()
513        assert_eq!(slice_chars("aβcδ", 1, 2), "βc");
514        assert_eq!(slice_chars_from("abc", 1), "bc");
515        assert_eq!(slice_chars_to("abc", 2), "ab");
516    }
517}