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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
//! `silk_router` is a URL routing library inspired by rust's pattern matching
//! syntax.
//!
//! ```rust
//!     route_match!(request.verb, request.url,
//!        GET ("/user") => user_list(),
//!        GET ("/user/", id = num::<u32>) => user_details(id),
//!        POST ("/user") => create_user(),
//!        PUT ("/user/", id = num::<u32>) => update_user(id),
//!        _ => error(404, "Not Found")
//!    );
//! ```
//!
//! It is agnostic to the HTTP library you are using. HTTP verbs are checked for
//! strict equality. The URL must support a `.chars()` method returning a
//! `std::str::Chars`. The verbs can be omitted, especially useful for nesting
//! match statements:
//!
//! ```rust
//!     route_match!(request.verb, request.url,
//!         GET ("/user", id = num::<u32>, sub_url = rest) => {
//!             let user = load_user(id);
//!             route_match!(sub_url
//!                 ("/settings") => user_settings(user),
//!                 ("/token") => user_token(user),
//!                 _ => user_info(user)
//!             )
//!         }
//!     );
//! ```
//!
//! Inside the match expressions, strings are checkd for exact equality.
//! Expression matches: `ident = expr` call the function returned by `expr`
//! which must be a `FnMut(&mut Peekable<Chars>) -> Option<T>`. If the branch
//! matches, the identifier will be a block-scoped variable with type `T`.
//! 
//! Matches are exhaustive: the entire URL must have been consumed. The
//! `parsers::rest` parser can be used to consume the end of the string.

extern crate num;

use std::iter::Peekable;
use std::str::Chars;

pub mod parsers;

pub fn matches(iter: &mut Peekable<Chars>, text: &'static str) -> bool {
    for ch in text.chars() {
        let other: char = match iter.peek() {
            Some(&ch) => ch,
            None => return false,
        };
        if other != ch {
            return false;
        }
        iter.next();
    }
    return true;
}

/// Pattern-match-style URL routing
#[macro_export]
macro_rules! route_match {
    ($request_verb:expr, $url:expr, $( $verb:ident ( $( $match_url:tt )+ ) => $body:expr ),+, _ => $default:expr) => (
        {
            #[allow(unused_imports)]
            use matches;

            let mut url_iter = $url.chars().peekable();
            branch!($request_verb, url_iter, $default, $( $body, $verb, ( $( $match_url )+ ) ),+ )
        }
    );
    ($url:expr, $( ( $( $match_url:tt )+ ) => $body:expr ),+, _ => $default:expr) => (
        {
            #[allow(unused_imports)]
            use matches;

            let mut url_iter = $url.chars().peekable();
            branch!(url_iter, $default, $( $body, ( $( $match_url )+ ) ),+ )
        }
    )
}

#[macro_export]
macro_rules! branch {
    ($request_verb:expr, $iter:ident, $default:expr, $body:expr, $verb:expr, ( $( $url:tt )+ ), $( $bodies:expr, $verbs:ident, ( $( $urlses:tt )+ ) ),+) => {
        {
            let mut next_iter = $iter.clone();
            if let Some(result) = match_verb!($request_verb, $verb, next_iter, $body, $($url)+) {
                result
            } else {
                branch!($request_verb, $iter, $default, $( $bodies, $verbs, ( $( $urlses )+ ) ),+ )
            }
        }
    };
    ($request_verb:expr, $iter:ident, $default:expr, $body:expr, $verb:expr, ( $( $url:tt )+ ) ) => {
        if let Some(result) = match_verb!($request_verb, $verb, $iter, $body, $($url)+) {
            result
        } else {
            $default
        }
    };
    ($iter:ident, $default:expr, $body:expr, ( $( $url:tt )+ ), $( $bodies:expr, ( $( $urlses:tt )+ ) ),+) => {
        {
            let mut next_iter = $iter.clone();
            if let Some(result) = predicates!(next_iter, $body, $($url)+) {
                result
            } else {
                branch!($iter, $default, $( $bodies, ( $( $urlses )+ ) ),+ )
            }
        }
    };
    ($iter:ident, $default:expr, $body:expr, ( $( $url:tt )+ ) ) => {
        if let Some(result) = predicates!($iter, $body, $($url)+) {
            result
        } else {
            $default
        }
    };
}

#[macro_export]
macro_rules! match_verb {
    ($request_verb:expr, $verb:expr, $iter:ident, $body:expr, $( $url:tt )+) => (
        if $request_verb == $verb {
            predicates!($iter, $body, $($url)+)
        } else { None }
    )
}

#[macro_export]
macro_rules! predicates {
    ($iter:ident, $body:expr, $first:tt, $( $rest:tt )+) => (
        if matches(&mut $iter, $first) {
            predicates!($iter, $body, $($rest)+)
        } else { None }
    );
    ($iter:ident, $body:expr, $first:tt) => (
        if matches(&mut $iter, $first) {
            if $iter.peek() == None {
                Some($body)
            } else { None }
        } else { None }
    );
    ($iter:ident, $body:expr, $first:ident = $parser:expr, $( $rest:tt )+) => (
        if let Some($first) = $parser(&mut $iter) {
            predicates!($iter, $body, $($rest)+)
        } else { None }
    );
    ($iter:ident, $body:expr, $first:ident = $parser:expr) => (
        if let Some($first) = $parser(&mut $iter) {
            if $iter.peek() == None {
                Some($body)
            } else { None }
        } else { None }
    );
}

#[cfg(test)]
mod tests {
    pub const GET: &'static str = "GET";
    pub const POST: &'static str = "POST";

    use super::parsers::{num, rest, until};

    #[test]
    fn match_success() {
        assert!(route_match!("/foo/bar",
            ("/foo/bar") => true,
            _ => false
        ));
    }

    #[test]
    fn match_failure() {
        assert!(route_match!("/foo/fail",
            ("/foo/bar") => false,
            _ => true
        ));
    }

    #[test]
    fn parser_success() {
        assert!(route_match!("/foo/5",
            ("/foo/", id = num::<u8>) => id == 5,
            _ => false
        ));
    }

    #[test]
    fn parser_failure() {
        assert!(route_match!("/foo/0xDEADBEEF",
            ("/foo/", _id = num::<u32>) => false,
            _ => true
        ));
    }

    #[test]
    fn first_match() {
        assert!(route_match!("/foo",
            ("/foo") => true,
            ("/foo") => false,
            _ => false
        ));
    }

    #[test]
    fn multiarm_success() {
        assert!(route_match!("/foo/5",
            ("/foo/bar") => false,
            ("/foo/", _id = num::<u8>) => true,
            _ => false
        ));
    }

    #[test]
    fn match_verb() {
        assert!(route_match!(POST, "/foo/bar",
            GET ("/foo/bar") => false,
            POST ("/foo/bar") => true,
            _ => false
        ));
    }

    #[test]
    fn match_fun() {
        assert!(route_match!(GET, "/foo/groucho:swordfish",
            GET ("/foo/", username = until(':'), password = rest) => 
                username == "groucho" && password == "swordfish",
            _ => false
        ));
    }

    #[test]
    fn match_full() {
        assert!(route_match!("/abcde",
            ("/abcd") => false,
            ("/abcde") => true,
            _ => false
        ));
    }
}