1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
//! Defines the type `AndRouteMatcher`

use crate::router::non_match::RouteNonMatch;
use crate::router::route::RouteMatcher;
use crate::state::State;

/// Allows multiple `RouteMatcher` values to be combined when accessing a request.
///
/// # Examples
///
/// ```rust
/// # fn main() {
/// #   use hyper::Method;
/// #   use hyper::header::{HeaderMap, ACCEPT};
/// #   use gotham::state::State;
/// #   use gotham::router::route::matcher::{RouteMatcher, MethodOnlyRouteMatcher, AndRouteMatcher, AcceptHeaderRouteMatcher};
/// #
/// #   State::with_new(|state| {
/// #
///   let methods = vec![Method::GET, Method::HEAD];
///   let supported_media_types = vec![mime::APPLICATION_JSON];
///   let method_matcher = MethodOnlyRouteMatcher::new(methods);
///   let accept_matcher = AcceptHeaderRouteMatcher::new(supported_media_types);
///   let matcher = AndRouteMatcher::new(method_matcher, accept_matcher);
///
///   state.put(Method::GET);
///
///   // Request that matches both requirements
///   let mut headers = HeaderMap::new();
///   headers.insert(ACCEPT, mime::APPLICATION_JSON.to_string().parse().unwrap());
///   state.put(headers);
///   assert!(matcher.is_match(&state).is_ok());
///
///   // Request that fails method requirements
///   state.put(Method::POST);
///   assert!(matcher.is_match(&state).is_err());
///
///   // Request that fails accept header
///   state.put(Method::GET);
///   let mut headers = HeaderMap::new();
///   headers.insert(ACCEPT, mime::TEXT.to_string().parse().unwrap());
///   state.put(headers);
///   assert!(matcher.is_match(&state).is_err());
/// #
/// #   });
/// # }
/// ```
#[derive(Clone)]
pub struct AndRouteMatcher<T, U>
where
    T: RouteMatcher,
    U: RouteMatcher,
{
    t: T,
    u: U,
}

impl<T, U> AndRouteMatcher<T, U>
where
    T: RouteMatcher,
    U: RouteMatcher,
{
    /// Creates a new `AndRouteMatcher`
    pub fn new(t: T, u: U) -> Self {
        AndRouteMatcher { t, u }
    }
}

impl<T, U> RouteMatcher for AndRouteMatcher<T, U>
where
    T: RouteMatcher,
    U: RouteMatcher,
{
    fn is_match(&self, state: &State) -> Result<(), RouteNonMatch> {
        match (self.t.is_match(state), self.u.is_match(state)) {
            (Ok(_), Ok(_)) => Ok(()),
            (Err(e), Ok(_)) => Err(e),
            (Ok(_), Err(e)) => Err(e),
            (Err(e), Err(e1)) => Err(e.intersection(e1)),
        }
    }
}