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
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
extern crate regex;

use self::regex::Regex;
use super::{Validated, ValidatedWrapper};

use std::error::Error;
use std::fmt::{self, Debug, Display, Formatter};
use std::hash::{Hash, Hasher};
use std::ops::Deref;
use std::str::{FromStr, Utf8Error};

lazy_static! {
    static ref URI_RE: Regex = {
        Regex::new(r"^(?i)([a-z][a-z0-9+.-]+):(//([^@]+@)?([a-z0-9.\-_~]+)(:\d+)?)?((?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])+(?:/(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])*)*|(?:/(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@])+)*)?(\?(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@]|[/?])+)?(\#(?:[a-z0-9-._~]|%[a-f0-9]|[!$&'()*+,;=:@]|[/?])+)?$").unwrap()
    };
}

#[derive(Debug, PartialEq, Clone)]
pub enum URIError {
    IncorrectFormat,
    UTF8Error(Utf8Error),
}

impl Display for URIError {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        Debug::fmt(self, f)
    }
}

impl Error for URIError {}

impl From<Utf8Error> for URIError {
    #[inline]
    fn from(err: Utf8Error) -> Self {
        URIError::UTF8Error(err)
    }
}

pub type URIResult = Result<URI, URIError>;

#[derive(Debug, PartialEq)]
pub struct URIValidator {}

#[derive(Clone)]
pub struct URI {
    full_uri: String,
    scheme: (usize, usize),
    authority: Option<(usize, usize)>,
    user_info: Option<(usize, usize)>,
    host: Option<(usize, usize)>,
    port: Option<u16>,
    path: Option<(usize, usize)>,
    query: Option<(usize, usize)>,
    fragment: Option<(usize, usize)>,
}

impl URI {
    #[inline]
    pub fn get_full_uri(&self) -> &str {
        &self.full_uri
    }

    #[inline]
    pub fn get_scheme(&self) -> &str {
        &self.full_uri[self.scheme.0..self.scheme.1]
    }

    #[inline]
    pub fn get_authority(&self) -> Option<&str> {
        if let Some(authority) = self.authority {
            Some(&self.full_uri[authority.0..authority.1])
        } else {
            None
        }
    }

    #[inline]
    pub fn get_user_info(&self) -> Option<&str> {
        if let Some(user_info) = self.user_info {
            Some(&self.full_uri[user_info.0..user_info.1])
        } else {
            None
        }
    }

    #[inline]
    pub fn get_host(&self) -> Option<&str> {
        if let Some(host) = self.host {
            Some(&self.full_uri[host.0..host.1])
        } else {
            None
        }
    }

    #[inline]
    pub fn get_port(&self) -> Option<u16> {
        self.port
    }

    #[inline]
    pub fn get_path(&self) -> Option<&str> {
        if let Some(path) = self.path {
            Some(&self.full_uri[path.0..path.1])
        } else {
            None
        }
    }

    #[inline]
    pub fn get_query(&self) -> Option<&str> {
        if let Some(query) = self.query {
            Some(&self.full_uri[query.0..query.1])
        } else {
            None
        }
    }

    #[inline]
    pub fn get_fragment(&self) -> Option<&str> {
        if let Some(fragment) = self.fragment {
            Some(&self.full_uri[fragment.0..fragment.1])
        } else {
            None
        }
    }

    #[inline]
    pub fn into_string(self) -> String {
        self.full_uri
    }
}

impl Deref for URI {
    type Target = str;

    #[inline]
    fn deref(&self) -> &Self::Target {
        &self.full_uri
    }
}

impl Validated for URI {}

impl Debug for URI {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        impl_debug_for_tuple_struct!(URI, f, self, let .0 = self.full_uri);
    }
}

impl Display for URI {
    #[inline]
    fn fmt(&self, f: &mut Formatter) -> fmt::Result {
        f.write_str(&self.full_uri)?;
        Ok(())
    }
}

impl PartialEq for URI {
    #[inline]
    fn eq(&self, other: &Self) -> bool {
        self.full_uri.eq(&other.full_uri)
    }
}

impl Eq for URI {}

impl Hash for URI {
    #[inline]
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.full_uri.hash(state)
    }
}

impl URIValidator {
    #[inline]
    pub fn is_uri(&self, full_uri: &str) -> bool {
        self.parse_inner(full_uri).is_ok()
    }

    #[inline]
    pub fn parse_string(&self, full_uri: String) -> URIResult {
        let mut uri_inner = self.parse_inner(&full_uri)?;

        uri_inner.full_uri = full_uri;

        Ok(uri_inner)
    }

    #[inline]
    pub fn parse_str(&self, full_uri: &str) -> URIResult {
        let mut uri_inner = self.parse_inner(full_uri)?;

        uri_inner.full_uri.push_str(full_uri);

        Ok(uri_inner)
    }

