time/parsing/
shim.rs

1//! Extension traits for things either not implemented or not yet stable in the MSRV.
2
3/// Marker trait for integer types.
4pub(crate) trait Integer: Sized {
5    /// The maximum number of digits that this type can have.
6    const MAX_NUM_DIGITS: u8;
7    /// The zero value for this type.
8    const ZERO: Self;
9
10    /// Push a digit onto the end of this integer, assuming no overflow.
11    ///
12    /// This is equivalent to `self * 10 + digit`.
13    fn push_digit(self, digit: u8) -> Self;
14
15    /// Push a digit onto the end of this integer, returning `None` on overflow.
16    ///
17    /// This is equivalent to `self.checked_mul(10)?.checked_add(digit)`.
18    fn checked_push_digit(self, digit: u8) -> Option<Self>;
19}
20
21/// Parse the given types from bytes.
22macro_rules! impl_parse_bytes {
23    ($($t:ty)*) => ($(
24        impl Integer for $t {
25            const MAX_NUM_DIGITS: u8 = match Self::MAX.checked_ilog10() {
26                Some(digits) => digits as u8 + 1,
27                None => 1,
28            };
29
30            const ZERO: Self = 0;
31
32            #[allow(trivial_numeric_casts, reason = "macro-generated code")]
33            #[inline]
34            fn push_digit(self, digit: u8) -> Self {
35                self * 10 + digit as Self
36            }
37
38            #[allow(trivial_numeric_casts, reason = "macro-generated code")]
39            #[inline]
40            fn checked_push_digit(self, digit: u8) -> Option<Self> {
41                self.checked_mul(10)?.checked_add(digit as Self)
42            }
43        }
44    )*)
45}
46impl_parse_bytes! { u8 u16 u32 u128 }