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
use std::ops::{Range, Deref};
use std::fmt;
use lazy_static::lazy_static;
use regex::Regex;
use crate::regex_generator;
#[derive(Clone)]
pub struct Url<S: AsRef<str>> {
full: S,
scheme: Option<Range<usize>>,
user: Option<Range<usize>>,
password: Option<Range<usize>>,
host: Option<Range<usize>>,
port: Option<Range<usize>>,
path: Option<Range<usize>>,
query: Option<Range<usize>>,
fragment: Option<Range<usize>>,
}
#[derive(Debug, PartialEq, Eq)]
pub enum Query<'a> {
Field(&'a str),
Form(&'a str, &'a str),
}
impl<S> Url<S>
where S: AsRef<str>
{
/**
Create a new Url instance.
Parse the url given in parameter and store it and ranges of several element present in the url into the instance.
If the url is well formed, it returns theUrl instance in an [`Ok`] value. An empty [`Err`] is returns otherwise (meaning parsing doesn't capture the url well)
**Note** : To parse the url, it uses a very long regular expression. As it works pretty well, it is planned to be improved.
*/
pub fn new(v: S) -> Result<Url<S>, &'static str> {
lazy_static! {
static ref URL_REGEX: Regex = {
Regex::new(regex_generator::url_regex())
.expect(r"/!\ Regex error from internal string. /!\")
};
}
let test = v.as_ref();
let captures: regex::Captures = match URL_REGEX.captures(test) {
Some(captures) => captures,
None => return Err("Url not valid"),
};
let (scheme, user, password, host, port, path, query, fragment) = {
let to_opt_range = |i| (&captures).get(i).map(|m| m.range());
(
to_opt_range(1),
to_opt_range(2),
to_opt_range(3),
to_opt_range(4),
to_opt_range(5),
to_opt_range(6),
to_opt_range(7),
to_opt_range(8),
)
};
Ok(Url {
full: v,
scheme, user, password, host, port, path, query, fragment
})
}
/**
Returns the complete url.
*/
pub fn full(&self) -> &str {
self.full.as_ref()
}
fn range_to_str(&self, range: &Option<Range<usize>>) -> Option<&str> {
range.clone().map(|s| &self.full.as_ref()[s])
}
/**
Returns the scheme of the url if present, [`None`] otherwise.
## Example
```
use url_compose::Url;
let url = Url::new("https://username:password@www.example.com:8080/path/to/file?field=value#fragment").unwrap();
assert_eq!(url.scheme(), Some("https"));
let url = Url::new("/path/example").unwrap();
assert_eq!(url.scheme(), None);
```
*/
pub fn scheme(&self) -> Option<&str>
{
self.range_to_str(&self.scheme)
}
/**
Returns the username of the url if present, [`None`] otherwise.
In a URL (to connect ftp for example), you can pass userinfo as `username:password`.
## Example
```
use url_compose::Url;
let url = Url::new("https://username:password@www.example.com:8080/path/to/file?field=value#fragment").unwrap();
assert_eq!(url.user(), Some("username"));
let url = Url::new("https://www.example.com").unwrap();
assert_eq!(url.user(), None);
```
*/
pub fn user(&self) -> Option<&str>
{
self.range_to_str(&self.user)
}
/**
Returns the password of the url if present, [`None`] otherwise.
In a URL (to connect ftp for example), you can pass userinfo as `username:password`.
Note that the password in the url is deprecated as the data is displayed in clear.
## Example
```
use url_compose::Url;
let url = Url::new("https://username:password@www.example.com:8080/path/to/file?field=value#fragment").unwrap();
assert_eq!(url.password(), Some("password"));
let url = Url::new("https://www.example.com").unwrap();
assert_eq!(url.password(), None);
```
*/
pub fn password(&self) -> Option<&str>
{
self.range_to_str(&self.password)
}
/**
Returns the host of the url if present, [`None`] otherwise.
## Example
```
use url_compose::Url;
let url = Url::new("https://username:password@www.example.com:8080/path/to/file?field=value#fragment").unwrap();
assert_eq!(url.host(), Some("www.example.com"));
let url = Url::new("http://localhost:8080").unwrap();
assert_eq!(url.host(), Some("localhost"));
let url = Url::new("/path/example").unwrap();
assert_eq!(url.host(), None);
```
*/
pub fn host(&self) -> Option<&str>
{
self.range_to_str(&self.host)
}
/**
Returns the port of the url if present, [`None`] otherwise.
## Example
```
use url_compose::Url;
let url = Url::new("https://username:password@www.example.com:8080/path/to/file?field=value#fragment").unwrap();
assert_eq!(url.port(), Some("8080"));
let url = Url::new("/path/example").unwrap();
assert_eq!(url.port(), None);
```
*/
pub fn port(&self) -> Option<&str>
{
self.range_to_str(&self.port)
}
/**
Returns the path of the url.
Even if the path returns an [`Option`], it will never return [`None`], but can return [`Some("")`]
[`Some("")`]: https://doc.rust-lang.org/nightly/core/option/enum.Option.html#variant.Some
## Example
```
use url_compose::Url;
let url = Url::new("https://username:password@www.example.com:8080/path/to/file?field=value#fragment").unwrap();
assert_eq!(url.path(), Some("/path/to/file"));
let url = Url::new("https://www.example.com").unwrap();
assert_eq!(url.path(), Some(""));
```
*/
pub fn path(&self) -> Option<&str>
{
self.range_to_str(&self.path)
}
/**
Returns the query of the url if present, [`None`] otherwise.
It returns the full query in a string slice, including the question mark.
To format into a [`Vec`], see [`Self::dispatch_query()`].
## Example
```
use url_compose::Url;
let url = Url::new("https://username:password@www.example.com:8080/path/to/file?field=value#fragment").unwrap();
assert_eq!(url.query(), Some("?field=value"));
let url = Url::new("/path/example").unwrap();
assert_eq!(url.query(), None);
```
*/
pub fn query(&self) -> Option<&str>
{
self.range_to_str(&self.query)
}
/**
Returns the fragment of the url if present, [`None`] otherwise.
## Example
```
use url_compose::Url;
let url = Url::new("https://username:password@www.example.com:8080/path/to/file?field=value#fragment").unwrap();
assert_eq!(url.frament(), Some("#fragment"));
let url = Url::new("/path/example").unwrap();
assert_eq!(url.frament(), None);
```
*/
pub fn fragment(&self) -> Option<&str>
{
self.range_to_str(&self.fragment)
}
/**
Split the query into a [`Vec`] of [`Query`].
## Example
```
use url_compose::Url;
use url_compose::Query::{Form, Field};
let url = Url::new("/?field1=value1&field2=value2&present").unwrap();
assert_eq!(url.dispatch_query(), [Form("field1", "value1"), Form("field2", "value2"), Field("present")]);
let url = Url::new("/?field1=value1;field2=value2").unwrap();
assert_eq!(url.dispatch_query(), [Form("field1", "value1"), Form("field2", "value2")]);
let url = Url::new("/").unwrap();
assert_eq!(url.dispatch_query(), []);
```
*/
pub fn dispatch_query(&self) -> Vec<Query> {
let queries = match self.query() {
Some(v) => v,
None => return Vec::new()
};
let queries = &queries[1..];
let mut result = vec![];
for query in queries.split(|c| c=='&' || c==';') {
result.push(match query.find('=') {
Some(pos) => Query::Form(&query[0..pos], &query[pos+1..]),
None => Query::Field(query)
});
}
result
}
/**
Split the host domains into a [`Vec`] of `&str`.
If the host isn't present in the url, the function returns a empty value.
## Example
```
use url_compose::Url;
let url = Url::new("https://www.example.com/").unwrap();
assert_eq!(url.dispatch_domains(), ["www","example","com"]);
let url = Url::new("/").unwrap();
assert_eq!(url.dispatch_domains(), [] as [&str;0]);
```
*/
pub fn dispatch_domains(&self) -> Vec<&str> {
match self.host() {
Some(domains) => domains.split('.').collect(),
None => Vec::new(),
}
}
}
impl<S> From<Url<S>> for String
where S: AsRef<str>
{
fn from(v: Url<S>) -> String {
String::from(v.full.as_ref())
}
}
impl<S> fmt::Debug for Url<S>
where S: AsRef<str>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Url")
.field("full", &self.full.as_ref())
.field("scheme", &self.scheme())
.field("user", &self.user())
.field("host", &self.host())
.field("port", &self.port())
.field("path", &self.path())
.field("query", &self.query())
.field("fragment", &self.fragment())
.finish()
}
}
impl<S> fmt::Display for Url<S>
where S: AsRef<str>
{
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write!(f, "{}", self.full.as_ref())
}
}
impl<S> AsRef<str> for Url<S>
where S: AsRef<str>
{
fn as_ref(&self) -> &str {
self.full()
}
}
impl<S> AsRef<[u8]> for Url<S>
where S: AsRef<str>
{
fn as_ref(&self) -> &[u8] {
self.full().as_ref()
}
}
impl<S> Deref for Url<S>
where S: AsRef<str>
{
type Target = str;
fn deref(&self) -> &str {
self.full()
}
}