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
//! **auris** is an experimental URI parsing library
//!
//! - Uses only safe features in rust.
//! - `rfc2396` & `rfc3986` compliant (incomplete)
//!
//!
//! ## Parses structure:
//!
//! ```notrust
//!     foo://example.com:8042/over/there?name=ferret#nose
//!     \_/   \______________/\_________/ \_________/ \__/
//!      |           |            |            |        |
//!   scheme     authority       path        query   fragment
//! ```
//!
//! # Usage
//!
//! ```
//! use auris::URI;
//!
//! "postgres://user:password@host".parse::<URI<String>>();
//!
//! "https://crates.io/crates/auris".parse::<URI<String>>();
//! ```
//!
//! ## Query strings
//!
//! We also parse query strings into HashMaps:
//!
//! ```
//! # use auris::URI;
//! "postgres://user:password@example.com/db?replication=true".parse::<URI<String>>();
//! ```
//!
//! In the case of duplicated query string tags the last one wins:
//! ```
//! # use auris::URI;
//! "scheme://host/path?a=1&a=2".parse::<URI<String>>();
//! ```
extern crate nom;
use std::str;

use core::hash::Hash;
use std::collections::HashMap;
use std::fmt;
use std::net::{Ipv4Addr, Ipv6Addr};
use std::str::FromStr;

pub mod parsers;

#[derive(Debug)]
pub enum AurisParseErrorKind {
    Failed,
}

#[derive(Debug)]
pub struct ParseError {
    kind: AurisParseErrorKind,
}

impl fmt::Display for ParseError {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        match &self.kind {
            AurisParseErrorKind::Failed => write!(f, "Parsing failed"),
        }
    }
}

/// Make impossible authentication states unrepresentable
#[derive(Debug, PartialEq, Eq)]
pub enum UserInfo<T> {
    User(T),
    UserAndPassword(T, T),
}

impl UserInfo<&str> {
    fn to_owned(&self) -> UserInfo<String> {
        match self {
            UserInfo::User(d) => UserInfo::User((*d).to_string()),
            UserInfo::UserAndPassword(u, p) => {
                UserInfo::UserAndPassword((*u).to_string(), (*p).to_string())
            }
        }
    }
}

impl fmt::Display for UserInfo<String> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self {
            UserInfo::User(user) => write!(f, "{}", user),
            UserInfo::UserAndPassword(user, password) => write!(f, "{}:{}", user, password),
        }
    }
}

/// Authority section of the URI
#[derive(Debug, PartialEq, Eq)]
pub struct Authority<T>
where
    T: Ord + Hash,
{
    //TODO(bradford): IPV6, IPV4, DNS enum
    pub host: T,
    pub userinfo: Option<UserInfo<T>>,
    pub port: Option<u16>,
}

impl Authority<&str> {
    fn to_owned(&self) -> Authority<String> {
        Authority {
            host: self.host.to_string(),
            userinfo: self.userinfo.as_ref().map(|u| u.to_owned()),
            port: self.port,
        }
    }
}

/// Converts the URI struct back to a string
///
/// # Examples
/// ```
/// use auris::{Authority, UserInfo};
///
/// assert_eq!("a:b@bob.com:443",
///     format!("{}", Authority {
///       host: "bob.com".to_string(),
///       userinfo: Some(UserInfo::UserAndPassword("a".to_string(), "b".to_string())),
///       port: Some(443),
///     }));
/// ```
impl fmt::Display for Authority<String> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut formatted = String::new();
        // using a match as this feels cleaner than a map
        let userinfo_string = match self.userinfo.as_ref() {
            Some(userinfo) => format!("{}@", userinfo),
            None => String::new(),
        };
        formatted.push_str(&userinfo_string);
        formatted.push_str(&self.host);
        let port_string = match self.port.as_ref() {
            Some(port) => format!(":{}", port),
            None => String::new(),
        };
        formatted.push_str(&port_string);
        write!(f, "{}", formatted)
    }
}

/// URI is the whole URI object
///
/// # Examples
///
/// When parsing whole URIs:
///
/// ```
/// use auris::URI;
/// "http://bob.com".parse::<URI<String>>();
/// ```
///
#[derive(Debug, PartialEq, Eq)]
pub struct URI<T>
where
    T: Ord + Hash,
{
    pub scheme: T,
    pub authority: Authority<T>,
    pub path: Option<Vec<T>>,
    pub qs: Option<HashMap<T, T>>,
}

impl URI<&str> {
    fn to_owned(&self) -> URI<String> {
        URI {
            scheme: self.scheme.to_owned(),
            authority: self.authority.to_owned(),
            path: self
                .path
                .as_ref()
                .map(|p: &Vec<&str>| p.iter().map(|f| String::from(*f)).collect()),
            qs: self.qs.as_ref().map(|qs| {
                qs.iter()
                    .map(|(k, v)| ((*k).to_string(), (*v).to_string()))
                    .collect()
            }),
        }
    }
}

impl FromStr for URI<String> {
    type Err = ParseError;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match parsers::uri(s) {
            Ok((_, obj)) => Ok(obj.to_owned()),
            Err(_) => Err(ParseError {
                kind: AurisParseErrorKind::Failed,
            }),
        }
    }
}
/// Converts the URI struct back to a string
///
/// # Examples
/// ```
/// use auris::URI;
///
/// let parsed = "http://bob.com".parse::<URI<String>>().unwrap();
///
/// assert_eq!("http://bob.com",
///     format!("{}", parsed));
/// ```
impl fmt::Display for URI<String> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut formatted = String::new();
        formatted.push_str(&self.scheme);
        formatted.push_str("://");
        formatted.push_str(&format!("{}", self.authority));
        write!(f, "{}", formatted)
    }
}

// The host name of an URL.
pub enum Host<S = String> {
    Domain(S),
    Ipv4(Ipv4Addr),
    Ipv6(Ipv6Addr),
}