Skip to main content

utils/parser/
leaf.rs

1use crate::parser::then::Then2;
2use crate::parser::{ParseError, ParseState, Parser, ParserResult};
3
4/// [`Result`] type returned by [`Leaf::parse`].
5///
6/// Contains the error information inline, unlike [`ParserResult`].
7pub type LeafResult<'i, T> = Result<(T, &'i [u8]), (ParseError, &'i [u8])>;
8
9/// Trait implemented by atomic, fail‑fast parsers.
10///
11/// Leaf parsers always return the first error they encounter without backtracking.
12#[must_use]
13pub trait Leaf<'i>: Sized {
14    /// Type of the value produced by [`parse`](Self::parse) when successful.
15    type Output;
16
17    /// Parse one item, returning immediately on error without backtracking.
18    ///
19    /// Returns a tuple of the successfully parsed [`Output`](Self::Output) value and the
20    /// remaining bytes, or a tuple containing a [`ParseError`] and the location of the error.
21    fn parse(&self, input: &'i [u8]) -> LeafResult<'i, Self::Output>;
22}
23
24impl<'i, L: Leaf<'i>> Parser<'i> for L {
25    type Output = L::Output;
26    type Then<T: Parser<'i>> = Then2<Self, T>;
27
28    // Using #[inline] instead of #[inline(always)] is ~7% faster for 2018 day 2 and 2025 day 12.
29    //
30    // With #[inline(always)] the leaf's result is only partially optimized away, and each
31    // successful parse still writes information only used for errors. For example, 2025 day 12 goes
32    // from ~6k to ~20k writes per run.
33    #[inline]
34    fn parse_ctx(
35        &self,
36        input: &'i [u8],
37        state: &mut ParseState<'i>,
38        _: &mut bool,
39        _: bool,
40    ) -> ParserResult<'i, Self::Output> {
41        match self.parse(input) {
42            Ok(v) => Ok(v),
43            Err((err, remaining)) => Err(state.error(err, remaining)),
44        }
45    }
46}
47
48/// Matches the string literal exactly.
49///
50/// Normally used with [`with_prefix`](Parser::with_prefix) or [`with_suffix`](Parser::with_suffix).
51impl<'i> Leaf<'i> for &'static str {
52    type Output = ();
53
54    #[inline(always)]
55    fn parse(&self, input: &'i [u8]) -> LeafResult<'i, Self::Output> {
56        // Requires the string literal to be known at compile time to avoid memcmp
57        match input.strip_prefix(self.as_bytes()) {
58            Some(remaining) => Ok(((), remaining)),
59            None => Err((ParseError::ExpectedLiteral(self), input)),
60        }
61    }
62}
63
64/// Matches the byte exactly.
65///
66/// Normally used with [`with_prefix`](Parser::with_prefix) or [`with_suffix`](Parser::with_suffix).
67impl<'i> Leaf<'i> for u8 {
68    type Output = ();
69
70    #[inline(always)]
71    fn parse(&self, input: &'i [u8]) -> LeafResult<'i, Self::Output> {
72        if input.first() == Some(self) {
73            Ok(((), &input[1..]))
74        } else {
75            Err((ParseError::ExpectedByte(*self), input))
76        }
77    }
78}
79
80/// Allow custom functions/closures to be used as [`Leaf`] parsers.
81impl<'i, F: Fn(&'i [u8]) -> LeafResult<'i, O>, O> Leaf<'i> for F {
82    type Output = O;
83
84    #[inline(always)]
85    fn parse(&self, input: &'i [u8]) -> LeafResult<'i, Self::Output> {
86        self(input)
87    }
88}
89
90/// Coerces the provided function/closure into a [`Leaf`] parser.
91///
92/// This function exists to help with type inference.
93#[inline]
94#[must_use]
95pub const fn from_leaf_fn<'i, F, O>(f: F) -> F
96where
97    F: Fn(&'i [u8]) -> LeafResult<'i, O>,
98    F: Leaf<'i, Output = O>,
99{
100    f
101}
102
103/// Trait for types that have a canonical [`Leaf`] parser.
104pub trait Parseable {
105    type Parser: for<'i> Leaf<'i, Output = Self>;
106    const PARSER: Self::Parser;
107}