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 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
167impl 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#[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#[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 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 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 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 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#[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}