pub struct Dispatcher<'a, Item, M> { /* private fields */ }Expand description
A dispatcher backed by a borrowed table and a matching strategy.
The table is scanned from beginning to end. The first matching item is selected, so table order defines dispatch priority.
Implementations§
Source§impl<'a, Item, M> Dispatcher<'a, Item, M>
impl<'a, Item, M> Dispatcher<'a, Item, M>
Sourcepub const fn new(table: &'a [Item], matcher: M) -> Self
pub const fn new(table: &'a [Item], matcher: M) -> Self
Creates a dispatcher backed by table.
Examples found in repository?
72fn main() {
73 let routes = [
74 Route {
75 command: Command::Read,
76 handler: read,
77 },
78 Route {
79 command: Command::Write,
80 handler: double,
81 },
82 ];
83 let dispatcher = Dispatcher::new(&routes, CommandMatcher);
84 let mut context = AppContext::default();
85 let request = Request {
86 command: Command::Write,
87 value: 21,
88 };
89
90 let response = dispatcher.dispatch(&request, &mut context).unwrap();
91
92 assert_eq!(response, Response { value: 42 });
93 assert_eq!(context.execution_count, 1);
94 println!(
95 "value={}, execution_count={}",
96 response.value, context.execution_count
97 );
98}Sourcepub fn select<Input>(&self, input: &Input) -> Option<&Item>
pub fn select<Input>(&self, input: &Input) -> Option<&Item>
Returns the first item accepted by the matcher.
This method performs selection only and does not invoke the item’s
Handler.
Sourcepub fn dispatch(
&self,
input: &Item::Input,
context: &mut Item::Context,
) -> Result<Item::Output, DispatchError<Item::Error>>
pub fn dispatch( &self, input: &Item::Input, context: &mut Item::Context, ) -> Result<Item::Output, DispatchError<Item::Error>>
Selects and executes the first item accepted by the matcher.
input is immutable for the entire operation. Runtime state and other
mutable resources should be carried by context instead.
Examples found in repository?
72fn main() {
73 let routes = [
74 Route {
75 command: Command::Read,
76 handler: read,
77 },
78 Route {
79 command: Command::Write,
80 handler: double,
81 },
82 ];
83 let dispatcher = Dispatcher::new(&routes, CommandMatcher);
84 let mut context = AppContext::default();
85 let request = Request {
86 command: Command::Write,
87 value: 21,
88 };
89
90 let response = dispatcher.dispatch(&request, &mut context).unwrap();
91
92 assert_eq!(response, Response { value: 42 });
93 assert_eq!(context.execution_count, 1);
94 println!(
95 "value={}, execution_count={}",
96 response.value, context.execution_count
97 );
98}Sourcepub fn matcher_mut(&mut self) -> &mut M
pub fn matcher_mut(&mut self) -> &mut M
Returns a mutable reference to the matcher.
This can be used to reconfigure matching between dispatch calls. The matcher itself remains immutable while selection is in progress.
Sourcepub fn into_parts(self) -> (&'a [Item], M)
pub fn into_parts(self) -> (&'a [Item], M)
Splits the dispatcher into its table and matcher.