Macro request

Source
macro_rules! request {
    ($($token:tt)*) => { ... };
}
Expand description

Requests one of a set of possible values, refs, or tags from a provider.

If a value is found, its branch will be evaluated and none of the subsequent values will be requested from the provider.

§Usage

use dynamic_provider::{define_tag, request, Lt, ProvideRef};

define_tag! {
    /// A tag that requires an arg
    tag TagWithArg: for<'x, 'y, 'arg> &'arg i32 => i32;

    /// A tag that does not require an arg
    tag TagWithoutArg: for<'x, 'y, 'arg> i32;
}

fn get_number<'x, 'y>(provider: &'x mut dyn for<'arg> ProvideRef<Lt!['y, 'arg]>) -> i32 {
    let arg_value = 1;

    request! {
        from provider;

        // This line is optional unless the lifetime list cannot be inferred:
        in 'x, 'y, '_;

        // Request by tag with arg:
        tag x: TagWithArg where arg <- &arg_value => x,

        // Request by tag without arg:
        tag x: TagWithoutArg => x,

        // Request a 'static type:
        x: i32 => x,

        // Request a unique reference:
        ref mut x: i32 => *x,

        // Request a shared reference with an inferred type:
        ref x => *x,

        // When none of the above requests were fulfilled:
        else => 0,
    }
}

§Notes

The else branch may also include a pattern that will be bound to the original provider like so:

else provider => todo!()

If there is no else branch at all, this macro evaluates to a Result where Ok contains the output of one of the above branches, and Err contains the original provider.