1mod handler;
58
59pub mod di;
60pub mod prelude;
61pub mod send;
62
63pub use handler::*;
64
65#[macro_export]
187macro_rules! case {
188 (:: $($variant:ident)::+) => {
189 $crate::filter(|x| ::core::matches!(x, ::$($variant)::+))
190 };
191 ($($variant:ident)::+) => {
192 $crate::filter(|x| ::core::matches!(x, $($variant)::+))
193 };
194 ($($variant:ident)::+ ($param:ident)) => {
195 $crate::filter_map(|x| match x {
196 $($variant)::+($param) => ::core::option::Option::Some($param),
197 _ => ::core::option::Option::None,
198 })
199 };
200 ($($variant:ident)::+ ($($param:ident),+ $(,)?)) => {
201 $crate::filter_map(|x| match x {
202 $($variant)::+($($param),+) => ::core::option::Option::Some(($($param),+ ,)),
203 _ => ::core::option::Option::None,
204 })
205 };
206 ($($variant:ident)::+ {$param:ident}) => {
207 $crate::filter_map(|x| match x {
208 $($variant)::+{$param} => ::core::option::Option::Some($param),
209 _ => ::core::option::Option::None,
210 })
211 };
212 ($($variant:ident)::+ {$($param:ident),+ $(,)?}) => {
213 $crate::filter_map(|x| match x {
214 $($variant)::+ { $($param),+ } => ::core::option::Option::Some(($($param),+ ,)),
215 _ => ::core::option::Option::None,
216 })
217 };
218 ($($pattern:tt)+) => {
219 $crate::filter_map(|x| {
220 #[allow(unreachable_patterns)]
221 match x {
222 $($pattern)+ => ::core::option::Option::Some(
223 $crate::__case_payload!(@fields scalar [] $($pattern)+)
224 ),
225 _ => ::core::option::Option::None,
226 }
227 })
228 };
229}
230
231#[doc(hidden)]
236#[macro_export]
237macro_rules! __case_payload {
238 (@fields $shape:ident [$($items:expr,)*]) => { ($($items,)*) };
239
240 (@fields $shape:ident [$($items:expr,)*] .. $(, $($tail:tt)*)?) => {
241 $crate::__case_payload!(@fields tuple [$($items,)*] $($($tail)*)?)
242 };
243
244 (@fields $shape:ident $items:tt $key:ident : $($tail:tt)+) => {
245 $crate::__case_payload!(@fields $shape $items $($tail)+)
246 };
247 (@fields $shape:ident $items:tt :: $first:ident $($tail:tt)*) => {
248 $crate::__case_payload!(@path $shape $items [::$first] $($tail)*)
249 };
250 (@fields $shape:ident $items:tt $first:ident $($tail:tt)*) => {
251 $crate::__case_payload!(@path $shape $items [$first] $($tail)*)
252 };
253
254 (@path $shape:ident $items:tt [$($path:tt)+] :: $next:ident $($tail:tt)*) => {
256 $crate::__case_payload!(@path $shape $items [$($path)+ :: $next] $($tail)*)
257 };
258 (@path $shape:ident $items:tt [$($path:tt)+] ::<$($ty:ty),+ $(,)?> $($tail:tt)*) => {
259 $crate::__case_payload!(@path $shape $items [$($path)+ ::<$($ty),+>] $($tail)*)
260 };
261 (@path $shape:ident $items:tt [$($path:tt)+] ($($fields:tt)*) $($tail:tt)*) => {
262 $crate::__case_payload!(@push $shape $items
263 [$crate::__case_payload!(@fields scalar [] $($fields)*)] $($tail)*)
264 };
265 (@path $shape:ident $items:tt [$($path:tt)+] {$($fields:tt)*} $($tail:tt)*) => {
266 $crate::__case_payload!(@push $shape $items
267 [$crate::__case_payload!(@fields scalar [] $($fields)*)] $($tail)*)
268 };
269
270 (@path $shape:ident $items:tt [$($path:tt)+] $(, $($tail:tt)*)?) => {
271 $crate::__case_payload!(@push $shape $items [$($path)+] $(, $($tail)*)?)
272 };
273
274 (@push $shape:ident [$($items:expr,)*] [$value:expr], $($tail:tt)*) => {
275 $crate::__case_payload!(@fields tuple [$($items,)* $value,] $($tail)*)
276 };
277 (@push scalar [] [$value:expr]) => { $value };
278 (@push tuple [$($items:expr,)*] [$value:expr]) => { ($($items,)* $value,) };
279
280 ($($unsupported:tt)*) => {{
281 compile_error!("unsupported pattern in case!; use filter or filter_map for arbitrary Rust patterns")
282 }};
283}
284
285#[cfg(test)]
288macro_rules! cross_test {
289 () => {};
290 ($(#[$($attr:tt)*])* async fn $name:ident() $body:block $($rest:tt)*) => {
291 #[cfg_attr(not(target_arch = "wasm32"), tokio::test)]
292 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
293 $(#[$($attr)*])*
294 async fn $name() $body
295
296 crate::cross_test! { $($rest)* }
297 };
298 ($(#[$($attr:tt)*])* fn $name:ident() $body:block $($rest:tt)*) => {
299 #[cfg_attr(not(target_arch = "wasm32"), test)]
300 #[cfg_attr(target_arch = "wasm32", wasm_bindgen_test::wasm_bindgen_test)]
301 $(#[$($attr)*])*
302 fn $name() $body
303
304 crate::cross_test! { $($rest)* }
305 };
306}
307
308#[cfg(test)]
309pub(crate) use cross_test;
310
311#[cfg(test)]
312mod tests {
313 use std::ops::ControlFlow;
314
315 #[derive(Debug, Copy, Clone, Eq, PartialEq)]
316 enum State {
317 A,
318 B(i32),
319 C(i32, &'static str),
320 D { foo: i32 },
321 E { foo: i32, bar: &'static str },
322 Other,
323 }
324
325 #[derive(Clone)]
326 enum Dialogue {
327 Start,
328 GotNumber(i32),
329 ReceiveAge { full_name: String },
330 ReceiveLocation { full_name: String, age: u8 },
331 }
332
333 #[derive(Clone)]
334 enum Nested {
335 Tuple(State, Option<State>),
336 Named { inner: Named, flag: bool },
337 Maybe(Option<Result<u8, u16>>, i32),
338 Rest((), (), i32),
339 }
340
341 #[derive(Clone)]
342 struct Named {
343 state: State,
344 count: u8,
345 }
346
347 crate::cross_test! {
348 async fn handler_empty_variant() {
349 let input = State::A;
350 let h: crate::Handler<_> = case![State::A].endpoint(|| async move { 123 });
351
352 assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
353 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
354 }
355
356 async fn handler_single_fn_variant() {
357 let input = State::B(42);
358 let h: crate::Handler<_> = case![State::B(x)].endpoint(|x: i32| async move {
359 assert_eq!(x, 42);
360 123
361 });
362
363 assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
364 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
365 }
366
367 async fn handler_single_fn_variant_trailing_comma() {
368 let input = State::B(42);
369 let h: crate::Handler<_> = case![State::B(x,)].endpoint(|(x,): (i32,)| async move {
370 assert_eq!(x, 42);
371 123
372 });
373
374 assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
375 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
376 }
377
378 async fn handler_fn_variant() {
379 let input = State::C(42, "abc");
380 let h: crate::Handler<_> =
381 case![State::C(x, y)].endpoint(|(x, str): (i32, &'static str)| async move {
382 assert_eq!(x, 42);
383 assert_eq!(str, "abc");
384 123
385 });
386
387 assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
388 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
389 }
390
391 async fn handler_single_struct_variant() {
392 let input = State::D { foo: 42 };
393 let h: crate::Handler<_> = case![State::D { foo }].endpoint(|x: i32| async move {
394 assert_eq!(x, 42);
395 123
396 });
397
398 assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
399 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
400 }
401
402 async fn handler_single_struct_variant_trailing_comma() {
403 let input = State::D { foo: 42 };
404 #[rustfmt::skip] let h: crate::Handler<_> = case![State::D { foo, }].endpoint(|(x,): (i32,)| async move {
406 assert_eq!(x, 42);
407 123
408 });
409
410 assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
411 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
412 }
413
414 async fn handler_struct_variant() {
415 let input = State::E { foo: 42, bar: "abc" };
416 let h: crate::Handler<_> =
417 case![State::E { foo, bar }].endpoint(|(x, str): (i32, &'static str)| async move {
418 assert_eq!(x, 42);
419 assert_eq!(str, "abc");
420 123
421 });
422
423 assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(123));
424 assert!(matches!(h.dispatch(crate::deps![State::Other]).await, ControlFlow::Continue(_)));
425 }
426
427 async fn handler_teloxide_dialogue_forms() {
428 let h: crate::Handler<_> = crate::entry()
429 .branch(case![Dialogue::Start].endpoint(|| async { "start".to_owned() }))
430 .branch(
431 case![Dialogue::GotNumber(n)].endpoint(|n: i32| async move { n.to_string() }),
432 )
433 .branch(
434 case![Dialogue::ReceiveAge { full_name }]
435 .endpoint(|name: String| async move { name }),
436 )
437 .branch(
438 case![Dialogue::ReceiveLocation { full_name, age }].endpoint(
439 |(name, age): (String, u8)| async move { format!("{name}: {age}") },
440 ),
441 );
442
443 for (input, expected) in [
444 (Dialogue::Start, "start"),
445 (Dialogue::GotNumber(42), "42"),
446 (Dialogue::ReceiveAge { full_name: "Ada".to_owned() }, "Ada"),
447 (Dialogue::ReceiveLocation { full_name: "Ada".to_owned(), age: 37 }, "Ada: 37"),
448 ] {
449 assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(expected.to_owned()));
450 }
451 }
452
453 async fn handler_nested_variants_preserve_tuple_shape() {
454 let h: crate::Handler<_> = case![Nested::Tuple(State::C(n, label), Some(State::A))]
455 .endpoint(|payload: ((i32, &'static str), State)| async move { payload });
456 let dispatch = |input| h.dispatch(crate::deps![input]);
457
458 assert_eq!(
459 dispatch(Nested::Tuple(State::C(42, "answer"), Some(State::A))).await.break_value(),
460 Some(((42, "answer"), State::A)),
461 );
462 assert!(matches!(
463 dispatch(Nested::Tuple(State::C(42, "answer"), Some(State::Other))).await,
464 ControlFlow::Continue(_),
465 ));
466
467 let h: crate::Handler<_> = case![Nested::Tuple(State::B(n,), ..)]
468 .endpoint(|payload: ((i32,),)| async move { payload });
469 assert_eq!(
470 h.dispatch(crate::deps![Nested::Tuple(State::B(42), None)]).await.break_value(),
471 Some(((42,),)),
472 );
473 }
474
475 async fn handler_nested_named_fields_and_rest() {
476 let h: crate::Handler<_> =
477 case![Nested::Named { inner: Named { state: State::B(n), .. }, flag: enabled }]
478 .endpoint(|payload: ((i32,), bool)| async move { payload });
479 let input = Nested::Named { inner: Named { state: State::B(42), count: 5 }, flag: true };
480 assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some(((42,), true)));
481
482 let h: crate::Handler<_> =
483 case![Named { count: n, .. }].endpoint(|payload: (u8,)| async move { payload });
484 let input = Named { state: State::Other, count: 5 };
485 assert_eq!(h.dispatch(crate::deps![input]).await.break_value(), Some((5,)));
486 }
487
488 async fn handler_typed_unit_variant() {
489 let h: crate::Handler<_> = case![Nested::Maybe(None::<Result<u8, u16>>, n)]
490 .endpoint(|payload: (Option<Result<u8, u16>>, i32)| async move { payload });
491
492 assert_eq!(
493 h.dispatch(crate::deps![Nested::Maybe(None, 42)]).await.break_value(),
494 Some((None, 42)),
495 );
496 assert!(matches!(
497 h.dispatch(crate::deps![Nested::Maybe(Some(Ok(5)), 42)]).await,
498 ControlFlow::Continue(_),
499 ));
500
501 let h: crate::Handler<_> = case![Option::None::<u8>]
502 .endpoint(|payload: Option<u8>| async move { payload });
503 assert_eq!(h.dispatch(crate::deps![None::<u8>]).await.break_value(), Some(None));
504 }
505
506 async fn handler_tuple_rest_and_empty_payload() {
507 let h: crate::Handler<_> =
508 case![Nested::Rest(.., n)].endpoint(|payload: (i32,)| async move { payload });
509 assert_eq!(h.dispatch(crate::deps![Nested::Rest((), (), 3)]).await.break_value(), Some((3,)));
510
511 let h: crate::Handler<_> = case![Nested::Rest(..)].endpoint(|(): ()| async { 42 });
512 assert_eq!(h.dispatch(crate::deps![Nested::Rest((), (), 3)]).await.break_value(), Some(42));
513 }
514 }
515}