    fn parse_inner(&self, full_uri: &str) -> URIResult {
        let c = match URI_RE.captures(full_uri) {
            Some(c) => c,
            None => return Err(URIError::IncorrectFormat),
        };

        let scheme = match c.get(1) {
            Some(cc) => (cc.start(), cc.end()),
            None => unreachable!(),
        };

        let authority = match c.get(2) {
            Some(cc) => Some((cc.start() + 2, cc.end())),
            None => None,
        };

        let user_info = match c.get(3) {
            Some(cc) => Some((cc.start(), cc.end() - 1)),
            None => None,
        };

        let host = match c.get(4) {
            Some(cc) => Some((cc.start(), cc.end())),
            None => None,
        };

        let port = match c.get(5) {
            Some(cc) => Some(full_uri[(cc.start() + 1)..cc.end()].parse().unwrap()),
            None => None,
        };

        let path = match c.get(6) {
            Some(cc) => Some((cc.start(), cc.end())),
            None => None,
        };

        let query = match c.get(7) {
            Some(cc) => Some((cc.start() + 1, cc.end())),
            None => None,
        };

        let fragment = match c.get(8) {
            Some(cc) => Some((cc.start() + 1, cc.end())),
            None => None,
        };

        Ok(URI {
            full_uri: String::new(),
            scheme,
            authority,
            user_info,
            host,
            port,
            path,
            query,
            fragment,
        })
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_uri_methods() {
        let uri = "ssh://root@127.0.0.1:886/path/to?query=1#fragment".to_string();

        let uv = URIValidator {};

        let uri = uv.parse_string(uri).unwrap();

        assert_eq!("ssh://root@127.0.0.1:886/path/to?query=1#fragment", uri.get_full_uri());
        assert_eq!("ssh", uri.get_scheme());
        assert_eq!("root@127.0.0.1:886", uri.get_authority().unwrap());
        assert_eq!("root", uri.get_user_info().unwrap());
        assert_eq!("127.0.0.1", uri.get_host().unwrap());
        assert_eq!(886, uri.get_port().unwrap());
        assert_eq!("/path/to", uri.get_path().unwrap());
        assert_eq!("query=1", uri.get_query().unwrap());
        assert_eq!("fragment", uri.get_fragment().unwrap());
    }
}

// URI's wrapper struct is itself
impl ValidatedWrapper for URI {
    type Error = URIError;

    #[inline]
    fn from_string(full_uri: String) -> Result<Self, Self::Error> {
        URI::from_string(full_uri)
    }

    #[inline]
    fn from_str(full_uri: &str) -> Result<Self, Self::Error> {
        URI::from_str(full_uri)
    }
}

impl URI {
    #[inline]
    pub fn from_string(full_uri: String) -> Result<Self, URIError> {
        URI::create_validator().parse_string(full_uri)
    }

    #[inline]
    #[allow(clippy::should_implement_trait)]
    pub fn from_str(full_uri: &str) -> Result<Self, URIError> {
        URI::create_validator().parse_str(full_uri)
    }

    #[inline]
    fn create_validator() -> URIValidator {
        URIValidator {}
    }
}

impl FromStr for URI {
    type Err = URIError;

    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        URI::from_str(s)
    }
}

#[cfg(feature = "rocketly")]
impl<'a> ::rocket::request::FromFormValue<'a> for URI {
    type Error = URIError;

    #[inline]
    fn from_form_value(form_value: &'a ::rocket::http::RawStr) -> Result<Self, Self::Error> {
        URI::from_string(form_value.url_decode()?)
    }
}

#[cfg(feature = "rocketly")]
impl<'a> ::rocket::request::FromParam<'a> for URI {
    type Error = URIError;

    #[inline]
    fn from_param(param: &'a ::rocket::http::RawStr) -> Result<Self, Self::Error> {
        URI::from_string(param.url_decode()?)
    }
}

#[cfg(feature = "serdely")]
struct StringVisitor;

#[cfg(feature = "serdely")]
impl<'de> ::serde::de::Visitor<'de> for StringVisitor {
    type Value = URI;

    #[inline]
    fn expecting(&self, formatter: &mut fmt::Formatter) -> fmt::Result {
        formatter.write_str("a Base64 string")
    }

    #[inline]
    fn visit_str<E>(self, v: &str) -> Result<Self::Value, E>
    where
        E: ::serde::de::Error, {
        URI::from_str(v).map_err(|err| E::custom(err.to_string()))
    }

    #[inline]
    fn visit_string<E>(self, v: String) -> Result<Self::Value, E>
    where
        E: ::serde::de::Error, {
        URI::from_string(v).map_err(|err| E::custom(err.to_string()))
    }
}

#[cfg(feature = "serdely")]
impl<'de> ::serde::Deserialize<'de> for URI {
    #[inline]
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: ::serde::Deserializer<'de>, {
        deserializer.deserialize_string(StringVisitor)
    }
}

#[cfg(feature = "serdely")]
impl ::serde::Serialize for URI {
    #[inline]
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: ::serde::Serializer, {
        serializer.serialize_str(&self.full_uri)
    }
}