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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
/*
 *   Copyright 2016 Jean Piere Dudey
 *
 *   Licensed under the Apache License, Version 2.0 (the "License");
 *   you may not use this file except in compliance with the License.
 *   You may obtain a copy of the License at
 *
 *       http://www.apache.org/licenses/LICENSE-2.0
 *
 *   Unless required by applicable law or agreed to in writing, software
 *   distributed under the License is distributed on an "AS IS" BASIS,
 *   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *   See the License for the specific language governing permissions and
 *   limitations under the License.
*/

#![deny(missing_debug_implementations, missing_copy_implementations,
        trivial_casts, trivial_numeric_casts,
        unsafe_code,
        unused_import_braces, unused_qualifications)]

#![cfg_attr(feature="dev", feature(plugin))]
#![cfg_attr(feature="dev", plugin(clippy))]

/// This crate provides the type Uri used to parse a given uri string.
///
/// # Usage
///
/// This crate is on crates.io and can be used by adding uri to your dependencies in your
/// project's Cargo.toml.
///
/// ```toml
/// [dependencies]
/// uri = "0.1"
/// ```
///
/// and this to your crate root:
/// ```
/// extern crate uri;
/// ```

#[macro_use]
extern crate lazy_static;
extern crate regex;
use regex::*;

/// Uri represents the data contained in an uri string.
#[derive(Default, Debug)]
pub struct Uri {
    /// Represents the scheme of an uri.
    ///
    /// # Examples
    ///
    /// ```
    /// use uri::Uri;
    ///
    /// let uri = Uri::new("https://doc.rust-lang.org/book/README.html").unwrap();
    /// assert_eq!(uri.scheme, "https");
    /// ```
    pub scheme: String,

    /// Represents the username (authority) of an uri.
    ///
    /// # Examples
    ///
    /// ```
    /// use uri::Uri;
    ///
    /// let uri = Uri::new("https://user:pass@doc.rust-lang.org/book/README.html").unwrap();
    /// assert_eq!(uri.username.unwrap(), "user");
    /// ```
    pub username: Option<String>,

    /// Represents the password (authority) of an uri.
    ///
    /// # Examples
    ///
    /// ```
    /// use uri::Uri;
    ///
    /// let uri = Uri::new("https://user:pass@doc.rust-lang.org/book/README.html").unwrap();
    /// assert_eq!(uri.password.unwrap(), "pass");
    /// ```
    pub password: Option<String>,

    /// Represents the host of an uri.
    ///
    /// # Examples
    ///
    /// ```
    /// use uri::Uri;
    ///
    /// let uri = Uri::new("https://doc.rust-lang.org/book/README.html").unwrap();
    /// assert_eq!(uri.host.unwrap(), "doc.rust-lang.org");
    /// ```
    pub host: Option<String>,

    /// Represents the port of an uri.
    ///
    /// # Examples
    ///
    /// ```
    /// use uri::Uri;
    ///
    /// let uri = Uri::new("https://doc.rust-lang.org:1234").unwrap();
    /// assert_eq!(uri.host.unwrap(), "doc.rust-lang.org");
    /// assert_eq!(uri.port, Some(1234));
    /// ```
    pub port: Option<u16>,

    /// Represents the path of an uri.
    ///
    /// # Examples
    ///
    /// ```
    /// use uri::Uri;
    ///
    /// let uri = Uri::new("https:/doc.rust-lang.org/book/README.html").unwrap();
    /// assert_eq!(uri.path.unwrap(), "/book/README.html");
    /// ```
    pub path: Option<String>,

    /// Represents the query of an uri.
    ///
    /// # Examples
    ///
    /// ```
    /// use uri::Uri;
    ///
    /// let uri = Uri::new("https:/doc.rust-lang.org/?query=value&q=v").unwrap();
    /// assert_eq!(uri.query.unwrap(), "query=value&q=v");
    /// ```
    pub query: Option<String>,

    /// Represents the fragment of an uri.
    ///
    /// # Examples
    ///
    /// ```
    /// use uri::Uri;
    ///
    /// let uri = Uri::new("https:/doc.rust-lang.org/#fragment").unwrap();
    /// assert_eq!(uri.fragment.unwrap(), "fragment");
    /// ```
    pub fragment: Option<String>,
}

macro_rules! map_to_string {
    ( $x:expr ) => ({
        if let Some(contents) = $x.map(String::from) {
            if contents == "" {
                None
            } else {
                Some(contents)
            }
        } else {
            None
        }
    });
}

/// Parses a string into a u16.

