ctb_formats_pan/string/
stringmod.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//! Additional Pan string utilities.
27
28use ctb_formats_applescript::escape_string;
29
30#[allow(
31    unused_imports,
32    clippy::wildcard_imports,
33    reason = "Standard workspace module prelude"
34)]
35use crate::utilities::*;
36
37/// Escapes a string to use as an AppleScript string literal.
38///
39/// The result is wrapped in double quotes, and any `"` or `\` characters are
40/// escaped with a leading backslash.
41pub fn applescriptstring(text: &str) -> String {
42    escape_string(text)
43}
44
45/// Concatenates `prefix` and `suffix` with `connector` when both exist.
46pub fn connect(prefix: &str, connector: &str, suffix: &str) -> String {
47    match (prefix.is_empty(), suffix.is_empty()) {
48        (true, true) => String::new(),
49        (true, false) => suffix.to_owned(),
50        (false, true) => prefix.to_owned(),
51        (false, false) => {
52            let mut out = String::with_capacity(
53                prefix
54                    .len()
55                    .saturating_add(connector.len())
56                    .saturating_add(suffix.len()),
57            );
58            out.push_str(prefix);
59            out.push_str(connector);
60            out.push_str(suffix);
61            out
62        }
63    }
64}
65
66/// Like `connect`, but with different parameter naming.
67pub fn yoke(prefix: &str, joiner: &str, suffix: &str) -> String {
68    connect(prefix, joiner, suffix)
69}
70
71/// Replaces carriage returns with vertical tabs.
72pub fn crtovtab(text: &str) -> String {
73    text.chars()
74        .map(|c| if c == '\r' { '\u{000B}' } else { c })
75        .collect()
76}
77
78/// Replaces vertical tabs with carriage returns.
79pub fn vtabtocr(text: &str) -> String {
80    text.chars()
81        .map(|c| if c == '\u{000B}' { '\r' } else { c })
82        .collect()
83}
84
85/// Returns `default` when `text` is empty.
86pub fn defaulttext(text: &str, default: &str) -> String {
87    if text.is_empty() {
88        default.to_owned()
89    } else {
90        text.to_owned()
91    }
92}
93
94/// Extracts the `item`-th element from an array.
95///
96/// If `item` exceeds the number of elements, an empty string `""` is returned.
97pub fn extract(text: &str, separator: char, item: i64) -> Result<String> {
98    if item == -1 {
99        let count = if text.is_empty() {
100            0
101        } else {
102            text.split(separator).count()
103        };
104        return Ok(count.to_string());
105    }
106
107    if item < 1 {
108        bail!("extract(): item must be >= 1, or -1 to request the item count");
109    }
110
111    let idx_i64 = item.saturating_sub(1);
112    let idx =
113        usize::try_from(idx_i64).context("extract(): item index overflow")?;
114    Ok(text
115        .split(separator)
116        .nth(idx)
117        // Reason for fallback: requested item index out of bounds in separator split defaults to empty string (as per official Pan docs and docblock here)
118        .unwrap_or_default()
119        .to_owned())
120}
121
122/// Pads or truncates `text` to exactly `width` characters.
123pub fn fixedwidth(text: &str, width: usize) -> String {
124    if width == 0 {
125        return String::new();
126    }
127
128    let mut chars: Vec<char> = text.chars().collect();
129    if chars.len() > width {
130        chars.truncate(width);
131        return chars.into_iter().collect();
132    }
133
134    let pad = width.saturating_sub(chars.len());
135    let mut out: String = chars.into_iter().collect();
136    out.extend(std::iter::repeat_n(' ', pad));
137    out
138}
139
140/// Right-aligns `text` to `width`, truncating from the left if needed.
141#[expect(
142    clippy::expect_used,
143    reason = "start = chars.len() - width < chars.len() guaranteed by chars.len() > width"
144)]
145pub fn fixedwidthright(text: &str, width: usize) -> String {
146    if width == 0 {
147        return String::new();
148    }
149
150    let chars: Vec<char> = text.chars().collect();
151    if chars.len() > width {
152        let start = chars.len().saturating_sub(width);
153        return chars
154            .get(start..)
155            .expect("start < chars.len() guaranteed by chars.len() > width")
156            .iter()
157            .collect();
158    }
159
160    let pad = width.saturating_sub(chars.len());
161    let mut out = String::new();
162    out.extend(std::iter::repeat_n(' ', pad));
163    out.extend(chars);
164    out
165}
166
167#[expect(
168    clippy::expect_used,
169    reason = "start = chars.len() - width < chars.len() guaranteed by chars.len() > width"
170)]
171pub fn padzero(text: &str, width: usize) -> String {
172    if width == 0 {
173        return String::new();
174    }
175
176    let chars: Vec<char> = text.chars().collect();
177    if chars.len() > width {
178        let start = chars.len().saturating_sub(width);
179        return chars
180            .get(start..)
181            .expect("start < chars.len() guaranteed by chars.len() > width")
182            .iter()
183            .collect();
184    }
185
186    let pad = width.saturating_sub(chars.len());
187    let mut out = String::new();
188    out.extend(std::iter::repeat_n('0', pad));
189    out.extend(chars);
190    out
191}
192
193/// Removes empty lines and normalizes line breaks to `\n`.
194#[expect(
195    clippy::expect_used,
196    reason = "Infallible byte indexing and ASCII character boundary slice ranges in linestrip"
197)]
198pub fn linestrip(text: &str) -> String {
199    let mut out: Vec<&str> = Vec::new();
200    let mut start = 0usize;
201    let bytes = text.as_bytes();
202    let mut i = 0usize;
203
204    while i < bytes.len() {
205        let b = *bytes
206            .get(i)
207            .expect("i < bytes.len() guaranteed by loop condition");
208        let is_cr = b == b'\r';
209        let is_lf = b == b'\n';
210        if !is_cr && !is_lf {
211            i = i.saturating_add(1);
212            continue;
213        }
214
215        let line = text
216            .get(start..i)
217            .expect("start..i is a valid char boundary range <= text.len()");
218        if !line.trim().is_empty() {
219            out.push(line);
220        }
221
222        if is_cr && bytes.get(i.saturating_add(1)) == Some(&b'\n') {
223            i = i.saturating_add(2);
224        } else {
225            i = i.saturating_add(1);
226        }
227        start = i;
228    }
229
230    let tail = text
231        .get(start..)
232        .expect("start is a valid char boundary <= text.len()");
233    if !tail.trim().is_empty() {
234        out.push(tail);
235    }
236
237    out.join("\n")
238}
239
240/// Converts all characters to lowercase.
241pub fn lower(text: &str) -> String {
242    text.chars().flat_map(char::to_lowercase).collect()
243}
244
245/// Converts all characters to uppercase.
246pub fn upper(text: &str) -> String {
247    text.chars().flat_map(char::to_uppercase).collect()
248}
249
250/// Uppercases the first character of each whitespace-delimited word.
251pub fn upperword(text: &str) -> String {
252    let mut out = String::with_capacity(text.len());
253    let mut new_word = true;
254
255    for ch in text.chars() {
256        if ch.is_whitespace() {
257            new_word = true;
258            out.push(ch);
259            continue;
260        }
261
262        if new_word {
263            out.extend(ch.to_uppercase());
264            new_word = false;
265        } else {
266            out.extend(ch.to_lowercase());
267        }
268    }
269
270    out
271}
272
273/// Replaces all but the last `keep_last` digits with `X`.
274pub fn obscuredigits(text: &str, keep_last: usize) -> String {
275    let total_digits = text.chars().filter(char::is_ascii_digit).count();
276    let keep = total_digits.min(keep_last);
277
278    let mut seen_from_end = 0usize;
279    let mut out_rev = String::with_capacity(text.len());
280
281    for ch in text.chars().rev() {
282        if ch.is_ascii_digit() {
283            if seen_from_end < keep {
284                out_rev.push(ch);
285            } else {
286                out_rev.push('X');
287            }
288            seen_from_end = seen_from_end.saturating_add(1);
289        } else {
290            out_rev.push(ch);
291        }
292    }
293
294    out_rev.chars().rev().collect()
295}
296
297/// Collapses runs of spaces into a single space and trims ends.
298pub fn onespace(text: &str) -> String {
299    let mut out = String::with_capacity(text.len());
300    let mut prev_space = true;
301
302    for ch in text.chars() {
303        if ch == ' ' {
304            if !prev_space {
305                out.push(' ');
306                prev_space = true;
307            }
308            continue;
309        }
310        out.push(ch);
311        prev_space = false;
312    }
313
314    out.trim_matches(' ').to_owned()
315}
316
317/// Collapses runs of whitespace into a single space and trims ends.
318pub fn onewhitespace(text: &str) -> String {
319    let mut out = String::with_capacity(text.len());
320    let mut prev_space = true;
321
322    for ch in text.chars() {
323        let mapped = if ch.is_whitespace() { ' ' } else { ch };
324        if mapped == ' ' {
325            if !prev_space {
326                out.push(' ');
327                prev_space = true;
328            }
329            continue;
330        }
331
332        out.push(mapped);
333        prev_space = false;
334    }
335
336    out.trim_matches(' ').to_owned()
337}
338
339/// Wraps text in double quotes, doubling any internal quotes.
340pub fn quoted(text: &str) -> String {
341    let mut out = String::with_capacity(text.len().saturating_add(2));
342    out.push('"');
343    for ch in text.chars() {
344        if ch == '"' {
345            out.push('"');
346            out.push('"');
347        } else {
348            out.push(ch);
349        }
350    }
351    out.push('"');
352    out
353}
354
355/// Repeats `text` `count` times.
356pub fn rep(text: &str, count: i64) -> Result<String> {
357    if count < 0 {
358        bail!("rep(): count must be non-negative");
359    }
360    let count_usize =
361        usize::try_from(count).context("rep(): count overflow")?;
362
363    let cap = text
364        .len()
365        .checked_mul(count_usize)
366        .context("rep(): allocation size overflow")?;
367
368    let mut out = String::with_capacity(cap);
369    for _ in 0..count_usize {
370        out.push_str(text);
371    }
372    Ok(out)
373}
374
375/// Replaces all occurrences of `search` with `replace_with`.
376pub fn replace(text: &str, search: &str, replace_with: &str) -> Result<String> {
377    if search.is_empty() {
378        bail!("replace(): search string must not be empty");
379    }
380    Ok(text.replace(search, replace_with))
381}
382
383/// Replaces multiple search strings with their corresponding replacements.
384pub fn replacemultiple(
385    text: &str,
386    search: &str,
387    replace_with: &str,
388    sep: char,
389) -> Result<String> {
390    let search_items: Vec<&str> = search.split(sep).collect();
391    let replace_items: Vec<&str> = replace_with.split(sep).collect();
392
393    if search_items.len() != replace_items.len() {
394        bail!(
395            "replacemultiple(): search/replace lists must have the same length"
396        );
397    }
398
399    let mut out = text.to_owned();
400    for (s, r) in search_items.into_iter().zip(replace_items) {
401        if !s.is_empty() {
402            out = out.replace(s, r);
403        }
404    }
405    Ok(out)
406}
407
408/// Performs replacements based on a separator-delimited mapping table.
409pub fn batchreplace(
410    text: &str,
411    array: &str,
412    sep: char,
413    subsep: char,
414) -> Result<String> {
415    let mut out = text.to_owned();
416
417    for row in array.split(sep) {
418        if row.is_empty() {
419            continue;
420        }
421        let mut parts = row.splitn(2, subsep);
422        #[expect(
423            clippy::expect_used,
424            reason = "row is non-empty so splitn yields at least one part"
425        )]
426        let before = parts
427            .next()
428            .expect("row is non-empty so splitn yields at least one part");
429        let after = parts
430            .next()
431            .context("batchreplace(): row missing subseparator")?;
432
433        if before.is_empty() {
434            continue;
435        }
436        out = out.replace(before, after);
437    }
438
439    Ok(out)
440}
441
442/// Wraps `root` with `prefix` and `suffix` when `root` is non-empty.
443pub fn sandwich(prefix: &str, root: &str, suffix: &str) -> String {
444    if root.is_empty() {
445        return String::new();
446    }
447    let mut out = String::with_capacity(
448        prefix
449            .len()
450            .saturating_add(root.len())
451            .saturating_add(suffix.len()),
452    );
453    out.push_str(prefix);
454    out.push_str(root);
455    out.push_str(suffix);
456    out
457}
458
459/// Trims whitespace and control characters from both ends.
460pub fn strip(text: &str) -> String {
461    text.trim_matches(|c: char| c.is_whitespace() || u32::from(c) < 32)
462        .to_owned()
463}
464
465/// Keeps only characters within the inclusive `range` pairs.
466pub fn stripchar(text: &str, range: &str) -> Result<String> {
467    let rchars: Vec<char> = range.chars().collect();
468    if !rchars.len().is_multiple_of(2) {
469        bail!("stripchar(): range must contain an even number of characters");
470    }
471
472    let mut pairs = Vec::new();
473    for chunk in rchars.chunks(2) {
474        let a = *chunk.first().context("Missing start range character")?;
475        let b = *chunk.get(1).context("Missing end range character")?;
476        let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
477        pairs.push((lo, hi));
478    }
479
480    let mut out = String::with_capacity(text.len());
481    'outer: for ch in text.chars() {
482        for (lo, hi) in &pairs {
483            if *lo <= ch && ch <= *hi {
484                out.push(ch);
485                continue 'outer;
486            }
487        }
488    }
489    Ok(out)
490}
491
492/// Removes simple HTML tags delimited by `<` and `>`.
493pub fn striphtmltags(text: &str) -> String {
494    let mut out = String::with_capacity(text.len());
495    let mut in_tag = false;
496
497    for ch in text.chars() {
498        match ch {
499            '<' => in_tag = true,
500            '>' => in_tag = false,
501            _ if !in_tag => out.push(ch),
502            _ => {}
503        }
504    }
505    out
506}
507
508/// Removes non-printable ASCII control characters.
509pub fn stripprintable(text: &str) -> String {
510    text.chars().filter(|&c| u32::from(c) >= 32).collect()
511}
512
513/// Keeps only alphabetic characters.
514pub fn striptoalpha(text: &str) -> String {
515    text.chars().filter(|c| c.is_alphabetic()).collect()
516}
517
518/// Keeps only ASCII digits.
519pub fn striptonum(text: &str) -> String {
520    text.chars().filter(char::is_ascii_digit).collect()
521}
522
523/// Returns a random ASCII letter.
524///
525/// Use `U` for uppercase, `L` for lowercase, or anything else for either.
526pub fn randomletter(option: &str) -> Result<char> {
527    use rand::Rng;
528
529    let mut rng = rand::rng();
530    let choice: i32 = match option {
531        "U" => rng.random_range(0..26),
532        "L" => rng.random_range(26..52),
533        _ => rng.random_range(0..52),
534    };
535
536    let base = if choice < 26 { b'A' } else { b'a' };
537    let offset = if choice < 26 {
538        choice
539    } else {
540        choice.saturating_sub(26)
541    };
542
543    let offset_u8 =
544        u8::try_from(offset).context("randomletter(): offset overflow")?;
545    let b = base
546        .checked_add(offset_u8)
547        .context("randomletter(): byte overflow")?;
548
549    Ok(char::from(b))
550}
551
552/// Returns a random non-empty line from `text`.
553pub fn randomline(text: &str) -> Result<String> {
554    use rand::Rng;
555
556    let mut lines: Vec<&str> = Vec::new();
557    let mut start = 0usize;
558    let bytes = text.as_bytes();
559    let mut i = 0usize;
560
561    while i < bytes.len() {
562        let b = *bytes.get(i).context("Invalid byte index")?;
563        let is_cr = b == b'\r';
564        let is_lf = b == b'\n';
565        if !is_cr && !is_lf {
566            i = i.saturating_add(1);
567            continue;
568        }
569
570        let line = text.get(start..i).context("Invalid line range")?;
571        if !line.trim().is_empty() {
572            lines.push(line);
573        }
574
575        if is_cr && bytes.get(i.saturating_add(1)) == Some(&b'\n') {
576            i = i.saturating_add(2);
577        } else {
578            i = i.saturating_add(1);
579        }
580        start = i;
581    }
582
583    let tail = text.get(start..).context("Invalid tail range")?;
584    if !tail.trim().is_empty() {
585        lines.push(tail);
586    }
587
588    if lines.is_empty() {
589        return Ok(String::new());
590    }
591
592    let mut rng = rand::rng();
593    let idx = rng.random_range(0..lines.len());
594    Ok(lines
595        .get(idx)
596        .context("Random index out of bounds")?
597        .to_string())
598}
599
600/// Returns a random whitespace-delimited word from `wordlist`.
601pub fn randomword(wordlist: &str) -> Result<String> {
602    use rand::Rng;
603
604    let words: Vec<&str> = wordlist.split_whitespace().collect();
605    if words.is_empty() {
606        return Ok(String::new());
607    }
608
609    let mut rng = rand::rng();
610    let idx = rng.random_range(0..words.len());
611    Ok(words
612        .get(idx)
613        .context("Random index out of bounds")?
614        .to_string())
615}
616
617#[cfg(test)]
618#[allow(
619    clippy::panic,
620    clippy::expect_used,
621    clippy::unwrap_used,
622    clippy::unwrap_in_result,
623    clippy::panic_in_result_fn,
624    clippy::indexing_slicing,
625    clippy::arithmetic_side_effects,
626    reason = "Standard repository test boilerplate"
627)]
628mod tests {
629    use super::*;
630
631    #[crate::ctb_test]
632    fn test_basic_joining() {
633        assert_eq!(connect("City", ", ", "State"), "City, State");
634        assert_eq!(connect("", ", ", "State"), "State");
635        assert_eq!(connect("City", ", ", ""), "City");
636        assert_eq!(connect("", ", ", ""), "");
637
638        assert_eq!(yoke("a", "-", "b"), "a-b");
639        assert_eq!(sandwich(" (", "Mgr", ")"), " (Mgr)");
640        assert_eq!(sandwich(" (", "", ")"), "");
641    }
642
643    #[crate::ctb_test]
644    fn test_cr_vtab_roundtrip() {
645        let s = "a\rb";
646        assert_eq!(crtovtab(s), "a\u{000B}b");
647        assert_eq!(vtabtocr(&crtovtab(s)), s);
648    }
649
650    #[crate::ctb_test]
651    fn test_defaulttext_extract() -> Result<()> {
652        assert_eq!(defaulttext("", "x"), "x");
653        assert_eq!(defaulttext("y", "x"), "y");
654
655        let t = "a,b,,d,";
656        assert_eq!(extract(t, ',', 1)?, "a");
657        assert_eq!(extract(t, ',', 2)?, "b");
658        assert_eq!(extract(t, ',', 3)?, "");
659        assert_eq!(extract(t, ',', 5)?, "");
660        assert_eq!(extract(t, ',', -1)?, "5");
661        Ok(())
662    }
663
664    #[crate::ctb_test]
665    fn test_fixedwidths() {
666        assert_eq!(fixedwidth("ab", 5), "ab   ");
667        assert_eq!(fixedwidth("abcdef", 3), "abc");
668        assert_eq!(fixedwidthright("ab", 5), "   ab");
669        assert_eq!(fixedwidthright("abcdef", 3), "def");
670        assert_eq!(padzero("7", 3), "007");
671        assert_eq!(padzero("12345", 3), "345");
672    }
673
674    #[crate::ctb_test]
675    fn test_linestrip() {
676        let t = "a\r\r b \n\nc\r\n  \r\nd";
677        assert_eq!(linestrip(t), "a\n b \nc\nd");
678    }
679
680    #[crate::ctb_test]
681    fn test_case_and_words() {
682        assert_eq!(lower("ABC 123"), "abc 123");
683        assert_eq!(upper("a.f.k."), "A.F.K.");
684        assert_eq!(upperword("new york"), "New York");
685        assert_eq!(upperword("TEST"), "Test");
686    }
687
688    #[crate::ctb_test]
689    fn test_obscuredigits() {
690        let t = "1234-1234-1234-1234";
691        assert_eq!(obscuredigits(t, 4), "XXXX-XXXX-XXXX-1234");
692        assert_eq!(obscuredigits("abc", 4), "abc");
693    }
694
695    #[crate::ctb_test]
696    fn test_spacing() {
697        assert_eq!(onespace("  a   b  c "), "a b c");
698        assert_eq!(onewhitespace(" \ta\r\nb  \nc "), "a b c");
699    }
700
701    #[crate::ctb_test]
702    fn test_quotes() {
703        assert_eq!(quoted(r#"a"b"#), r#""a""b""#);
704        assert_eq!(applescriptstring(r#"a"b\c"#), r#""a\"b\\c""#);
705    }
706
707    #[crate::ctb_test]
708    fn test_replace_rep_multi_batch() -> Result<()> {
709        assert_eq!(rep("*", 5)?, "*****");
710        assert_eq!(replace("aabb", "aa", "x")?, "xbb");
711
712        let out = replacemultiple(
713            "Street City County State",
714            "Street,City,County,State",
715            "St,City,Cty,NJ",
716            ',',
717        )?;
718        assert_eq!(out, "St City Cty NJ");
719
720        let array = "foo-bar|baz-qux";
721        let out2 = batchreplace("foo baz foo", array, '|', '-')?;
722        assert_eq!(out2, "bar qux bar");
723
724        Ok(())
725    }
726
727    #[crate::ctb_test]
728    fn test_strip_and_strip_variants() -> Result<()> {
729        assert_eq!(strip("\t  hi \r\n"), "hi");
730        assert_eq!(stripprintable("a\u{0001}b"), "ab");
731        assert_eq!(striptoalpha("a1 b!ç"), "abç");
732        assert_eq!(striptonum("a1 b2!3"), "123");
733
734        assert_eq!(striphtmltags("a<b>c</b>d"), "acd");
735
736        assert_eq!(stripchar("AZaz09..-_*", "AZaz09..")?, "AZaz09..");
737        Ok(())
738    }
739
740    #[crate::ctb_test]
741    fn test_random_sanity() -> Result<()> {
742        let c = randomletter("U")?;
743        assert!(c.is_ascii_uppercase());
744
745        let line = randomline("a\n\nb\n")?;
746        assert!(line == "a" || line == "b");
747
748        let w = randomword("one two three")?;
749        assert!(w == "one" || w == "two" || w == "three");
750        Ok(())
751    }
752}