cgp_dispatch/providers/
match_with_handlers.rs

1use core::marker::PhantomData;
2
3use cgp_core::prelude::*;
4use cgp_handler::{
5    Computer, ComputerComponent, Handler, HandlerComponent, TryComputer, TryComputerComponent,
6};
7
8use crate::DispatchMatchers;
9
10pub struct MatchWithHandlers<Handlers>(pub PhantomData<Handlers>);
11
12#[cgp_provider]
13impl<Context, Code, Input, Output, Remainder, Handlers> Computer<Context, Code, Input>
14    for MatchWithHandlers<Handlers>
15where
16    Input: HasExtractor,
17    DispatchMatchers<Handlers>:
18        Computer<Context, Code, Input::Extractor, Output = Result<Output, Remainder>>,
19    Remainder: FinalizeExtract,
20{
21    type Output = Output;
22
23    fn compute(_context: &Context, code: PhantomData<Code>, input: Input) -> Output {
24        let res = DispatchMatchers::compute(_context, code, input.to_extractor());
25
26        match res {
27            Ok(output) => output,
28            Err(remainder) => remainder.finalize_extract(),
29        }
30    }
31}
32
33#[cgp_provider]
34impl<Context, Code, Input, Output, Remainder, Handlers> TryComputer<Context, Code, Input>
35    for MatchWithHandlers<Handlers>
36where
37    Context: HasErrorType,
38    Input: HasExtractor,
39    DispatchMatchers<Handlers>:
40        TryComputer<Context, Code, Input::Extractor, Output = Result<Output, Remainder>>,
41    Remainder: FinalizeExtract,
42{
43    type Output = Output;
44
45    fn try_compute(
46        _context: &Context,
47        code: PhantomData<Code>,
48        input: Input,
49    ) -> Result<Output, Context::Error> {
50        let res = DispatchMatchers::try_compute(_context, code, input.to_extractor())?;
51
52        match res {
53            Ok(output) => Ok(output),
54            Err(remainder) => remainder.finalize_extract(),
55        }
56    }
57}
58
59#[cgp_provider]
60impl<Context, Code: Send, Input: Send, Output: Send, Remainder: Send, Handlers>
61    Handler<Context, Code, Input> for MatchWithHandlers<Handlers>
62where
63    Context: HasAsyncErrorType,
64    Input: HasExtractor<Extractor: Send>,
65    DispatchMatchers<Handlers>:
66        Handler<Context, Code, Input::Extractor, Output = Result<Output, Remainder>>,
67    Remainder: FinalizeExtract,
68{
69    type Output = Output;
70
71    async fn handle(
72        _context: &Context,
73        code: PhantomData<Code>,
74        input: Input,
75    ) -> Result<Output, Context::Error> {
76        let res = DispatchMatchers::handle(_context, code, input.to_extractor()).await?;
77
78        match res {
79            Ok(output) => Ok(output),
80            Err(remainder) => Err(remainder.finalize_extract()),
81        }
82    }
83}