ctb_formats_pan/string/
funnel.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//! Funnel-style substring extraction.
27
28#[allow(
29    unused_imports,
30    clippy::wildcard_imports,
31    reason = "Standard workspace module prelude"
32)]
33use crate::utilities::*;
34
35#[derive(Debug, Clone)]
36enum Term {
37    Index(i64),
38    Pattern(Pattern),
39    Empty,
40    Invalid,
41}
42
43#[derive(Debug, Clone)]
44struct Pattern {
45    reverse: bool,
46    negated: bool,
47    tokens: Vec<Token>,
48}
49
50#[derive(Debug, Clone, Copy)]
51enum Token {
52    Single(char),
53    Range(char, char),
54}
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
57enum Separator {
58    Comma,
59    Semicolon,
60    None,
61}
62
63/// Splits a funnel spec into left/right terms and the separator used.
64fn split_spec(spec: &str) -> (String, String, Separator) {
65    let mut in_quotes = false;
66
67    for (i, ch) in spec.char_indices() {
68        if ch == '"' {
69            in_quotes = !in_quotes;
70            continue;
71        }
72        if !in_quotes && (ch == ',' || ch == ';') {
73            let (a, b) = spec.split_at(i);
74            #[expect(
75                clippy::expect_used,
76                reason = "b starts with delimiter character ch, so b[ch.len_utf8()..] is in bounds"
77            )]
78            let b = b
79                .get(ch.len_utf8()..)
80                .expect("b starts with delimiter character");
81            let sep = if ch == ';' {
82                Separator::Semicolon
83            } else {
84                Separator::Comma
85            };
86            return (a.trim().to_string(), b.trim().to_string(), sep);
87        }
88    }
89
90    (spec.trim().to_string(), String::new(), Separator::None)
91}
92
93/// Parses a term into an index, pattern, or placeholder.
94fn parse_term(raw: &str) -> Term {
95    let s = raw.trim();
96    if s.is_empty() {
97        return Term::Empty;
98    }
99
100    if let Some(inner) = s.strip_prefix('"').and_then(|x| x.strip_suffix('"')) {
101        return Term::Pattern(parse_pattern(inner));
102    }
103
104    if let Ok(n) = s.parse::<i64>() {
105        return Term::Index(n);
106    }
107
108    Term::Invalid
109}
110
111/// Parses a quoted pattern with optional negation and reverse flags.
112fn parse_pattern(mut s: &str) -> Pattern {
113    let mut reverse = false;
114    let mut negated = false;
115
116    // This allows either `≠-` or `-≠` (non-matching + reverse) so we don’t
117    // accidentally treat the `-` as a literal token. However, `≠-` is the
118    // documented order; unsure what the precisely compatible behavior would be.
119    loop {
120        if !negated {
121            if let Some(rest) = s.strip_prefix('≠') {
122                negated = true;
123                s = rest;
124                continue;
125            }
126        }
127        if !reverse {
128            if let Some(rest) = s.strip_prefix('-') {
129                reverse = true;
130                s = rest;
131                continue;
132            }
133        }
134        break;
135    }
136
137    let mut tokens = Vec::new();
138    for tok in s.split(',') {
139        if tok.is_empty() {
140            tokens.push(Token::Single(','));
141            continue;
142        }
143
144        let mut chars = tok.chars();
145        let a = chars.next();
146        let b = chars.next();
147        let c = chars.next();
148        let extra = chars.next();
149
150        if let (Some(a), Some('-'), Some(c), None) = (a, b, c, extra) {
151            tokens.push(Token::Range(a, c));
152            continue;
153        }
154
155        for ch in tok.chars() {
156            tokens.push(Token::Single(ch));
157        }
158    }
159
160    Pattern {
161        reverse,
162        negated,
163        tokens,
164    }
165}
166
167fn contains_token(tokens: &[Token], ch: char) -> bool {
168    for t in tokens {
169        match *t {
170            Token::Single(c) => {
171                if c == ch {
172                    return true;
173                }
174            }
175            Token::Range(a, b) => {
176                let (lo, hi) = if a <= b { (a, b) } else { (b, a) };
177                if lo <= ch && ch <= hi {
178                    return true;
179                }
180            }
181        }
182    }
183    false
184}
185
186fn find_pattern(chars: &[char], pat: &Pattern) -> Option<usize> {
187    if chars.is_empty() {
188        return None;
189    }
190
191    let matches = |ch: char| {
192        let in_set = contains_token(&pat.tokens, ch);
193        if pat.negated { !in_set } else { in_set }
194    };
195
196    if pat.reverse {
197        for i in (0..chars.len()).rev() {
198            if chars.get(i).is_some_and(|&ch| matches(ch)) {
199                return Some(i);
200            }
201        }
202    } else {
203        for (i, &ch) in chars.iter().enumerate() {
204            if matches(ch) {
205                return Some(i);
206            }
207        }
208    }
209
210    None
211}
212
213fn find_pattern_or(chars: &[char], pat: &Pattern, default: usize) -> usize {
214    if let Some(i) = find_pattern(chars, pat) {
215        i
216    } else {
217        default
218    }
219}
220
221fn resolve_start_index(n: i64, len: usize) -> Option<usize> {
222    if len == 0 {
223        return None;
224    }
225
226    if n >= 1 {
227        let one_based = match usize::try_from(n) {
228            Ok(v) => v,
229            Err(_) => return None,
230        };
231        if one_based == 0 || one_based > len {
232            return None;
233        }
234        return Some(one_based.saturating_sub(1));
235    }
236
237    // Negative indices: -1 is last character. If too negative, saturate to 0.
238    let back = n.saturating_neg().saturating_sub(1);
239    let back_usize = match usize::try_from(back) {
240        Ok(v) => v,
241        Err(_) => usize::MAX,
242    };
243    Some(len.saturating_sub(1).saturating_sub(back_usize))
244}
245
246fn resolve_end_index(n: i64, len: usize) -> Option<usize> {
247    if len == 0 {
248        return None;
249    }
250
251    if n >= 1 {
252        let one_based = match usize::try_from(n) {
253            Ok(v) => v,
254            Err(_) => return Some(len.saturating_sub(1)),
255        };
256        let idx0 = one_based.saturating_sub(1);
257        return Some(idx0.min(len.saturating_sub(1)));
258    }
259
260    // Negative indices: -1 is last character. If too negative, saturate to 0.
261    let back = n.saturating_neg().saturating_sub(1);
262    let back_usize = match usize::try_from(back) {
263        Ok(v) => v,
264        Err(_) => usize::MAX,
265    };
266    Some(len.saturating_sub(1).saturating_sub(back_usize))
267}
268
269#[expect(
270    clippy::expect_used,
271    reason = "Caller guarantees start < chars.len(); 1 <= start < chars.len() guarantees in-bounds indexing for start, start - 1, and start - 2"
272)]
273fn adjust_start_for_negated_alnum_run(chars: &[char], start: usize) -> usize {
274    assert!(start < chars.len(), "start index must be in bounds");
275    if start == 0 {
276        return 0;
277    }
278
279    let cur = *chars
280        .get(start)
281        .expect("start < chars.len() asserted above");
282    if !cur.is_ascii_digit() {
283        return start;
284    }
285
286    let prev = *chars
287        .get(start.saturating_sub(1))
288        .expect("1 <= start < chars.len() guarantees start - 1 is in bounds");
289    if !prev.is_ascii_alphabetic() {
290        return start;
291    }
292
293    let preceded_by_delim = if start < 2 {
294        true
295    } else {
296        let before_prev = *chars.get(start.saturating_sub(2)).expect(
297            "2 <= start < chars.len() guarantees start - 2 is in bounds",
298        );
299        before_prev.is_ascii_whitespace() || before_prev == ','
300    };
301
302    if preceded_by_delim {
303        start.saturating_sub(1)
304    } else {
305        start
306    }
307}
308
309/// Extracts a substring using a funnel specification.
310///
311/// The spec is `A,B` or `A;B` where each term is a 1-based index, a
312/// negative index from the end, or a quoted pattern. A semicolon treats
313/// `B` as a length relative to `A`; a comma treats `B` as an absolute
314/// end. Patterns support character ranges like `a-z`, a leading `-`
315/// for reverse search, and `≠` for negation.
316pub fn funnel(text: &str, funnel: &str) -> String {
317    let chars: Vec<char> = text.chars().collect();
318    if chars.is_empty() {
319        return String::new();
320    }
321
322    let (a_raw, b_raw, sep) = split_spec(funnel);
323    let a = parse_term(&a_raw);
324    let b = parse_term(&b_raw);
325
326    let len = chars.len();
327    let start = match a {
328        Term::Index(n) => {
329            let Some(s) = resolve_start_index(n, len) else {
330                return String::new();
331            };
332            s
333        }
334        Term::Pattern(ref p) => {
335            let s = find_pattern_or(&chars, p, 0);
336            if p.negated && !p.reverse {
337                adjust_start_for_negated_alnum_run(&chars, s)
338            } else {
339                s
340            }
341        }
342        Term::Empty => 0,
343        Term::Invalid => return text.to_string(),
344    };
345
346    match sep {
347        Separator::Semicolon => {
348            let Term::Index(n) = b else {
349                if matches!(b, Term::Empty) {
350                    return String::new();
351                }
352                return text.to_string();
353            };
354
355            if n == 0 {
356                return String::new();
357            }
358
359            let end = if n >= 1 {
360                let span_i64 = n.saturating_sub(1);
361                let span = match usize::try_from(span_i64) {
362                    Ok(v) => v,
363                    Err(_) => usize::MAX,
364                };
365                start.saturating_add(span).min(len.saturating_sub(1))
366            } else {
367                let span_i64 = n.saturating_neg().saturating_sub(1);
368                let span = match usize::try_from(span_i64) {
369                    Ok(v) => v,
370                    Err(_) => usize::MAX,
371                };
372                start.saturating_sub(span)
373            };
374
375            let lo = start.min(end);
376            let hi = start.max(end);
377            // Reason for fallback: character range slice out of bounds defaults to empty char slice
378            chars.get(lo..=hi).unwrap_or(&[]).iter().collect()
379        }
380        Separator::Comma | Separator::None => {
381            let end = match b {
382                Term::Index(n) => {
383                    if let Some(e) = resolve_end_index(n, len) {
384                        e
385                    } else {
386                        len.saturating_sub(1)
387                    }
388                }
389                Term::Pattern(ref p) => {
390                    find_pattern_or(&chars, p, len.saturating_sub(1))
391                }
392                Term::Empty => len.saturating_sub(1),
393                Term::Invalid => return text.to_string(),
394            };
395
396            if start > end {
397                return String::new();
398            }
399
400            // Reason for fallback: character range slice out of bounds defaults to empty char slice
401            chars.get(start..=end).unwrap_or(&[]).iter().collect()
402        }
403    }
404}
405
406#[cfg(test)]
407#[allow(
408    clippy::panic,
409    clippy::expect_used,
410    clippy::unwrap_used,
411    clippy::unwrap_in_result,
412    clippy::panic_in_result_fn,
413    clippy::indexing_slicing,
414    clippy::arithmetic_side_effects,
415    reason = "Standard repository test boilerplate"
416)]
417mod tests {
418    use super::*;
419
420    #[crate::ctb_test]
421    fn test_funnel() {
422        let phone = "(123) 456-7890";
423        let price_line1 = "A1234B Item Name $56.78";
424        let price_line1_simple = "Item Name $56.78";
425        let price_line2_num_simple = "Another Item 9.10";
426        let price_line2_dlr = "XY5678 Another Item $9.10";
427        let price_line2_dlr_simple = "Another Item $9.10";
428        let price_line3 = "CD4 Third Item $12.34";
429        let price_line_lower = "fourth item $12.34";
430        let time1 = "12:34 AM";
431        let time2 = "1:23:45 PM";
432        let date_in_text_1 = "Here's the date: 1/2/34";
433        let date_in_text_2 = "Here's some text with a date 1/2/34 in it.";
434        let date_in_text_3 = "1/2 is a date, unless it's a half";
435        let text = "Sample text for testing.";
436        let sentences =
437            "Sample text for testing. Another sentence. Yet another one!";
438        let sentences_exclam =
439            "Sample text for testing! Another sentence! Yet another one!";
440        let sentences_ques =
441            "Sample text for testing? Another sentence? Yet another one?";
442        let sentences_commas =
443            "Sample text, for, testing? Another, sentence? Yet, another one?";
444        let kexp = "KEXP 90.3 FM";
445        let us_loc = "New York, NY 10001";
446        let can_loc = "Toronto, ON M5H 2N2";
447
448        let result = funnel("abc", "2,-1");
449        assert_eq!(result, "bc");
450
451        let result = funnel("abc", "1,-2");
452        assert_eq!(result, "ab");
453
454        let result = funnel(phone, "2,4");
455        assert_eq!(result, "123");
456
457        let result = funnel(phone, "2;3");
458        assert_eq!(result, "123");
459
460        let result = funnel(phone, "-1;-8");
461        assert_eq!(result, "456-7890");
462
463        let result = funnel("123", "-1;-8");
464        assert_eq!(result, "123");
465
466        let result = funnel(time1, "1,\":\"");
467        assert_eq!(result, "12:");
468
469        let result = funnel(price_line1, "\"$\",-1");
470        assert_eq!(result, "$56.78");
471
472        let result = funnel(&funnel(price_line1, "\"$\",-1"), "2,-1");
473        assert_eq!(result, "56.78");
474
475        let result = funnel(price_line2_dlr, "\"$\",-1");
476        assert_eq!(result, "$9.10");
477
478        let result = funnel(&funnel(price_line2_dlr, "\"$\",-1"), "2,-1");
479        assert_eq!(result, "9.10");
480
481        let result = funnel(price_line3, "\"$\",-1");
482        assert_eq!(result, "$12.34");
483
484        let result = funnel(&funnel(price_line3, "\"$\",-1"), "2,-1");
485        assert_eq!(result, "12.34");
486
487        let result = funnel(&funnel(time1, "1,\":\""), "1,-2");
488        assert_eq!(result, "12");
489
490        let result = funnel(&funnel(time2, "1,\":\""), "1,-2");
491        assert_eq!(result, "1");
492
493        let result = funnel(date_in_text_1, "\"-/\",-1");
494        assert_eq!(result, "/34");
495
496        let result = funnel(&funnel(date_in_text_1, "\"-/\",-1"), "2;2");
497        assert_eq!(result, "34");
498
499        let result = funnel(date_in_text_2, "\"-/\",-1");
500        assert_eq!(result, "/34 in it.");
501
502        let result = funnel(&funnel(date_in_text_2, "\"-/\",-1"), "2;2");
503        assert_eq!(result, "34");
504
505        let result = funnel(date_in_text_3, "\"-/\",-1");
506        assert_eq!(result, "/2 is a date, unless it's a half");
507
508        let result = funnel(&funnel(date_in_text_3, "\"-/\",-1"), "2;2");
509        assert_eq!(result, "2 ");
510
511        let result = funnel(text, "\"-/\",-1");
512        assert_eq!(result, "Sample text for testing.");
513
514        let result = funnel(&funnel(text, "\"-/\",-1"), "2;2");
515        assert_eq!(result, "am");
516
517        let result = funnel(text, "1,\" \"");
518        assert_eq!(result, "Sample ");
519
520        let result = funnel(&funnel(text, "1,\" \""), "1,-2");
521        assert_eq!(result, "Sample");
522
523        let result = funnel(text, "\" \",-1");
524        assert_eq!(result, " text for testing.");
525
526        let result = funnel(&funnel(text, "\" \",-1"), "2,-1");
527        assert_eq!(result, "text for testing.");
528
529        let result =
530            funnel(&funnel(&funnel(text, "\" \",-1"), "2,-1"), "1,\" \"");
531        assert_eq!(result, "text ");
532
533        let result = funnel(
534            &funnel(&funnel(&funnel(text, "\" \",-1"), "2,-1"), "1,\" \""),
535            "1,-2",
536        );
537        assert_eq!(result, "text");
538
539        let result = funnel(text, "\"- \",-1");
540        assert_eq!(result, " testing.");
541
542        let result = funnel(&funnel(text, "\"- \",-1"), "2,-1");
543        assert_eq!(result, "testing.");
544
545        let result = funnel(sentences, "1,\".,?,!\"");
546        assert_eq!(result, "Sample text for testing.");
547
548        let result = funnel(sentences_exclam, "1,\".,?,!\"");
549        assert_eq!(result, "Sample text for testing!");
550
551        let result = funnel(sentences_ques, "1,\".,?,!\"");
552        assert_eq!(result, "Sample text for testing?");
553
554        let result = funnel(sentences_commas, "1,\";,,,:\"");
555        assert_eq!(result, "Sample text,");
556
557        let result = funnel(time1, "\"a,p,A,P\";2");
558        assert_eq!(result, "AM");
559
560        let result = funnel(kexp, "\"0-9\",-1");
561        assert_eq!(result, "90.3 FM");
562
563        let result = funnel(price_line1_simple, "\"0-9,$\",-1");
564        assert_eq!(result, "$56.78");
565
566        let result = funnel(price_line2_dlr_simple, "\"0-9,$\",-1");
567        assert_eq!(result, "$9.10");
568
569        let result = funnel(price_line2_num_simple, "\"0-9,$\",-1");
570        assert_eq!(result, "9.10");
571
572        let result = funnel(price_line3, "\"0-9,$\",-1");
573        assert_eq!(result, "4 Third Item $12.34");
574
575        let result = funnel(price_line1_simple, "1,\"-A-Z,a-z\"");
576        assert_eq!(result, "Item Name");
577
578        let result = funnel(price_line_lower, "1,\"-A-Z,a-z\"");
579        assert_eq!(result, "fourth item");
580
581        let result = funnel("####12.34", "\"≠#\",-1");
582        assert_eq!(result, "12.34");
583
584        let result = funnel("    12.34", "\"≠ \",-1");
585        assert_eq!(result, "12.34");
586
587        let result = funnel(us_loc, "\"≠A-Z,a-z,,, \",-1");
588        assert_eq!(result, "10001");
589
590        let result = funnel(can_loc, "\"≠A-Z,a-z,,, \",-1");
591        assert_eq!(result, "M5H 2N2");
592
593        let result =
594            funnel(&funnel(price_line1_simple, "\"≠-0-9,.\",-1"), "2,-1");
595        assert_eq!(result, "56.78");
596    }
597}