Skip to main content

utils/parser/
number.rs

1use crate::number::{Integer, SignedInteger, UnsignedInteger};
2use crate::parser::{Leaf, LeafResult, ParseError, Parseable};
3use std::marker::PhantomData;
4use std::ops::RangeInclusive;
5
6#[derive(Copy, Clone)]
7pub struct UnsignedParser<U: UnsignedInteger>(PhantomData<U>);
8impl<'i, U: UnsignedInteger> Leaf<'i> for UnsignedParser<U> {
9    type Output = U;
10
11    #[inline(always)]
12    fn parse(&self, mut input: &'i [u8]) -> LeafResult<'i, Self::Output> {
13        let mut n = match input {
14            [d @ b'0'..=b'9', ..] => {
15                input = &input[1..];
16                U::from(d - b'0')
17            }
18            _ => return Err((ParseError::Expected("unsigned integer"), input)),
19        };
20
21        while let Some(&b) = input.first() {
22            let d = U::from(b).wrapping_sub(U::from(b'0'));
23            if d > U::from(9) {
24                break;
25            }
26            // Avoid checked operations until near the maximum value
27            if n >= U::MAX / U::from(10) {
28                return unsigned_near_max(n, input);
29            }
30            n = n * U::from(10) + d;
31            input = &input[1..];
32        }
33
34        Ok((n, input))
35    }
36}
37
38#[cold]
39#[inline(never)]
40fn unsigned_near_max<U: UnsignedInteger>(mut n: U, mut input: &[u8]) -> LeafResult<'_, U> {
41    while let Some(d @ b'0'..=b'9') = input.first() {
42        n = n
43            .checked_mul(U::from(10))
44            .and_then(|n| n.checked_add(U::from(d - b'0')))
45            .ok_or((ParseError::too_large(U::MAX), input))?;
46        input = &input[1..];
47    }
48    Ok((n, input))
49}
50
51#[derive(Copy, Clone)]
52pub struct SignedParser<S: SignedInteger>(PhantomData<S>);
53impl<'i, S: SignedInteger> Leaf<'i> for SignedParser<S> {
54    type Output = S;
55
56    #[expect(clippy::cast_possible_wrap)]
57    #[inline(always)]
58    fn parse(&self, mut input: &'i [u8]) -> LeafResult<'i, Self::Output> {
59        let (mut n, positive) = match input {
60            [d @ b'0'..=b'9', rem @ ..] | [b'+', d @ b'0'..=b'9', rem @ ..] => {
61                input = rem;
62                (S::from((d - b'0') as i8), true)
63            }
64            [b'-', d @ b'0'..=b'9', rem @ ..] => {
65                input = rem;
66                (S::from(-((d - b'0') as i8)), false)
67            }
68            _ => return Err((ParseError::Expected("signed integer"), input)),
69        };
70
71        if positive {
72            while let Some(&b) = input.first() {
73                let d = S::Unsigned::from(b).wrapping_sub(S::Unsigned::from(b'0'));
74                if d > S::Unsigned::from(9) {
75                    break;
76                }
77                n = n
78                    .checked_mul(S::from(10))
79                    .and_then(|n| n.checked_add(d.cast_signed()))
80                    .ok_or((ParseError::too_large(S::MAX), input))?;
81                input = &input[1..];
82            }
83        } else {
84            while let Some(&b) = input.first() {
85                let d = S::Unsigned::from(b).wrapping_sub(S::Unsigned::from(b'0'));
86                if d > S::Unsigned::from(9) {
87                    break;
88                }
89                n = n
90                    .checked_mul(S::from(10))
91                    .and_then(|n| n.checked_sub(d.cast_signed()))
92                    .ok_or((ParseError::too_small(S::MIN), input))?;
93                input = &input[1..];
94            }
95        }
96
97        Ok((n, input))
98    }
99}
100
101#[derive(Copy, Clone)]
102pub struct NonZeroParser<I: Integer + Parseable>(PhantomData<I>);
103impl<'i, I: Integer + Parseable> Leaf<'i> for NonZeroParser<I> {
104    type Output = I::NonZero;
105
106    #[inline(always)]
107    fn parse(&self, input: &'i [u8]) -> LeafResult<'i, Self::Output> {
108        let (value, remaining) = I::PARSER.parse(input)?;
109        match I::NonZero::try_from(value) {
110            Ok(value) => Ok((value, remaining)),
111            Err(_) => Err((ParseError::Expected("non-zero integer"), input)),
112        }
113    }
114}
115
116macro_rules! parser_for {
117    ($p:ident => $($n:ident: $nonzero:ident),+ $(,)?) => {$(
118        impl Parseable for std::primitive::$n {
119            type Parser = $p<std::primitive::$n>;
120            const PARSER: Self::Parser = $p(PhantomData);
121        }
122
123        #[doc = concat!("[`Leaf`] parser for [`prim@", stringify!($n), "`] values.")]
124        #[inline]
125        #[must_use]
126        pub fn $n() -> $p<std::primitive::$n> {
127            $p(PhantomData)
128        }
129
130        impl Parseable for std::num::NonZero<$n> {
131            type Parser = NonZeroParser<$n>;
132            const PARSER: Self::Parser = NonZeroParser(PhantomData);
133        }
134
135        #[doc = concat!(
136            "[`Leaf`] parser for [`NonZero<", stringify!($n), ">`](std::num::NonZero) values.",
137            "\n\n# Examples\n```\n",
138            "# use utils::parser::{self, Parser};\n",
139            "assert!(parser::", stringify!($nonzero), "().parse_complete(\"0\").is_err());\n",
140            "assert!(parser::", stringify!($nonzero), "().parse_complete(\"1\").is_ok_and(|n| n.get() == 1));\n",
141            "```"
142        )]
143        #[inline]
144        #[must_use]
145        pub fn $nonzero() -> NonZeroParser<std::primitive::$n> {
146            NonZeroParser(PhantomData)
147        }
148    )+};
149}
150parser_for! {
151    UnsignedParser =>
152    u8: nonzero_u8,
153    u16: nonzero_u16,
154    u32: nonzero_u32,
155    u64: nonzero_u64,
156    u128: nonzero_u128,
157}
158parser_for! {
159    SignedParser =>
160    i8: nonzero_i8,
161    i16: nonzero_i16,
162    i32: nonzero_i32,
163    i64: nonzero_i64,
164    i128: nonzero_i128,
165}
166
167/// Parsing as [`usize`] should be discouraged as it leads to parsers which behave differently at
168/// runtime on 32-bit and 64-bit platforms, so no `parser::usize()` function is provided.
169///
170/// However, [`Parseable`] is implemented for [`usize`] as it is safe to use [`number_range()`]
171/// with a constant hard-coded max, which will fail at compile time if the constant is too large
172/// for the platform's usize.
173impl Parseable for std::primitive::usize {
174    type Parser = UnsignedParser<std::primitive::usize>;
175    const PARSER: Self::Parser = UnsignedParser(PhantomData);
176}
177
178#[derive(Copy, Clone)]
179pub struct NumberRange<I> {
180    min: I,
181    max: I,
182}
183
184impl<'i, I: Integer + Parseable> Leaf<'i> for NumberRange<I> {
185    type Output = I;
186
187    #[inline(always)]
188    fn parse(&self, input: &'i [u8]) -> LeafResult<'i, Self::Output> {
189        let (v, remaining) = I::PARSER.parse(input)?;
190        if v < self.min {
191            Err((ParseError::too_small(self.min), input))
192        } else if v > self.max {
193            Err((ParseError::too_large(self.max), input))
194        } else {
195            Ok((v, remaining))
196        }
197    }
198}
199
200/// [`Leaf`] parser for numbers in the supplied range.
201///
202/// The type of the number to parse is inferred from the range's type.
203///
204/// See also [`byte_range`](super::byte_range).
205///
206/// # Examples
207/// ```
208/// # use utils::parser::{self, Leaf};
209/// assert_eq!(
210///     parser::number_range(100u8..=125u8).parse(b"123, 120"),
211///     Ok((123u8, &b", 120"[..]))
212/// );
213/// ```
214#[inline]
215#[must_use]
216pub fn number_range<I: Integer + Parseable>(range: RangeInclusive<I>) -> NumberRange<I> {
217    let min = *range.start();
218    let max = *range.end();
219    assert!(min <= max);
220    NumberRange { min, max }
221}
222
223#[derive(Copy, Clone)]
224pub struct Digit {}
225
226impl<'i> Leaf<'i> for Digit {
227    type Output = u8;
228
229    #[inline(always)]
230    fn parse(&self, input: &'i [u8]) -> LeafResult<'i, Self::Output> {
231        if let Some(d @ b'0'..=b'9') = input.first() {
232            Ok((d - b'0', &input[1..]))
233        } else {
234            Err((ParseError::Expected("digit"), input))
235        }
236    }
237}
238
239/// [`Leaf`] parser for single digits.
240///
241/// # Examples
242/// ```
243/// # use utils::parser::{self, Leaf};
244/// assert_eq!(
245///     parser::digit().parse(b"12345"),
246///     Ok((1u8, &b"2345"[..]))
247/// );
248/// ```
249#[inline]
250#[must_use]
251pub fn digit() -> Digit {
252    Digit {}
253}
254
255#[derive(Copy, Clone)]
256pub struct DigitsRange<U, const MIN: u128, const MAX: u128>(PhantomData<U>);
257impl<U: UnsignedInteger, const MIN: u128, const MAX: u128> DigitsRange<U, MIN, MAX> {
258    const MIN_DIGITS: usize = (MIN | 1).ilog10() as usize + 1;
259    const MAX_DIGITS: usize = (MAX | 1).ilog10() as usize + 1;
260
261    // Ensure too large check is omitted when MAX is the largest MAX_DIGITS number.
262    // n < MIN is already skipped when MIN = 0.
263    const CHECK_MAX: bool = MAX.saturating_add(1).ilog10() == (MAX | 1).ilog10();
264}
265impl<'i, U: UnsignedInteger, const MIN: u128, const MAX: u128> Leaf<'i>
266    for DigitsRange<U, MIN, MAX>
267{
268    type Output = U;
269
270    #[inline(always)]
271    fn parse(&self, input: &'i [u8]) -> LeafResult<'i, Self::Output> {
272        const {
273            assert!(MIN <= MAX);
274            assert!(Self::MAX_DIGITS <= U::SAFE_DIGITS);
275        }
276
277        // Use a fixed-size chunk to avoid bounds checks
278        let (n, rem) = if let Some((chunk, mut rem)) = input.split_at_checked(Self::MAX_DIGITS) {
279            let mut n = U::ZERO;
280            for (i, &b) in chunk.iter().enumerate().take(Self::MIN_DIGITS) {
281                let d = U::from(b).wrapping_sub(U::from(b'0'));
282                if d > U::from(9) {
283                    // cold_path makes these predictable branches instead of conditional moves
284                    std::hint::cold_path();
285                    return Err((ParseError::Expected("digit"), &input[i..]));
286                }
287                n = n * U::from(10) + d;
288            }
289            for (i, &b) in chunk.iter().enumerate().skip(Self::MIN_DIGITS) {
290                let d = U::from(b).wrapping_sub(U::from(b'0'));
291                if d > U::from(9) {
292                    std::hint::cold_path();
293                    rem = &input[i..];
294                    break;
295                }
296                n = n * U::from(10) + d;
297            }
298            (n, rem)
299        } else {
300            digits_near_end(input, Self::MIN_DIGITS)?
301        };
302
303        if n < MIN.try_into().unwrap() {
304            Err((ParseError::too_small(MIN), input))
305        } else if Self::CHECK_MAX && n > MAX.try_into().unwrap() {
306            Err((ParseError::too_large(MAX), input))
307        } else {
308            Ok((n, rem))
309        }
310    }
311}
312
313#[cold]
314#[inline(never)]
315fn digits_near_end<U: UnsignedInteger>(input: &[u8], min_digits: usize) -> LeafResult<'_, U> {
316    // Always less than max_digits
317    let len = input.iter().take_while(|b| b.is_ascii_digit()).count();
318    if len < min_digits {
319        return Err((ParseError::Expected("digit"), &input[len..]));
320    }
321
322    let n = input[..len]
323        .iter()
324        .fold(U::ZERO, |n, &d| n * U::from(10) + U::from(d - b'0'));
325    Ok((n, &input[len..]))
326}
327
328/// [`Leaf`] parser for unsigned numbers, reading only digits matching the supplied range.
329///
330/// This can be faster than [`number_range`] for ranges with a small number of digits, but unlike
331/// the normal number parsers it does not check for trailing digits. It should be followed by a
332/// parser that wouldn't match digits to ensure the number is in the intended range.
333///
334/// `MIN` and `MAX` must match the supplied range, and all numbers with as many digits as `MAX`
335/// must fit in the unsigned type.
336///
337/// See also [`parser::digits_range!`](crate::parser::digits_range!).
338///
339/// # Examples
340/// ```
341/// # use utils::parser::{self, Leaf};
342/// let parser = parser::digits_range::<_, 1, 12>(1u32..=12);
343/// assert_eq!(parser.parse(b"07-21"), Ok((7, &b"-21"[..])));
344/// assert_eq!(parser.parse(b"123"), Ok((12, &b"3"[..])));
345/// assert!(parser.parse(b"13-21").is_err());
346/// ```
347#[must_use]
348#[inline(always)]
349#[expect(clippy::inline_always, reason = "ensure assert is optimized out")]
350pub fn digits_range<U: UnsignedInteger, const MIN: u128, const MAX: u128>(
351    range: RangeInclusive<U>,
352) -> DigitsRange<U, MIN, MAX> {
353    assert!(*range.start() == MIN.try_into().unwrap() && *range.end() == MAX.try_into().unwrap());
354    DigitsRange(PhantomData)
355}