fn map_to_u16(value: &str) -> Option<u16> {
    match String::from(value).parse::<u16>() {
        Ok(parsed_value) => Some(parsed_value),
        _ => None
    }
}

lazy_static! {
    static ref URI_REGEX: Regex = Regex::new(URI_PATTERN).unwrap();
}

static URI_PATTERN: &'static str = "^(?P<scheme>[a-zA-Z][a-zA-Z0-9+.-]*):\
                                    /{0,3}\
                                    (?P<username>.*?)?\
                                    (:(?P<password>.*?))?@?\
                                    (?P<host>[0-9\\.A-Za-z-?]+)\
                                    (?::(?P<port>\\d+))?\
                                    (:?(?P<path>/[^?#]*))?\
                                    (?:\\?(?P<query>[^#]*))?\
                                    (?:#(?P<fragment>.*))?$";

/// Checks if a given string is an URI.
///
/// # Examples
///
/// ```
/// use uri::is_uri;
///
/// let result = is_uri("https://doc.rust-lang.org/book/README.html");
/// assert_eq!(result, true);
/// ```
pub fn is_uri(uristr: &str) -> bool {
    URI_REGEX.is_match(uristr)
}

impl Uri {
    /// Creates Uri object from a given uri string.
    ///
    /// # Failures
    ///
    /// If the string isn't a valid uri the function will return `None`.
    ///
    /// # Examples
    ///
    /// ```
    /// use uri::Uri;
    ///
    /// let uri = match Uri::new("https://doc.rust-lang.org/book/README.html") {
    ///     Some(value) => value,
    ///     None => panic!("Oh no!")
    /// };
    /// ```
    pub fn new(uristr: &str) -> Option<Uri> {
        if !is_uri(uristr) {
            return None;
        }

        let mut uri = Uri {
            scheme: String::new(),
            username: None,
            password: None,
            host: None,
            port: None,
            path: None,
            query: None,
            fragment: None,
        };

        match URI_REGEX.captures(uristr) {
            Some(caps) => {
                match caps.name("scheme") {
                    Some(scheme) => uri.scheme = String::from(scheme),
                    None => {println!("here"); return None;}
                }

                uri.username = map_to_string!(caps.name("username"));
                uri.password = map_to_string!(caps.name("password"));
                uri.host = map_to_string!(caps.name("host"));
                uri.port = caps.name("port").and_then(map_to_u16);
                uri.path = map_to_string!(caps.name("path"));
                uri.query = map_to_string!(caps.name("query"));
                uri.fragment = map_to_string!(caps.name("fragment"));
            },
            None => return None
        };

        Some(uri)
    }
}

#[cfg(test)]
mod test {

    static URI_GOOD_STRING: &'static str = "https://www.unknown.host/false/path.html?query=value";
    static URI_BAD_STRING: &'static str = "lazy string";

    #[test]
    fn is_uri() {
        let res1 = ::is_uri(URI_GOOD_STRING);
        assert_eq!(res1, true);

        let res2 = ::is_uri(URI_BAD_STRING);
        assert_eq!(res2, false);
    }

    #[test]
    fn blank_username_should_parse_as_none() {
        let uri_with_blank_username = "http://some.host/";
        if let Some(parsed_uri) = ::Uri::new(uri_with_blank_username) {
            assert_eq!(parsed_uri.username, None);
        } else {
            panic!("Cannot create a URI from a valid string");
        }
    }

    #[test]
    fn bad_port_shouldnt_panic() {
        let bad_port_uri = "http://some.host:99999";
        if let Some(parsed_uri) = ::Uri::new(bad_port_uri) {
            if let Some(weird_port) = parsed_uri.port {
                panic!("Incorrectly parsed port as {}", weird_port);
            }
        } else {
            panic!("Cannot create URI");
        }
    }

    #[test]
    fn uri_new() {
        match ::Uri::new(URI_GOOD_STRING) {
            Some(uri) => {
                assert_eq!(uri.scheme, "https");
                assert_eq!(uri.host.unwrap(), "www.unknown.host");
                assert_eq!(uri.path.unwrap(), "/false/path.html");
            }
            None => panic!("Cannot create uri from a valid one"),
        }

        match ::Uri::new("https://rust:1234567eight9@www.unknown.host:1345") {
            Some(uri) => {
                assert_eq!(uri.scheme, "https");
                assert_eq!(uri.host.unwrap(), "www.unknown.host");
                assert_eq!(uri.port.unwrap(), 1345);
                assert_eq!(uri.username.unwrap(), "rust");
                assert_eq!(uri.password.unwrap(), "1234567eight9");
            }
            None => panic!("Cannot create uri from a valid one"),
        }
    }

}