Macro strategy

Source
macro_rules! strategy {
    (
        $(#[$attr:meta])*
        $vis:vis struct $name:ident
            $( ($($tuple_fields:tt)*) = $tuple_unit:expr; )?
            $( {$($struct_fields:tt)*} = $struct_unit:expr; )?
            $(;)?

        type Result<$t:ident, $e:ident> = $output:ty;

        Ok($ok_val:pat) => $ok:expr;
        Err($err_val:pat) => $err:expr;

        fn map($map_val:pat, $map_f:pat) => $map:expr;
        fn map_err($map_err_val:pat, $map_err_f:pat) => $map_err:expr;
        fn and_then($and_then_val:pat, $and_then_f:pat) => $and_then:expr;
    ) => { ... };
}
Expand description

Create a custom Strategy.

ยงExamples


strategy! {
    // The name and visibility of the strategy, plus whatever docs/attrs you
    // want to put on it.
    //
    // If it's not a unit struct, it has to have a `const` default value.
    #[derive(Debug, Copy)]
    pub struct Log(Logger) = Log(Logger::new());

    // The result of applying the transformation. In this case, we're just
    // logging, so we don't want to remove the errors.
    type Result<T, E> = Result<T, E>;

    // How to transform an `Ok`/`Err` value to an ok/error result of our
    // `Result` type. In our case, we don't want to change anything, just
    // log any errors.
    Ok(val) => Ok(val);
    Err(err) => {
        self.0.log("encountered an error", &err);
        Err(err)
    };

    // How to apply various transformations to our result type. Since this
    // is just a plain `Result`, we can delegate to its implementations.
    fn map(value, f) => value.map(f);
    fn map_err(value, f) => value.map_err(f);
    fn and_then(value, f) => value.and_then(f);
}