ctb_formats_pan/string/
pattern.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 numeric pattern formatting.
27
28#[allow(
29    unused_imports,
30    clippy::wildcard_imports,
31    reason = "Standard workspace module prelude"
32)]
33use crate::utilities::*;
34
35use number_to_words::number_to_words;
36use pluralizer::pluralize;
37use regex::Regex;
38
39use std::str::FromStr;
40
41/// Formats `number` using the Pan pattern syntax.
42///
43/// Use `#` for digits, `§` for words, `¢` for cents digits, `~` for
44/// pluralization, and an optional trailing `-` or parentheses to control
45/// negative formatting.
46pub fn pattern(number: f64, pat: &str) -> Result<String> {
47    if !number.is_finite() {
48        bail!("pattern(): number must be finite");
49    }
50
51    let (abs_value, core_pat, neg_style) = extract_negative_style(number, pat)?;
52
53    let (rendered, is_one) = if core_pat.contains('§') {
54        (
55            format_words(abs_value, &core_pat)?,
56            is_one_words(abs_value, &core_pat)?,
57        )
58    } else {
59        let (prefix, numeric_pat, suffix) =
60            split_prefix_numeric_suffix(&core_pat)?;
61
62        if is_scientific_marker(&numeric_pat) {
63            let precision = scientific_precision(&numeric_pat)?;
64            let s = format_scientific(abs_value, precision)?;
65            (format!("{prefix}{s}{suffix}"), is_one_from_rendered(&s))
66        } else if numeric_pat.contains('.') || numeric_pat.contains(',') {
67            let s = format_normal_numeric(abs_value, &numeric_pat)?;
68            (format!("{prefix}{s}{suffix}"), is_one_from_rendered(&s))
69        } else if numeric_pat.chars().all(|c| c == '#') {
70            // A plain run of hashes (e.g. "#" or "#####") is a normal numeric
71            // pattern: it may pad with leading zeros, but it must not fail when the
72            // value has more digits than the pattern length.
73            let s = format_normal_numeric(abs_value, &numeric_pat)?;
74            (format!("{prefix}{s}{suffix}"), is_one_from_rendered(&s))
75        } else {
76            // Mixed literal/component patterns like "###-####".
77            let s = format_component(abs_value, &numeric_pat)?;
78            (format!("{prefix}{s}{suffix}"), is_one_from_rendered(&s))
79        }
80    };
81
82    let mut out = apply_plural_suffix(rendered, is_one);
83
84    out = match neg_style {
85        NegStyle::Parens if number.is_sign_negative() && number != 0.0 => {
86            format!("({out})")
87        }
88        NegStyle::TrailingMinus
89            if number.is_sign_negative() && number != 0.0 =>
90        {
91            let mut s = out;
92            s.push('-');
93            s
94        }
95        NegStyle::Default if number.is_sign_negative() && number != 0.0 => {
96            format!("-{out}")
97        }
98        _ => out,
99    };
100
101    Ok(out)
102}
103
104#[derive(Clone, Copy, Debug, Eq, PartialEq)]
105enum NegStyle {
106    Default,
107    TrailingMinus,
108    Parens,
109}
110
111fn extract_negative_style(
112    number: f64,
113    pat: &str,
114) -> Result<(f64, String, NegStyle)> {
115    let abs_value = number.abs();
116    let mut p = pat.to_string();
117
118    // Parentheses indicate negative-only wrapping: (#.##)
119    if let Some((open, close)) = find_wrapping_parens(&p) {
120        let inner = p
121            .get(open.saturating_add(1)..close)
122            .context("Invalid parentheses range")?;
123        let contains_placeholder =
124            inner.chars().any(|c| matches!(c, '#' | '§' | '¢'));
125        if contains_placeholder {
126            let mut stripped = String::new();
127            stripped.push_str(p.get(..open).context("Invalid prefix range")?);
128            stripped.push_str(inner);
129            stripped.push_str(
130                p.get(close.saturating_add(1)..)
131                    .context("Invalid suffix range")?,
132            );
133            return Ok((abs_value, stripped, NegStyle::Parens));
134        }
135    }
136
137    // Trailing minus: #.##-
138    if p.ends_with('-') && p.chars().any(|c| matches!(c, '#' | '§' | '¢')) {
139        p.pop();
140        return Ok((abs_value, p, NegStyle::TrailingMinus));
141    }
142
143    Ok((abs_value, p, NegStyle::Default))
144}
145
146fn find_wrapping_parens(s: &str) -> Option<(usize, usize)> {
147    let open = s.find('(')?;
148    let close_rel = s.get(open..)?.find(')')?;
149    let close = open.saturating_add(close_rel);
150    Some((open, close))
151}
152
153fn split_prefix_numeric_suffix(pat: &str) -> Result<(String, String, String)> {
154    let first = pat
155        .char_indices()
156        .find(|(_, c)| matches!(c, '#' | '§' | '¢'))
157        .map(|(i, _)| i)
158        .context("pattern(): missing placeholder (#, §, or ¢)")?;
159
160    let last_hash = pat
161        .char_indices()
162        .rev()
163        .find(|(_, c)| matches!(c, '#' | '§' | '¢'))
164        .map(|(i, _)| i)
165        .context("pattern(): missing placeholder (#, §, or ¢)")?;
166
167    // Extend numeric region by a single scientific marker if it immediately
168    // follows the last placeholder, e.g. "#.#E kg".
169    let after_last = last_hash
170        .checked_add(1)
171        .context("pattern(): invalid placeholder index")?;
172    let mut end = last_hash;
173
174    if let Some(next) = pat
175        .get(after_last..)
176        .context("Invalid index")?
177        .chars()
178        .next()
179    {
180        if matches!(next, 'e' | 'E') {
181            end = after_last;
182        }
183    }
184
185    let prefix = pat
186        .get(..first)
187        .context("Invalid prefix index")?
188        .to_string();
189    let numeric = pat
190        .get(first..=end)
191        .context("Invalid numeric index")?
192        .to_string();
193    // Reason for fallback: pattern without trailing suffix after numeric part defaults suffix string to empty
194    let suffix = pat.get(end.saturating_add(1)..).unwrap_or("").to_string();
195
196    Ok((prefix, numeric, suffix))
197}
198
199fn apply_plural_suffix(s: String, is_one: bool) -> String {
200    if !s.contains('~') {
201        return s;
202    }
203
204    let count = if is_one { 1 } else { 2 };
205
206    let mut out = String::with_capacity(s.len());
207    let mut rest = s.as_str();
208    while let Some(tilde_pos) = rest.find('~') {
209        let (before_tilde, with_tilde) = rest.split_at(tilde_pos);
210
211        // Reason for fallback: word start search without preceding whitespace defaults word boundary offset to 0
212        let word_start = before_tilde
213            .rfind(|c: char| c.is_whitespace())
214            .map_or(0, |i| i.saturating_add(1));
215        let (prefix, word) = before_tilde.split_at(word_start);
216
217        out.push_str(prefix);
218        if !word.is_empty() {
219            out.push_str(&pluralize(word, count, false));
220        }
221
222        // Skip the tilde.
223        // Reason for fallback: rest slice stripping tilde at end of string defaults remaining rest to empty string
224        rest = with_tilde.get(1..).unwrap_or("");
225    }
226
227    out.push_str(rest);
228    out
229}
230
231fn is_scientific_marker(numeric_pat: &str) -> bool {
232    numeric_pat.ends_with('e') || numeric_pat.ends_with('E')
233}
234
235fn scientific_precision(numeric_pat: &str) -> Result<usize> {
236    let mut chars = numeric_pat.chars().peekable();
237
238    // Count # after '.' until the trailing e/E (if any).
239    for c in chars.by_ref() {
240        if c == '.' {
241            break;
242        }
243    }
244    let mut n = 0usize;
245    while let Some(&c) = chars.peek() {
246        if matches!(c, 'e' | 'E') {
247            break;
248        }
249        if c == '#' {
250            n = n.saturating_add(1);
251        }
252        chars.next();
253    }
254    Ok(n)
255}
256
257fn format_scientific(value: f64, precision: usize) -> Result<String> {
258    let raw = format!("{value:.precision$e}");
259    let (mantissa, exp_part) = raw
260        .split_once('e')
261        .context("pattern(): unexpected scientific formatting")?;
262
263    let exp_i32 = i32::from_str(exp_part)
264        .context("pattern(): invalid exponent in scientific formatting")?;
265
266    let exp = if exp_i32 >= 0 {
267        format!("+{exp_i32}")
268    } else {
269        exp_i32.to_string()
270    };
271
272    Ok(format!("{mantissa}e{exp}"))
273}
274
275fn format_normal_numeric(value: f64, numeric_pat: &str) -> Result<String> {
276    let has_comma = numeric_pat.contains(',');
277
278    let (min_int_digits, decimals) = min_int_and_decimals(numeric_pat)?;
279    let formatted = format!("{value:.decimals$}");
280    let (mut int_part, frac_part) = split_int_frac(&formatted, decimals)?;
281
282    if int_part.len() < min_int_digits {
283        let mut padded = String::new();
284        padded.extend(std::iter::repeat_n(
285            '0',
286            min_int_digits.saturating_sub(int_part.len()),
287        ));
288        padded.push_str(&int_part);
289        int_part = padded;
290    }
291
292    if has_comma {
293        int_part = add_commas(&int_part);
294    }
295
296    if decimals == 0 {
297        return Ok(int_part);
298    }
299
300    Ok(format!("{int_part}.{frac_part}"))
301}
302
303fn min_int_and_decimals(numeric_pat: &str) -> Result<(usize, usize)> {
304    let mut before_dot = 0usize;
305    let mut after_dot = 0usize;
306    let mut seen_dot = false;
307
308    for c in numeric_pat.chars() {
309        match c {
310            '.' => seen_dot = true,
311            '#' if !seen_dot => before_dot = before_dot.saturating_add(1),
312            '#' if seen_dot => after_dot = after_dot.saturating_add(1),
313            _ => {}
314        }
315    }
316
317    Ok((before_dot, after_dot))
318}
319
320fn split_int_frac(s: &str, decimals: usize) -> Result<(String, String)> {
321    if decimals == 0 {
322        return Ok((s.to_string(), String::new()));
323    }
324
325    let (int_part, frac_part) = s
326        .split_once('.')
327        .context("pattern(): expected decimal point in formatted number")?;
328
329    Ok((int_part.to_string(), frac_part.to_string()))
330}
331
332fn add_commas(int_part: &str) -> String {
333    let mut groups: Vec<String> = Vec::new();
334    let mut digits: Vec<char> = int_part.chars().collect();
335
336    while !digits.is_empty() {
337        let take = digits.len().min(3);
338        let start = digits.len().saturating_sub(take);
339        let chunk: String = digits.drain(start..).collect();
340        groups.push(chunk);
341    }
342
343    groups.reverse();
344    groups.join(",")
345}
346
347fn format_component(value: f64, numeric_pat: &str) -> Result<String> {
348    let n_hashes = numeric_pat.chars().filter(|&c| c == '#').count();
349    if n_hashes == 0 {
350        return Ok(numeric_pat.to_string());
351    }
352
353    let digits = format!("{value:.0}");
354    let mut padded = digits.clone();
355    if padded.len() < n_hashes {
356        let mut s = String::new();
357        s.extend(std::iter::repeat_n(
358            '0',
359            n_hashes.saturating_sub(padded.len()),
360        ));
361        s.push_str(&padded);
362        padded = s;
363    }
364
365    if padded.len() > n_hashes {
366        bail!("pattern(): value has more digits than component pattern allows");
367    }
368
369    let mut it = padded.chars();
370    let mut out = String::new();
371    for c in numeric_pat.chars() {
372        if c == '#' {
373            let d = it
374                .next()
375                .context("pattern(): internal digit mapping error")?;
376            out.push(d);
377        } else {
378            out.push(c);
379        }
380    }
381
382    Ok(out)
383}
384
385fn is_one_from_rendered(rendered_numeric: &str) -> bool {
386    // Normalize: trim and remove grouping commas.
387    let s = rendered_numeric.trim().replace(',', "");
388
389    // Exact integer 1.
390    if s == "1" {
391        return true;
392    }
393
394    // Decimal forms like "1.0", "1.00", or even "1." should be considered 1.
395    if let Some(frac) = s.strip_prefix("1.") {
396        // If everything after the decimal point is zeros (or empty), it's 1.
397        return frac.chars().all(|c| c == '0');
398    }
399
400    false
401}
402
403fn is_one_words(value: f64, pat: &str) -> Result<bool> {
404    let cents_run = cents_run_len(pat)?;
405    if cents_run == 0 {
406        return Ok(format!("{value:.0}") == "1");
407    }
408
409    let rounded = format!("{value:.cents_run$}");
410    let (int_part, _) = split_int_frac(&rounded, cents_run)?;
411    Ok(int_part == "1")
412}
413
414fn cents_run_len(pat: &str) -> Result<usize> {
415    let mut run_len = 0usize;
416
417    let mut it = pat.chars().peekable();
418    while let Some(c) = it.next() {
419        if c != '¢' {
420            continue;
421        }
422
423        run_len = 1;
424
425        while matches!(it.peek(), Some('¢')) {
426            it.next();
427            run_len = run_len.saturating_add(1);
428        }
429
430        // If we find another run later, bail for now.
431        for rest in it {
432            if rest == '¢' {
433                bail!("pattern(): multiple ¢ runs are not supported");
434            }
435        }
436        break;
437    }
438
439    Ok(run_len)
440}
441
442fn format_words(value: f64, pat: &str) -> Result<String> {
443    let cents_len = cents_run_len(pat)?;
444    let rounded = if cents_len == 0 {
445        format!("{value:.0}")
446    } else {
447        format!("{value:.cents_len$}")
448    };
449
450    let (int_part, frac_part) = if cents_len == 0 {
451        (rounded, String::new())
452    } else {
453        split_int_frac(&rounded, cents_len)?
454    };
455
456    let int_f64 =
457        f64::from_str(&int_part).context("pattern(): invalid integer part")?;
458    let mut words = number_to_words(int_f64, true);
459    words = normalize_words_output(&words)?;
460
461    let mut out = pat.replacen('§', &words, 1);
462
463    if cents_len > 0 {
464        let cents_pat = "¢".repeat(cents_len);
465        out = out.replace(&cents_pat, &frac_part);
466    }
467
468    Ok(out)
469}
470
471fn normalize_words_output(s: &str) -> Result<String> {
472    let mut out = s.trim().to_string();
473
474    // Some implementations add a trailing marker like "*".
475    out = out.trim_end_matches('*').trim().to_string();
476
477    // Use spaces rather than hyphens, and omit commas.
478    out = out.replace('-', " ");
479    out = out.replace(',', "");
480
481    // If the words converter appends "and 00/100" for integer values, strip it.
482    let re = Regex::new(r"\s+and\s+0+/100$")?;
483    out = re.replace(&out, "").to_string();
484
485    // Collapse whitespace.
486    let ws = Regex::new(r"\s+")?;
487    out = ws.replace_all(out.trim(), " ").to_string();
488
489    Ok(out)
490}
491
492#[cfg(test)]
493#[allow(
494    clippy::panic,
495    clippy::expect_used,
496    clippy::unwrap_used,
497    clippy::unwrap_in_result,
498    clippy::panic_in_result_fn,
499    clippy::indexing_slicing,
500    clippy::arithmetic_side_effects,
501    reason = "Standard repository test boilerplate"
502)]
503mod tests {
504    use super::*;
505
506    #[crate::ctb_test]
507    fn examples_fixed_decimal_and_commas() -> Result<()> {
508        assert_eq!(pattern(1234.56, "#")?, "1235");
509        assert_eq!(pattern(1234.56, "#.#")?, "1234.6");
510        assert_eq!(pattern(1234.56, "#.##")?, "1234.56");
511        assert_eq!(pattern(1234.56, "#.####")?, "1234.5600");
512
513        assert_eq!(pattern(1234.56, "#,.##")?, "1,234.56");
514        assert_eq!(pattern(1234.56, "$#,.##")?, "$1,234.56");
515        assert_eq!(pattern(1234.56, "#,.## kg")?, "1,234.56 kg");
516        Ok(())
517    }
518
519    #[crate::ctb_test]
520    fn examples_scientific() -> Result<()> {
521        assert_eq!(pattern(1234.56, "#e")?, "1e+3");
522        assert_eq!(pattern(1234.56, "#.#E")?, "1.2e+3");
523        assert_eq!(pattern(1234.56, "#.######E")?, "1.234560e+3");
524        assert_eq!(pattern(1234.56, "#.#E kg")?, "1.2e+3 kg");
525        Ok(())
526    }
527
528    #[crate::ctb_test]
529    fn examples_negative() -> Result<()> {
530        assert_eq!(pattern(-1234.56, "#.##")?, "-1234.56");
531        assert_eq!(pattern(-1234.56, "#.##-")?, "1234.56-");
532        assert_eq!(pattern(-1234.56, "(#.##)")?, "(1234.56)");
533        assert_eq!(pattern(1234.56, "(#.##)")?, "1234.56");
534        Ok(())
535    }
536
537    #[crate::ctb_test]
538    fn examples_leading_zeros_and_components() -> Result<()> {
539        assert_eq!(pattern(123.0, "#####")?, "00123");
540        assert_eq!(pattern(1234.0, "#####")?, "01234");
541        assert_eq!(pattern(12345.0, "#####")?, "12345");
542
543        assert_eq!(pattern(219_204_349.0, "###-##-####")?, "219-20-4349");
544        assert_eq!(pattern(5_293_672.0, "###-####")?, "529-3672");
545        assert_eq!(pattern(241_018.0, "L## R## L##")?, "L24 R10 L18");
546        Ok(())
547    }
548
549    #[crate::ctb_test]
550    fn examples_plural_suffix_and_words() -> Result<()> {
551        assert_eq!(pattern(1.0, "# mile~")?, "1 mile");
552        assert_eq!(pattern(5.0, "# mile~")?, "5 miles");
553        assert_eq!(pattern(5.0, "# goose~")?, "5 geese");
554
555        assert_eq!(pattern(312.0, "§")?, "Three hundred twelve");
556        assert_eq!(
557            pattern(42.29, "§ dollar~ and ¢¢/100")?,
558            "Forty two dollars and 29/100"
559        );
560        assert_eq!(
561            pattern(42.09, "§ dollar~ and ¢¢/100")?,
562            "Forty two dollars and 09/100"
563        );
564        Ok(())
565    }
566
567    #[crate::ctb_test]
568    fn test_pattern_cents_variations_and_errors() -> Result<()> {
569        assert_eq!(
570            pattern(0.50, "§ dollar~ and ¢¢/100")?,
571            "Zero dollars and 50/100"
572        );
573        assert_eq!(
574            pattern(1.00, "§ dollar~ and ¢¢/100")?,
575            "One dollar and 00/100"
576        );
577        assert_eq!(
578            pattern(42.125, "§ and ¢¢¢/1000")?,
579            "Forty two and 125/1000"
580        );
581        assert_eq!(pattern(100.0, "§ and ¢¢/100")?, "One hundred and 00/100");
582
583        // Multiple distinct runs of ¢ are disallowed in Panorama patterns
584        pattern(42.29, "§ ¢¢ and ¢¢").unwrap_err();
585        Ok(())
586    }
587}