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
use crate::{Constraint, Path, Request, RouteRef, Router};
use std::sync::Arc;

#[derive(Default)]
pub struct Scope<'a> {
    pub(crate) path: Path<'a>,
    pub(crate) pipes: Vec<&'a str>,
    pub(crate) router: Router<'a>,
    pub(crate) constraint: Option<Arc<Constraint>>,
}

impl<'a> Scope<'a> {
    pub fn empty() -> Self {
        Self::default()
    }

    pub fn new<P>(path: P) -> Self
    where
        P: Into<Path<'a>>,
    {
        Self {
            path: path.into(),
            ..Default::default()
        }
    }

    pub fn through(mut self, pipes: &[&'a str]) -> Self {
        self.pipes = pipes.to_vec();
        self
    }

    pub fn to<R>(mut self, f: R) -> Self
    where
        R: Fn(&mut Router),
    {
        let mut router = Router::in_scope();
        f(&mut router);

        self.router = router;
        self
    }

    pub fn constraint<C>(mut self, constraint: C) -> Self
    where
        C: Fn(&Request) -> bool + Send + Sync + 'static,
    {
        self.constraint = Some(Arc::new(Box::new(constraint)));
        self
    }

    pub(crate) fn regex(&self) -> (String, Vec<(String, String)>) {
        (self.path.regex(), self.router.regex())
    }

    pub(crate) fn refs(&self) -> (Option<Arc<Constraint>>, Vec<RouteRef>, Vec<&str>) {
        (
            self.constraint.clone(),
            self.router.refs(),
            self.pipes.clone(),
        )
    }
}