Skip to main content

nautilus_core/string/
parsing.rs

1// -------------------------------------------------------------------------------------------------
2//  Copyright (C) 2015-2026 Nautech Systems Pty Ltd. All rights reserved.
3//  https://nautechsystems.io
4//
5//  Licensed under the GNU Lesser General Public License Version 3.0 (the "License");
6//  You may not use this file except in compliance with the License.
7//  You may obtain a copy of the License at https://www.gnu.org/licenses/lgpl-3.0.en.html
8//
9//  Unless required by applicable law or agreed to in writing, software
10//  distributed under the License is distributed on an "AS IS" BASIS,
11//  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12//  See the License for the specific language governing permissions and
13//  limitations under the License.
14// -------------------------------------------------------------------------------------------------
15
16//! Core parsing functions.
17
18use crate::correctness::{CorrectnessResult, check_predicate_true};
19
20/// Clamps a length to `u8::MAX` with optional debug logging.
21#[inline]
22#[must_use]
23#[expect(
24    clippy::cast_possible_truncation,
25    reason = "Intentional for parsing, value range validated"
26)]
27fn clamp_precision_with_log(len: usize, context: &str, input: &str) -> u8 {
28    if len > u8::MAX as usize {
29        log::debug!(
30            "{} precision clamped from {} to {} for input: {}",
31            context,
32            len,
33            u8::MAX,
34            input
35        );
36    }
37    len.min(u8::MAX as usize) as u8
38}
39
40/// Computes decimal precision from a scientific-notation string.
41///
42/// Precision is `max(0, mantissa_fractional_digits - exponent)`, clamped to
43/// `u8::MAX` (255). When `trim_trailing_zeros` is true, trailing zeros in the
44/// mantissa's fractional part are stripped before counting.
45///
46/// Absurd exponents that overflow `i64` clamp to 255 (negative) or 0 (positive)
47/// without panicking.
48fn precision_from_scientific(
49    s: &str,
50    e_pos: usize,
51    trim_trailing_zeros: bool,
52) -> CorrectnessResult<u8> {
53    let mantissa = &s[..e_pos];
54    let exponent_str = &s[e_pos + 1..];
55
56    let frac_digits = mantissa.split_once('.').map_or(0, |(_, frac)| {
57        if trim_trailing_zeros {
58            frac.trim_end_matches('0').len()
59        } else {
60            frac.len()
61        }
62    });
63
64    let exponent: i64 = if let Ok(v) = exponent_str.parse::<i64>() {
65        v
66    } else {
67        let (digits, is_negative) = exponent_str
68            .strip_prefix('-')
69            .map(|rest| (rest, true))
70            .or_else(|| exponent_str.strip_prefix('+').map(|rest| (rest, false)))
71            .unwrap_or((exponent_str, false));
72
73        check_predicate_true(
74            !digits.is_empty(),
75            "Invalid scientific notation format: missing exponent value",
76        )?;
77        check_predicate_true(
78            digits.chars().all(|c| c.is_ascii_digit()),
79            &format!(
80                "Invalid scientific notation exponent '{exponent_str}': must be a valid number"
81            ),
82        )?;
83
84        return Ok(if is_negative { u8::MAX } else { 0 });
85    };
86
87    let precision = i64::try_from(frac_digits)
88        .unwrap_or(i64::MAX)
89        .saturating_sub(exponent)
90        .clamp(0, i64::from(u8::MAX));
91
92    #[expect(
93        clippy::cast_possible_truncation,
94        clippy::cast_sign_loss,
95        reason = "clamped to 0..=u8::MAX above"
96    )]
97    let precision = precision as u8;
98
99    Ok(precision)
100}
101
102/// Returns the decimal precision inferred from the given string.
103///
104/// For scientific notation (e.g., "1e-300", "1.5e-2"), the precision accounts
105/// for both the mantissa's fractional digits and the signed exponent:
106/// `max(0, fractional_digits - exponent)`, clamped to `u8::MAX` (255).
107///
108/// # Errors
109///
110/// Returns an error if a scientific exponent is missing or non-numeric.
111pub fn precision_from_str(s: &str) -> CorrectnessResult<u8> {
112    let s = s.trim();
113    if let Some(e_pos) = s.find(['e', 'E']) {
114        return precision_from_scientific(s, e_pos, false);
115    }
116
117    if let Some((_, decimal_part)) = s.split_once('.') {
118        Ok(clamp_precision_with_log(decimal_part.len(), "Decimal", s))
119    } else {
120        Ok(0)
121    }
122}
123
124/// Returns the minimum increment precision inferred from the given string,
125/// ignoring trailing zeros.
126///
127/// For scientific notation (e.g., "1e-300", "1.5e-2"), trailing zeros in the
128/// mantissa are stripped before computing precision, matching the behavior of
129/// [`precision_from_str`].
130#[must_use]
131pub fn min_increment_precision_from_str(s: &str) -> u8 {
132    let s = s.trim();
133    if let Some(e_pos) = s.find(['e', 'E']) {
134        return precision_from_scientific(s, e_pos, true).unwrap_or(0);
135    }
136
137    if let Some(dot_pos) = s.find('.') {
138        let decimal_part = &s[dot_pos + 1..];
139        match decimal_part.as_bytes().iter().rposition(|&b| b != b'0') {
140            Some(index) => clamp_precision_with_log(index + 1, "Minimum increment", s),
141            None => clamp_precision_with_log(decimal_part.len(), "Decimal", s),
142        }
143    } else {
144        0
145    }
146}
147
148#[cfg(test)]
149mod tests {
150    use rstest::rstest;
151
152    use super::*;
153
154    #[rstest]
155    #[case("", 0)]
156    #[case("0", 0)]
157    #[case("1.0", 1)]
158    #[case("1.00", 2)]
159    #[case("1.23456789", 8)]
160    #[case("123456.789101112", 9)]
161    #[case("0.000000001", 9)]
162    #[case("1e-1", 1)]
163    #[case("1e-2", 2)]
164    #[case("1e-3", 3)]
165    #[case("1e8", 0)]
166    #[case("1e99999999999999999999", 0)]
167    #[case("1e+99999999999999999999", 0)]
168    #[case("-1.23", 2)]
169    #[case("-1e-2", 2)]
170    #[case("1E-2", 2)]
171    #[case("1.5e-2", 3)]
172    #[case("1.23e-2", 4)]
173    #[case("1.5e2", 0)]
174    #[case("1.5E2", 0)]
175    #[case("1.5e+2", 0)]
176    #[case("1.5e0", 1)]
177    #[case("1.5e-1", 2)]
178    #[case("  1.23", 2)]
179    #[case("1.23  ", 2)]
180    fn test_precision_from_str(#[case] s: &str, #[case] expected: u8) {
181        let result = precision_from_str(s).unwrap();
182        assert_eq!(result, expected);
183    }
184
185    #[rstest]
186    #[case("", 0)]
187    #[case("0", 0)]
188    #[case("1.0", 1)]
189    #[case("1.00", 2)]
190    #[case("1.23456789", 8)]
191    #[case("123456.789101112", 9)]
192    #[case("0.000000001", 9)]
193    #[case("1e-1", 1)]
194    #[case("1e-2", 2)]
195    #[case("1e-3", 3)]
196    #[case("1e8", 0)]
197    #[case("1e99999999999999999999", 0)]
198    #[case("1e+99999999999999999999", 0)]
199    #[case("-1.23", 2)]
200    #[case("-1e-2", 2)]
201    #[case("1E-2", 2)]
202    #[case("1.5e-2", 3)]
203    #[case("1.23e-2", 4)]
204    #[case("1.5e2", 0)]
205    #[case("1.50e-2", 3)]
206    #[case("1.0e-2", 2)]
207    #[case("  1.23", 2)]
208    #[case("1.23  ", 2)]
209    #[case("1.010", 2)]
210    #[case("1.00100", 3)]
211    #[case("0.0001000", 4)]
212    #[case("1.000000000", 9)]
213    fn test_min_increment_precision_from_str(#[case] s: &str, #[case] expected: u8) {
214        let result = min_increment_precision_from_str(s);
215        assert_eq!(result, expected);
216    }
217
218    #[rstest]
219    fn test_precision_from_str_large_exponent_clamped() {
220        // u8::MAX is 255, so 999 should be clamped to 255
221        let result = precision_from_str("1e-999").unwrap();
222        assert_eq!(result, 255);
223    }
224
225    #[rstest]
226    fn test_precision_from_str_very_large_exponent_clamped() {
227        // Very large exponents should also be clamped to u8::MAX
228        let result = precision_from_str("1e-300").unwrap();
229        assert_eq!(result, 255);
230
231        let result = precision_from_str("1e-1000000").unwrap();
232        assert_eq!(result, 255);
233    }
234
235    #[rstest]
236    fn test_precision_from_str_invalid_exponent_not_numeric() {
237        let error = precision_from_str("1e-abc").unwrap_err();
238        assert_eq!(
239            error.to_string(),
240            "Invalid scientific notation exponent '-abc': must be a valid number"
241        );
242    }
243
244    #[rstest]
245    fn test_precision_from_str_malformed_scientific_notation() {
246        let error = precision_from_str("1e-").unwrap_err();
247        assert_eq!(
248            error.to_string(),
249            "Invalid scientific notation format: missing exponent value"
250        );
251    }
252
253    #[rstest]
254    fn test_precision_from_str_edge_case_max_u8() {
255        // u8::MAX = 255, should work
256        let result = precision_from_str("1e-255").unwrap();
257        assert_eq!(result, 255);
258    }
259
260    #[rstest]
261    fn test_precision_from_str_just_above_max_u8() {
262        // 256 should be clamped to 255
263        let result = precision_from_str("1e-256").unwrap();
264        assert_eq!(result, 255);
265    }
266
267    #[rstest]
268    fn test_precision_from_str_u32_overflow() {
269        // Exponent > u32::MAX (4294967296) should be clamped to 255
270        let result = precision_from_str("1e-4294967296").unwrap();
271        assert_eq!(result, 255);
272    }
273
274    #[rstest]
275    fn test_precision_from_str_u64_overflow() {
276        // Exponent > u64::MAX should be clamped to 255
277        let result = precision_from_str("1e-99999999999999999999").unwrap();
278        assert_eq!(result, 255);
279    }
280
281    #[rstest]
282    fn test_min_increment_precision_from_str_large_exponent() {
283        // Large exponents should be clamped to u8::MAX (255), not return 0
284        let result = min_increment_precision_from_str("1e-300");
285        assert_eq!(result, 255);
286    }
287
288    #[rstest]
289    fn test_min_increment_precision_from_str_very_large_exponent() {
290        // Very large exponents should also be clamped to 255
291        let result = min_increment_precision_from_str("1e-99999999999999999999");
292        assert_eq!(result, 255);
293    }
294
295    #[rstest]
296    fn test_min_increment_precision_from_str_consistency() {
297        // Should match precision_from_str for large exponents
298        let input = "1e-1000";
299        let precision = precision_from_str(input).unwrap();
300        let min_precision = min_increment_precision_from_str(input);
301        assert_eq!(precision, min_precision);
302        assert_eq!(precision, 255);
303    }
304
305    #[rstest]
306    fn test_precision_from_str_i64_min_exponent_clamped() {
307        // Exponent equal to i64::MIN must saturate, not overflow the subtraction
308        let result = precision_from_str("1e-9223372036854775808").unwrap();
309        assert_eq!(result, 255);
310    }
311
312    #[rstest]
313    fn test_min_increment_precision_from_str_empty_exponent() {
314        // Empty exponent should return 0, not u8::MAX
315        let result = min_increment_precision_from_str("1e-");
316        assert_eq!(result, 0);
317    }
318
319    #[rstest]
320    #[case(
321        "1E-ABC",
322        "Invalid scientific notation exponent '-ABC': must be a valid number"
323    )]
324    #[case(
325        "1eE-2",
326        "Invalid scientific notation exponent 'E-2': must be a valid number"
327    )]
328    #[case("1E-", "Invalid scientific notation format: missing exponent value")]
329    fn test_scientific_precision_reports_original_exponent(
330        #[case] input: &str,
331        #[case] expected: &str,
332    ) {
333        assert_eq!(min_increment_precision_from_str(input), 0);
334        let error = precision_from_str(input).unwrap_err();
335        assert_eq!(error.to_string(), expected);
336    }
337
338    #[rstest]
339    #[case("1.\u{e9}00", 2)]
340    #[case("1.\u{660}00", 2)]
341    #[case("1.00\u{660}", 4)]
342    #[case("1.", 0)]
343    fn test_minimum_precision_preserves_utf8_byte_length(
344        #[case] input: &str,
345        #[case] expected: u8,
346    ) {
347        assert_eq!(min_increment_precision_from_str(input), expected);
348    }
349
350    #[rstest]
351    fn test_minimum_precision_clamps_all_zero_fraction() {
352        let input = format!("1.{}", "0".repeat(256));
353        assert_eq!(min_increment_precision_from_str(&input), u8::MAX);
354    }
355}