Skip to main content

jiff/util/
parse.rs

1use jcore::bounds::Bounds;
2
3use crate::{
4    Error,
5    error::util::{ParseFractionError, ParseIntError},
6};
7
8/// Parses an `i64` number from the beginning to the end of the given slice of
9/// ASCII digit characters.
10///
11/// If any byte in the given slice is not `[0-9]`, then this returns an error.
12/// Similarly, if the number parsed does not fit into a `i64`, then this
13/// returns an error. Notably, this routine does not permit parsing a negative
14/// integer. (We use `i64` because everything in this crate uses signed
15/// integers, and because a higher level routine might want to parse the sign
16/// and then apply it to the result of this routine.)
17#[cfg_attr(feature = "perf-inline", inline(always))]
18pub(crate) fn i64(bytes: &[u8]) -> Result<i64, ParseIntError> {
19    if bytes.is_empty() {
20        return Err(ParseIntError::NoDigitsFound);
21    }
22    let mut n: i64 = 0;
23    for &byte in bytes {
24        if !(b'0' <= byte && byte <= b'9') {
25            return Err(ParseIntError::InvalidDigit(byte));
26        }
27        let digit = i64::from(byte - b'0');
28        n = n
29            .checked_mul(10)
30            .and_then(|n| n.checked_add(digit))
31            .ok_or(ParseIntError::TooBig)?;
32    }
33    Ok(n)
34}
35
36/// Like `self::i64`, but also does a boundary check for the given type.
37///
38/// # Errors
39///
40/// If the given slice is not a valid integer (i.e., overflow or contains
41/// anything other than `[0-9]`) or is not in the bounds for the given `Bounds`
42/// implementation, then an error is returned.
43///
44/// Note that the error can either be a parsing error or it can be a
45/// boundary error.
46#[cfg_attr(feature = "perf-inline", inline(always))]
47pub(crate) fn bi64<B>(bytes: &[u8]) -> Result<B::Primitive, Error>
48where
49    B: Bounds,
50    Error: From<B::Error>,
51{
52    Ok(B::check(self::i64(bytes)?)?)
53}
54
55/// Parsed an optional `u64` that is a prefix of `bytes`.
56///
57/// If no digits (`[0-9]`) were found at the beginning of `bytes`, then `None`
58/// is returned.
59///
60/// Note that this is safe to call on untrusted input. It will not attempt
61/// to consume more input than could possibly fit into a parsed integer.
62///
63/// Since this returns a `u64`, it is possible that an integer that cannot
64/// fit into an `i64` is returned. Callers should handle this. (Indeed,
65/// `DurationUnits` handles this case.)
66///
67/// # Errors
68///
69/// When the parsed integer cannot fit into a `u64`.
70#[cfg_attr(feature = "perf-inline", inline(always))]
71pub(crate) fn u64_prefix(
72    bytes: &[u8],
73) -> Result<(Option<u64>, &[u8]), ParseIntError> {
74    // Discovered via `u64::MAX.to_string().len()`.
75    const MAX_U64_DIGITS: usize = 20;
76
77    let mut digit_count = 0;
78    let mut n: u64 = 0;
79    while digit_count <= MAX_U64_DIGITS {
80        let Some(&byte) = bytes.get(digit_count) else { break };
81        if !byte.is_ascii_digit() {
82            break;
83        }
84        digit_count += 1;
85        // OK because we confirmed `byte` is an ASCII digit.
86        let digit = u64::from(byte - b'0');
87        n = n
88            .checked_mul(10)
89            .and_then(|n| n.checked_add(digit))
90            .ok_or(ParseIntError::TooBig)?;
91    }
92    if digit_count == 0 {
93        return Ok((None, bytes));
94    }
95    Ok((Some(n), &bytes[digit_count..]))
96}
97
98/// Parses a `u32` fractional number from the beginning to the end of the given
99/// slice of ASCII digit characters.
100///
101/// The fraction's maximum precision is always 9 digits. The returned integer
102/// will always be in units of `10^{max_precision}`. For example, this
103/// will parse a fractional amount of seconds with a maximum precision of
104/// nanoseconds.
105///
106/// If any byte in the given slice is not `[0-9]`, then this returns an error.
107/// Notably, this routine does not permit parsing a negative integer.
108pub(crate) fn fraction(bytes: &[u8]) -> Result<u32, ParseFractionError> {
109    if bytes.is_empty() {
110        return Err(ParseFractionError::NoDigitsFound);
111    } else if bytes.len() > ParseFractionError::MAX_PRECISION {
112        return Err(ParseFractionError::TooManyDigits);
113    }
114    let mut n: u32 = 0;
115    for &byte in bytes {
116        let digit = match byte.checked_sub(b'0') {
117            None => {
118                return Err(ParseFractionError::InvalidDigit(byte));
119            }
120            Some(digit) if digit > 9 => {
121                return Err(ParseFractionError::InvalidDigit(byte));
122            }
123            Some(digit) => {
124                if true {
    if !(0..=9).contains(&digit) {
        ::core::panicking::panic("assertion failed: (0..=9).contains(&digit)")
    };
};debug_assert!((0..=9).contains(&digit));
125                u32::from(digit)
126            }
127        };
128        n = n
129            .checked_mul(10)
130            .and_then(|n| n.checked_add(digit))
131            .ok_or_else(|| ParseFractionError::TooBig)?;
132    }
133    for _ in bytes.len()..ParseFractionError::MAX_PRECISION {
134        n = n.checked_mul(10).ok_or_else(|| ParseFractionError::TooBig)?;
135    }
136    Ok(n)
137}
138
139/// Parses an `OsStr` into a `&str` when `&[u8]` isn't easily available.
140///
141/// This is effectively `OsStr::to_str`, but with a slightly better error
142/// message.
143#[cfg(any(feature = "tz-system", feature = "tzdb-zoneinfo"))]
144pub(crate) fn os_str_utf8<'o, O>(
145    os_str: &'o O,
146) -> Result<&'o str, crate::error::util::OsStrUtf8Error>
147where
148    O: ?Sized + AsRef<std::ffi::OsStr>,
149{
150    let os_str = os_str.as_ref();
151    os_str
152        .to_str()
153        .ok_or_else(|| crate::error::util::OsStrUtf8Error::from(os_str))
154}
155
156/// Splits the given input into two slices at the given position.
157///
158/// If the position is greater than the length of the slice given, then this
159/// returns `None`.
160#[cfg_attr(feature = "perf-inline", inline(always))]
161pub(crate) fn split(input: &[u8], at: usize) -> Option<(&[u8], &[u8])> {
162    if at > input.len() { None } else { Some(input.split_at(at)) }
163}
164
165/// Returns a function that converts two slices to an offset.
166///
167/// It takes the starting point as input and returns a function that, when
168/// given an ending point (greater than or equal to the starting point), then
169/// the corresponding pointers are subtracted and an offset relative to the
170/// starting point is returned.
171///
172/// This is useful as a helper function in parsing routines that use slices
173/// but want to report offsets.
174///
175/// # Panics
176///
177/// This may panic if the ending point is not a suffix slice of `start`.
178pub(crate) fn offseter<'a>(
179    start: &'a [u8],
180) -> impl Fn(&'a [u8]) -> usize + 'a {
181    move |end| (end.as_ptr() as usize) - (start.as_ptr() as usize)
182}
183
184/// Returns a function that converts two slices to the slice between them.
185///
186/// This takes a starting point as input and returns a function that, when
187/// given an ending point (greater than or equal to the starting point), it
188/// returns a slice beginning at the starting point and ending just at the
189/// ending point.
190///
191/// This is useful as a helper function in parsing routines.
192///
193/// # Panics
194///
195/// This may panic if the ending point is not a suffix slice of `start`.
196pub(crate) fn slicer<'a>(
197    start: &'a [u8],
198) -> impl Fn(&'a [u8]) -> &'a [u8] + 'a {
199    let mkoffset = offseter(start);
200    move |end| {
201        let offset = mkoffset(end);
202        &start[..offset]
203    }
204}