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
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
mod and;
mod and_then;
pub(crate) mod impls;
mod or;
mod or_else;

pub(crate) use self::and::And;
use self::and_then::AndThen;
pub(crate) use self::or::Or;
use self::or_else::OrElse;
use crate::http::Request;
use crate::routing::PathState;
pub use impls::*;

use crate::http::Method;

pub trait Filter: Send + Sync + 'static {
    fn and<F>(self, other: F) -> And<Self, F>
    where
        Self: Sized,
        F: Filter + Sync + Send,
    {
        And {
            first: self,
            second: other,
        }
    }

    fn or<F>(self, other: F) -> Or<Self, F>
    where
        Self: Sized,
        F: Filter + Sync + Send,
    {
        Or {
            first: self,
            second: other,
        }
    }

    fn and_then<F, U>(self, fun: F) -> AndThen<Self, F>
    where
        Self: Sized,
        F: Fn(&mut Request, &mut PathState) -> bool + Send + Sync + 'static,
        U: Filter + Sync + Send,
    {
        AndThen {
            filter: self,
            callback: fun,
        }
    }

    fn or_else<F, U>(self, fun: F) -> OrElse<Self, F>
    where
        Self: Sized,
        F: Fn(&mut Request, &mut PathState) -> bool + Send + Sync + 'static,
        U: Filter + Sync + Send,
    {
        OrElse {
            filter: self,
            callback: fun,
        }
    }

    fn filter(&self, req: &mut Request, path: &mut PathState) -> bool;
}

// ===== FnFilter =====
#[derive(Copy, Clone)]
#[allow(missing_debug_implementations)]
pub struct FnFilter<F>(pub F);

impl<F> Filter for FnFilter<F>
where
    F: Fn(&mut Request, &mut PathState) -> bool + Send + Sync + 'static,
{
    #[inline]
    fn filter(&self, req: &mut Request, path: &mut PathState) -> bool {
        self.0(req, path)
    }
}

#[inline]
pub fn path(path: impl Into<String>) -> PathFilter {
    PathFilter::new(path)
}
#[inline]
pub fn get() -> MethodFilter {
    MethodFilter(Method::GET)
}
#[inline]
pub fn head() -> MethodFilter {
    MethodFilter(Method::HEAD)
}
#[inline]
pub fn options() -> MethodFilter {
    MethodFilter(Method::OPTIONS)
}
#[inline]
pub fn post() -> MethodFilter {
    MethodFilter(Method::POST)
}
#[inline]
pub fn patch() -> MethodFilter {
    MethodFilter(Method::PATCH)
}
#[inline]
pub fn put() -> MethodFilter {
    MethodFilter(Method::PUT)
}
#[inline]
pub fn delete() -> MethodFilter {
    MethodFilter(Method::DELETE)
}