Skip to main content

search_core/cost/decimal/
parse.rs

1//! Exact parsing of [`Decimal`] from decimal text, for costs read from files
2//! such as PDDL action costs.
3
4use core::fmt;
5use core::str::FromStr;
6
7use super::Decimal;
8
9/// Why a string is not a valid [`Decimal<K>`].
10#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum ParseDecimalError {
13    /// The string, or the whole part before the point, is empty.
14    Empty,
15    /// A character other than an ASCII digit and one `.` between digits, such as a
16    /// sign, whitespace, an exponent or a trailing `.`.
17    InvalidDigit,
18    /// More fraction digits than the `K` decimal places, even if the extra digits are zeros:
19    /// the rule is the digit count, not whether the value could be represented.
20    TooManyFractionDigits,
21    /// The value exceeds the largest `Decimal<K>`, `u64::MAX` raw units.
22    Overflow,
23}
24
25impl fmt::Display for ParseDecimalError {
26    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
27        f.write_str(match self {
28            Self::Empty => "cannot parse a decimal cost from an empty string",
29            Self::InvalidDigit => "invalid character in a decimal cost",
30            Self::TooManyFractionDigits => "more fraction digits than the cost's decimal places",
31            Self::Overflow => "decimal cost too large",
32        })
33    }
34}
35
36impl core::error::Error for ParseDecimalError {}
37
38/// Parses `whole` or `whole.fraction`, exactly.
39///
40/// Both parts are plain ASCII digits; leading zeros are fine. The fraction has
41/// 1 to `K` digits, trailing zeros included, so nothing is ever rounded: `"1.25"` is a `Decimal<2>` or
42/// `Decimal<3>` but not a `Decimal<1>`, and `Decimal<0>` takes integers only.
43///
44/// # Errors
45///
46/// - [`ParseDecimalError::Empty`] for `""` or a missing whole part (`".5"`).
47/// - [`ParseDecimalError::InvalidDigit`] for signs, whitespace, exponents, a
48///   second `.`, or an empty fraction (`"1."`).
49/// - [`ParseDecimalError::TooManyFractionDigits`] for more than `K` fraction digits.
50/// - [`ParseDecimalError::Overflow`] when the value exceeds `u64::MAX` raw units.
51///
52/// # Examples
53///
54/// ```
55/// use search_core::{Decimal, ParseDecimalError};
56///
57/// assert_eq!("3.25".parse::<Decimal<2>>(), Ok(Decimal::from_raw(325)));
58/// assert_eq!("3.2".parse::<Decimal<2>>(), Ok(Decimal::from_raw(320)));
59/// assert_eq!("7".parse::<Decimal<2>>(), Ok(Decimal::from_raw(700)));
60/// assert_eq!("3.25".parse::<Decimal<1>>(), Err(ParseDecimalError::TooManyFractionDigits));
61/// assert_eq!("-1".parse::<Decimal<2>>(), Err(ParseDecimalError::InvalidDigit));
62/// ```
63impl<const K: u32> FromStr for Decimal<K> {
64    type Err = ParseDecimalError;
65
66    fn from_str(text: &str) -> Result<Self, Self::Err> {
67        let (whole, fraction) = match text.split_once('.') {
68            Some((whole, fraction)) => (whole, Some(fraction)),
69            None => (text, None),
70        };
71
72        if whole.is_empty() {
73            return Err(ParseDecimalError::Empty);
74        }
75
76        let whole_raw = digits_value(whole)?
77            .checked_mul(Self::SCALE)
78            .ok_or(ParseDecimalError::Overflow)?;
79        let fraction_raw = match fraction {
80            Some(fraction) => fraction_raw::<K>(fraction)?,
81            None => 0,
82        };
83
84        whole_raw
85            .checked_add(fraction_raw)
86            .map(Self::from_raw)
87            .ok_or(ParseDecimalError::Overflow)
88    }
89}
90
91/// The value of a run of ASCII digits, rejecting anything else and `u64` overflow.
92///
93/// `str::parse::<u64>` is not used because it accepts a leading `+`.
94fn digits_value(digits: &str) -> Result<u64, ParseDecimalError> {
95    digits.bytes().try_fold(0_u64, |value, byte| {
96        if !byte.is_ascii_digit() {
97            return Err(ParseDecimalError::InvalidDigit);
98        }
99
100        value
101            .checked_mul(10)
102            .and_then(|value| value.checked_add(u64::from(byte - b'0')))
103            .ok_or(ParseDecimalError::Overflow)
104    })
105}
106
107/// The fraction digits as raw `10^-K` units: `"5"` is `5 · 10^(K-1)`.
108///
109/// Malformed text is [`ParseDecimalError::InvalidDigit`] first. The length is checked before
110/// the digits are summed, so an overlong fraction is always
111/// [`ParseDecimalError::TooManyFractionDigits`], never `Overflow`. After that check there
112/// are at most `K <= 19` digits, so the value is below `10^K` and cannot overflow.
113fn fraction_raw<const K: u32>(fraction: &str) -> Result<u64, ParseDecimalError> {
114    if fraction.is_empty() || !fraction.bytes().all(|byte| byte.is_ascii_digit()) {
115        return Err(ParseDecimalError::InvalidDigit);
116    }
117
118    let missing = usize::try_from(K)
119        .ok()
120        .and_then(|k| k.checked_sub(fraction.len()))
121        .ok_or(ParseDecimalError::TooManyFractionDigits)?;
122    let padding = u32::try_from(missing).expect("missing <= K, which is a u32");
123    let value = digits_value(fraction)?;
124
125    Ok(value * 10_u64.pow(padding))
126}
127
128#[cfg(test)]
129mod tests {
130    //! Unit and property tests for parsing [`Decimal`].
131
132    extern crate std;
133
134    use std::string::ToString;
135
136    use proptest::prelude::*;
137
138    use super::{Decimal, ParseDecimalError};
139
140    /// Parses `text` as a `Decimal<K>` and returns its raw value.
141    fn raw<const K: u32>(text: &str) -> Result<u64, ParseDecimalError> {
142        text.parse::<Decimal<K>>().map(Decimal::raw)
143    }
144
145    /// Whole numbers, short fractions and leading zeros parse exactly.
146    #[test]
147    fn parses_valid_text() {
148        assert_eq!(raw::<2>("0"), Ok(0));
149        assert_eq!(raw::<2>("12"), Ok(1_200));
150        assert_eq!(raw::<2>("1.5"), Ok(150));
151        assert_eq!(raw::<2>("1.05"), Ok(105));
152        assert_eq!(raw::<2>("007.50"), Ok(750));
153        assert_eq!(raw::<0>("42"), Ok(42));
154    }
155
156    /// Signs, whitespace, exponents, stray points and empty parts are rejected.
157    #[test]
158    fn rejects_malformed_text() {
159        assert_eq!(raw::<2>(""), Err(ParseDecimalError::Empty));
160        assert_eq!(raw::<2>(".5"), Err(ParseDecimalError::Empty));
161        for text in ["+1", "-1", " 1", "1 ", "1e2", "1.", "1.2.3", "1,5", "x"] {
162            assert_eq!(
163                raw::<2>(text),
164                Err(ParseDecimalError::InvalidDigit),
165                "{text:?}"
166            );
167        }
168    }
169
170    /// More than `K` fraction digits are rejected by count, trailing zeros too, and
171    /// regardless of how large the digits are.
172    #[test]
173    fn rejects_too_many_fraction_digits() {
174        assert_eq!(
175            raw::<2>("0.99999999999999999999"),
176            Err(ParseDecimalError::TooManyFractionDigits)
177        );
178        assert_eq!(
179            raw::<1>("1.25"),
180            Err(ParseDecimalError::TooManyFractionDigits)
181        );
182        assert_eq!(
183            raw::<1>("1.50"),
184            Err(ParseDecimalError::TooManyFractionDigits)
185        );
186        assert_eq!(
187            raw::<0>("1.0"),
188            Err(ParseDecimalError::TooManyFractionDigits)
189        );
190    }
191
192    /// The bounds of `u64` raw units: the maximum parses, one more unit overflows.
193    #[test]
194    fn checks_overflow() {
195        assert_eq!(raw::<19>("1.8446744073709551615"), Ok(u64::MAX));
196        assert_eq!(
197            raw::<19>("1.8446744073709551616"),
198            Err(ParseDecimalError::Overflow)
199        );
200        assert_eq!(raw::<19>("2"), Err(ParseDecimalError::Overflow));
201        assert_eq!(
202            raw::<0>("18446744073709551616"),
203            Err(ParseDecimalError::Overflow)
204        );
205        assert_eq!(
206            raw::<2>("99999999999999999999999"),
207            Err(ParseDecimalError::Overflow)
208        );
209    }
210
211    /// Each error has a readable message.
212    #[test]
213    fn errors_display() {
214        assert_eq!(
215            ParseDecimalError::TooManyFractionDigits.to_string(),
216            "more fraction digits than the cost's decimal places"
217        );
218    }
219
220    proptest! {
221        /// Parsing the printed value gives back the same cost, for every raw value.
222        #[test]
223        fn display_round_trips(raw: u64) {
224            let cost = Decimal::<6>::from_raw(raw);
225            prop_assert_eq!(cost.to_string().parse::<Decimal<6>>(), Ok(cost));
226        }
227
228        /// Short fractions are scaled, not truncated: `w.f` is `w · 10^K + f · 10^(K - len)`.
229        #[test]
230        fn scales_short_fractions(whole in 0..1_000_000_u64, fraction in 0..1_000_u64) {
231            let text = std::format!("{whole}.{fraction:03}");
232            prop_assert_eq!(raw::<5>(&text), Ok(whole * 100_000 + fraction * 100));
233        }
234    }
235}