tokit/
require.rs

1/// A trait for tokens that can be compared for equivalence against a reference.
2/// A helper trait for ergonomically requiring specific token shapes.
3///
4/// `Require` is intended for tiny wrappers (e.g., `Dot`, `Comma`, `ParenOpen`) that want a
5/// `try_into`-style API without consuming the token stream. Implementors typically return
6/// `Ok(output)` when the token matches the desired pattern, or `Err(Self::Err)` to hand the
7/// original token (or a custom error type) back to the caller so other logic can handle it.
8///
9/// ## Example
10///
11/// ```rust
12/// use tokit::{Require, IdentifierToken};
13///
14/// #[derive(Debug, Clone)]
15/// pub enum Punct {
16///     Dot,
17///     Comma,
18///     Other(String),
19/// }
20///
21/// #[derive(Debug, Clone)]
22/// pub struct Dot(pub Punct);
23///
24/// impl Require<Dot> for Punct {
25///     type Err = Self;
26///
27///     fn require(self) -> Result<Dot, Self::Err> {
28///         match &self {
29///             Punct::Dot => Ok(Dot(Self::Dot)),
30///             _ => Err(self),
31///         }
32///     }
33/// }
34/// ```
35pub trait Require<O> {
36  /// The error type returned when a requirement is not met.
37  type Err;
38
39  /// Attempts to extract the desired output from the token, returning `Err(Self::Err)` if not possible.
40  fn require(self) -> Result<O, Self::Err>
41  where
42    Self: Sized;
43}