Skip to main content

case

Macro case 

Source
macro_rules! case {
    (:: $($variant:ident)::+) => { ... };
    ($($variant:ident)::+) => { ... };
    ($($variant:ident)::+ ($param:ident)) => { ... };
    ($($variant:ident)::+ ($($param:ident),+ $(,)?)) => { ... };
    ($($variant:ident)::+ {$param:ident}) => { ... };
    ($($variant:ident)::+ {$($param:ident),+ $(,)?}) => { ... };
    ($($pattern:tt)+) => { ... };
}
Expand description

Filters by a pattern, passing its payload forwards.

This macro expands to a crate::Handler that acts on your enumeration type: if the enumeration is of a certain variant, the execution continues; otherwise, dptree will try the next branch. This is very useful for dialogue FSM transitions and incoming command filtering; for a real-world example, please see teloxide’s examples/purchase.rs.

Variants can take the following forms:

  • Enum::MyVariant for empty variants;
  • Enum::MyVariant(param1, ..., paramN) for tuple-like variants;
  • Enum::MyVariant { param1, ..., paramN } for struct-like variants.

In the first case, this macro results in a simple crate::filter; in the second and third cases, this macro results in crate::filter_map that passes the payload of MyVariant to the next handler if the match occurs. (This next handler can be an endpoint or a more complex one.) The payload format depends on the form of MyVariant:

  • For Enum::MyVariant(param) and Enum::MyVariant { param }, the payload is param.
  • For Enum::MyVariant(param,) and Enum::MyVariant { param, }, the payload is (param,).
  • For Enum::MyVariant(param1, ..., paramN) and Enum::MyVariant { param1, ..., paramN }, the payload is (param1, ..., paramN) (where N>1).

Paths may start with ::, and type arguments may use turbofish syntax on the enum or the variant. A typed unit variant injects the matching value; an untyped standalone unit variant only filters.

use dptree::{case, Handler};

let _: Handler<u8> = case![Some::<u8>(v)].endpoint(|v: u8| async move { v });
let _: Handler<Option<u8>> = case![::core::option::Option::<u8>::None]
    .endpoint(|v: Option<u8>| async move { v });
let _: Handler<()> = case![::core::cmp::Ordering::Equal].endpoint(|| async {});

Tuple-like and struct-like patterns may also destructure structs and nested variants. At each level, payloads are collected in the order written:

  • An identifier contributes its bound value. In a named field key: pattern, the payload comes from pattern, not key.
  • A nested unit variant (such as Other::Ready) or typed unit variant (such as None::<T>) contributes that value. A standalone path without type arguments remains a filter that injects nothing.
  • A nested tuple-like or struct-like pattern contributes its own payload as one element; its tuple, if any, is not flattened into the outer tuple.
  • .. contributes no element. A comma still makes the payload a tuple: Variant(x, ..) contributes (x,), and Variant(..) contributes ().

For other Rust patterns, such as or-patterns or guards, use crate::filter or crate::filter_map directly.

§Dependency requirements

  • The type matched by the pattern.

§Examples

use dptree::prelude::*;

#[derive(Clone)]
enum Command {
    Meow,
    Add(i32, i32),
    Repeat { times: Option<usize> },
}

let h: Handler<_> = dptree::entry()
    .branch(dptree::case![Command::Meow].endpoint(|| async move { format!("Meow!") }))
    .branch(
        dptree::case![Command::Add(x, y)]
            .endpoint(|(x, y): (i32, i32)| async move { format!("{}", x + y) }),
    )
    .branch(
        dptree::case![Command::Repeat { times: Some(n) }]
            .endpoint(|n: usize| async move { "Meow!".repeat(n) }),
    );

assert_eq!(
    h.dispatch(dptree::deps![Command::Meow]).await.break_value(),
    Some("Meow!".to_owned())
);
assert_eq!(
    h.dispatch(dptree::deps![Command::Add(1, 2)]).await.break_value(),
    Some("3".to_owned())
);
assert_eq!(
    h.dispatch(dptree::deps![Command::Repeat { times: Some(2) }]).await.break_value(),
    Some("Meow!Meow!".to_owned())
);

The macro works even when matches!, Some, and None are shadowed:

use dptree::{case, deps, Handler};
#[allow(unused_macros)]
macro_rules! matches { ($($tt:tt)*) => { compile_error!("local matches!") }; }
#[derive(Clone)]
enum Choice { Some(u8), None }
use Choice::{Some, None};

let empty: Handler<_> = case![Choice::None].endpoint(|| async { 0 });
let payload: Handler<_> = case![Choice::Some(n)].endpoint(|n: u8| async move { n });
assert_eq!(empty.dispatch(deps![None]).await.break_value(), ::core::option::Option::Some(0));
assert_eq!(payload.dispatch(deps![Some(42)]).await.break_value(), ::core::option::Option::Some(42));
assert!(payload.dispatch(deps![None]).await.is_continue());