Macro requirement

Source
macro_rules! requirement {
    (
        $(#[$attr:meta])*
        $vis:vis $req_name:ident => $cond:expr =>! $error_message:literal
    ) => { ... };
    (
        $(#[$attr:meta])*
        $vis:vis $req_name:ident => $cond:expr =>! $create_err:expr => $err_ty:ty
    ) => { ... };
    (
        $(#[$attr:meta])*
        $vis:vis $req_name:ident => $cond:expr =>! $err:ident ($($args:expr),* $(,)?)
    ) => { ... };
    (
        $(#[$attr:meta])*
        $vis:vis $req_name:ident => $cond:expr =>! $err:ident :: $func:ident ($($args:expr),* $(,)?)
    ) => { ... };
    (
        $(#[$attr:meta])*
        $vis:vis $req_name:ident => $cond:expr =>! $err:ident :: $variant:ident
    ) => { ... };
}
Available on crate feature require only.
Expand description

Define a Requirement

Requirements can easily be composed in the requirements! macro, allowing you to create highly maintainable and robust validators with decent performance.

§Example

use swift_check::{
    require::{Requirement, check},
    requirement, requirements,
    range, eq
};

enum Errors {
    Space,
    F,
    Number,
}

requirement!(
    /// The input must include a space
    space => eq(b' ') =>! Errors::Space
);

requirement!(
    /// The input must include `F`
    f => eq(b'f') =>! Errors::F
);

requirement!(
    /// The input must include a number
    number => range!(b'0'..=b'9') =>! Errors::Number
);

// now we can use each requirement together in the requirements! macro, as long as the errors
// of each requirement impl Into<requirements! error type> then you're good to go

let (valid, res_iter) = check(
    b"example input",
    requirements!(Errors, [space, f, number])
).results();

// valid denotes each byte met at least one of the requirements, in this case it should be
// false
assert!(!valid);

for result in res_iter {
    match result {
        Err(Errors::F) => {/* There was not an F in the input */},
        Err(Errors::Number) => {/* There was not a number in the input */},
        Err(Errors::Space) => unreachable!("There was a space in the input"),
        _ => {}
    }
}

Or, if you’re feeling lazy you can use literals as your error, these use the ErrMsg type.

requirement!(pub space => eq(b' ') =>! "There needs to be a space!");

§Syntax

#[attributes]
visibility identifier => condition =>! error

Syntax Limitation: Right now you cannot use errors within a module, so you must import them.