|
| 1 | +use std::collections::HashMap; |
| 2 | +use std::sync::{Arc, LazyLock}; |
| 3 | + |
| 4 | +use crate::common::Config; |
| 5 | +use crate::directives::{DirectiveLine, TestProps}; |
| 6 | + |
| 7 | +pub(crate) static DIRECTIVE_HANDLERS_MAP: LazyLock<HashMap<&str, Handler>> = |
| 8 | + LazyLock::new(make_directive_handlers_map); |
| 9 | + |
| 10 | +#[derive(Clone)] |
| 11 | +pub(crate) struct Handler { |
| 12 | + handler_fn: Arc<dyn Fn(HandlerArgs<'_>) + Send + Sync>, |
| 13 | +} |
| 14 | + |
| 15 | +impl Handler { |
| 16 | + pub(crate) fn handle(&self, config: &Config, line: &DirectiveLine<'_>, props: &mut TestProps) { |
| 17 | + (self.handler_fn)(HandlerArgs { config, line, props }) |
| 18 | + } |
| 19 | +} |
| 20 | + |
| 21 | +struct HandlerArgs<'a> { |
| 22 | + config: &'a Config, |
| 23 | + line: &'a DirectiveLine<'a>, |
| 24 | + props: &'a mut TestProps, |
| 25 | +} |
| 26 | + |
| 27 | +/// Intermediate data structure, used for defining a list of handlers. |
| 28 | +struct NamedHandler { |
| 29 | + names: Vec<&'static str>, |
| 30 | + handler: Handler, |
| 31 | +} |
| 32 | + |
| 33 | +/// Helper function to create a simple handler, so that changes can be made |
| 34 | +/// to the handler struct without disturbing existing handler declarations. |
| 35 | +fn handler( |
| 36 | + name: &'static str, |
| 37 | + handler_fn: impl Fn(&Config, &DirectiveLine<'_>, &mut TestProps) + Send + Sync + 'static, |
| 38 | +) -> NamedHandler { |
| 39 | + multi_handler(&[name], handler_fn) |
| 40 | +} |
| 41 | + |
| 42 | +/// Associates the same handler function with multiple directive names. |
| 43 | +fn multi_handler( |
| 44 | + names: &[&'static str], |
| 45 | + handler_fn: impl Fn(&Config, &DirectiveLine<'_>, &mut TestProps) + Send + Sync + 'static, |
| 46 | +) -> NamedHandler { |
| 47 | + NamedHandler { |
| 48 | + names: names.to_owned(), |
| 49 | + handler: Handler { |
| 50 | + handler_fn: Arc::new(move |args| handler_fn(args.config, args.line, args.props)), |
| 51 | + }, |
| 52 | + } |
| 53 | +} |
| 54 | + |
| 55 | +fn make_directive_handlers_map() -> HashMap<&'static str, Handler> { |
| 56 | + use crate::directives::directives::*; |
| 57 | + |
| 58 | + let handlers: Vec<NamedHandler> = vec![ |
| 59 | + handler(ERROR_PATTERN, |config, ln, props| { |
| 60 | + config.push_name_value_directive(ln, ERROR_PATTERN, &mut props.error_patterns, |r| r); |
| 61 | + }), |
| 62 | + handler(REGEX_ERROR_PATTERN, |config, ln, props| { |
| 63 | + config.push_name_value_directive( |
| 64 | + ln, |
| 65 | + REGEX_ERROR_PATTERN, |
| 66 | + &mut props.regex_error_patterns, |
| 67 | + |r| r, |
| 68 | + ); |
| 69 | + }), |
| 70 | + ]; |
| 71 | + |
| 72 | + handlers |
| 73 | + .into_iter() |
| 74 | + .flat_map(|NamedHandler { names, handler }| { |
| 75 | + names.into_iter().map(move |name| (name, Handler::clone(&handler))) |
| 76 | + }) |
| 77 | + .collect() |
| 78 | +} |
0 commit comments