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