search_core/cost/decimal/
parse.rs1use core::fmt;
5use core::str::FromStr;
6
7use super::Decimal;
8
9#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
11#[non_exhaustive]
12pub enum ParseDecimalError {
13 Empty,
15 InvalidDigit,
18 TooManyFractionDigits,
21 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
38impl<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
91fn 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
107fn 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 extern crate std;
133
134 use std::string::ToString;
135
136 use proptest::prelude::*;
137
138 use super::{Decimal, ParseDecimalError};
139
140 fn raw<const K: u32>(text: &str) -> Result<u64, ParseDecimalError> {
142 text.parse::<Decimal<K>>().map(Decimal::raw)
143 }
144
145 #[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 #[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 #[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 #[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 #[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 #[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 #[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}