urlable 0.2.0

A comprehensive URL manipulation library for Rust, providing utilities for parsing, encoding, and manipulating URLs with support for query strings, path manipulation, punycode domains and more
Documentation
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
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
use lazy_static::lazy_static;
use percent_encoding::percent_decode_str;
use regex::Regex;
use url::Url;

lazy_static! {
    /**
    Regular expression for matching special protocol URLs

    Matches URLs starting with the following protocols:
    - blob: (e.g. "blob:https://example.com/1234-5678")
    - data: (e.g. "data:image/png;base64,...")
    - javascript: (e.g. "javascript:alert('hello')")
    - vbscript: (e.g. "vbscript:MsgBox('hello')")
    - file: (e.g. "file:///path/to/file.txt")
    - ftp: (e.g. "ftp://ftp.example.com/file.zip")
    - gopher: (e.g. "gopher://gopher.example.com")
    - mailto: (e.g. "mailto:user@example.com")
    - news: (e.g. "news:comp.lang.rust")
    - telnet: (e.g. "telnet://example.com:23")
    - view-source: (e.g. "view-source:https://example.com")
    */
    static ref SPECIAL_PROTO_RE: Regex = Regex::new(
        r"^[[:space:]\x00]*((blob|data|javascript|vbscript|file|ftp|gopher|mailto|news|telnet|view-source):)(.*)"
    ).unwrap();

    /**
    Regular expression for parsing URL components

    Captures:
    1. Path portion before ? or # ([^#?]*)
    2. Query string portion with leading ? (\?[^#]*)?
    3. Fragment portion with leading # (#.*)?
    */
    static ref URL_COMPONENTS_RE: Regex = Regex::new(r"([^#?]*)(\?[^#]*)?(#.*)?").unwrap();

    /**
    Regular expression for matching URL host components

    Captures:
    1. Hostname portion ([^/:]*)
    2. Optional port number (:?\d+)?
    */
    static ref URL_HOST_RE: Regex = Regex::new(r"([^/:]*):?(\d+)?").unwrap();

}

#[derive(Debug, Clone)]
pub struct ParsedURL {
    /// Protocol of the URL (e.g. "http:", "https:", "ftp:")
    pub protocol: Option<String>,
    /// Host of the URL (e.g. "example.com:8080")
    pub host: Option<String>,
    /// Hostname without port (e.g. "example.com")
    pub hostname: Option<String>,
    /// Authentication info in the URL (e.g. "username:password")
    pub auth: Option<String>,
    /// Path portion of the URL (e.g. "/path/to/resource")
    pub pathname: String,
    /// Fragment identifier portion of the URL (e.g. "#section1")
    pub hash: String,
    /// Query string portion of the URL (e.g. "?key1=value1&key2=value2")
    pub search: String,
    /// Complete URL string (e.g. "https://example.com/path?query#hash")
    pub href: Option<String>,
    /// Whether the URL is protocol-relative (starts with "//")
    pub protocol_relative: bool,
}

/// Represents authentication information parsed from a URL
#[derive(Debug, Clone)]
pub struct ParsedAuth {
    /// The username portion of the authentication (e.g. "admin")
    pub username: String,
    /// The password portion of the authentication (e.g. "secret123")
    pub password: String,
}

/// Represents host information parsed from a URL
#[derive(Debug, Clone)]
pub struct ParsedHost {
    /// The hostname portion of the URL (e.g. "example.com")
    pub hostname: String,
    /// The port number as a string (e.g. "8080")
    pub port: String,
}

/// Parses a URL string into its components
///
/// This function takes a URL string and parses it into a `ParsedURL` struct containing
/// the individual components like protocol, host, path, etc.
///
/// # Arguments
///
/// * `input` - The URL string to parse
///
/// # Returns
///
/// * `ParsedURL` - A struct containing the parsed URL components:
///   - `protocol`: The URL protocol/scheme (e.g. "http:", "https:")
///   - `host`: The host portion including port if specified (e.g. "example.com:8080")
///   - `hostname`: The hostname without port (e.g. "example.com")
///   - `auth`: Authentication credentials if present (e.g. "username:password")
///   - `pathname`: The path portion (e.g. "/path/to/resource")
///   - `search`: The query string portion (e.g. "?key=value")
///   - `hash`: The fragment identifier (e.g. "#section1")
///   - `href`: The complete URL string
///   - `protocol_relative`: Whether URL is protocol-relative (starts with "//")
pub fn parse_url(input: &str) -> ParsedURL {
    // Handle special protocols
    // Example:
    // Input: "blob:https://example.com/some-path"
    // proto = "blob:"
    // pathname = "https://example.com/some-path"
    if let Some(captures) = SPECIAL_PROTO_RE.captures(input) {
        let proto = captures
            .get(2)
            .map(|m| m.as_str().to_lowercase())
            .unwrap_or_default();
        let pathname = captures
            .get(3)
            .map(|m| m.as_str().to_string())
            .unwrap_or_default();

        return ParsedURL {
            protocol: Some(proto.clone()),
            pathname: pathname.clone(),
            href: Some(format!("{}{}", proto, pathname)),
            auth: Some(String::new()),
            host: Some(String::new()),
            hostname: Some(String::new()),
            search: String::new(),
            hash: String::new(),
            protocol_relative: false,
        };
    }

    match Url::parse(input) {
        Ok(url) => {
            let host = url.host_str().map(String::from);
            let hostname = url.host_str().map(String::from);
            let port = url.port().map(|p| p.to_string());

            ParsedURL {
                protocol: Some(url.scheme().to_string()),
                host: match (host.clone(), port) {
                    (Some(h), Some(p)) => Some(format!("{}:{}", h, p)),
                    (Some(h), None) => Some(h),
                    _ => None,
                },
                hostname,
                auth: if !url.username().is_empty() {
                    Some(format!(
                        "{}:{}",
                        url.username(),
                        url.password().unwrap_or("")
                    ))
                } else {
                    None
                },
                pathname: url.path().to_string(),
                hash: url
                    .fragment()
                    .map(|f| format!("#{}", f))
                    .unwrap_or_default(),
                search: url.query().map(|q| format!("?{}", q)).unwrap_or_default(),
                href: Some(url.to_string()),
                protocol_relative: false,
            }
        }
        // Handle error cases like:
        // - "http://" (missing host)
        // - "http://[" (invalid IPv6 address)
        // - "http://example.com:-80" (invalid port)
        // - "http://user:@host" (empty password)
        // In these cases, fall back to parsing as a path
        Err(_) => parse_path(input),
    }
}

/// Parses a URL with a default protocol
///
/// # Arguments
/// * `input` - The URL to parse
/// * `proto` - The default protocol to use if input doesn't have one
///
/// # Returns
/// * `ParsedURL` - A struct containing the parsed URL components
pub fn parse_url_with_protocol(input: &str, proto: &str) -> ParsedURL {
    if !has_protocol(input) {
        parse_url(&format!("{}://{}", proto, input))
    } else {
        parse_url(input)
    }
}

/// Splits the input string into pathname, search, and hash components
///
/// # Arguments
/// * `input` - The path to parse (e.g. "/path?query#hash", "/users/123", "/search?q=test#results")
///
/// # Returns
/// * `ParsedURL` - A struct containing the parsed path components
pub fn parse_path(input: &str) -> ParsedURL {
    let caps = URL_COMPONENTS_RE
        .captures(input)
        .unwrap_or_else(|| URL_COMPONENTS_RE.captures("").unwrap());

    ParsedURL {
        pathname: caps.get(1).map_or("", |m| m.as_str()).to_string(),
        search: caps.get(2).map_or("", |m| m.as_str()).to_string(),
        hash: caps.get(3).map_or("", |m| m.as_str()).to_string(),
        protocol: None,
        host: None,
        hostname: None,
        auth: None,
        href: None,
        protocol_relative: false,
    }
}

/// Parse authentication string into username and password
///
/// # Arguments
/// * `input` - The auth string to parse
///
/// # Returns
/// * `ParsedAuth` - A struct containing the username and password
pub fn parse_auth(input: &str) -> ParsedAuth {
    let parts: Vec<&str> = input.split(':').collect();
    ParsedAuth {
        username: percent_decode_str(parts.first().unwrap_or(&""))
            .decode_utf8_lossy()
            .to_string(),
        password: percent_decode_str(parts.get(1).unwrap_or(&""))
            .decode_utf8_lossy()
            .to_string(),
    }
}

/// Parse host string into hostname and port
///
/// # Arguments
/// * `input` - The host string to parse (e.g. "example.com:8080", "localhost:3000")
///
/// # Returns
/// * `ParsedHost` - A struct containing the hostname and port
pub fn parse_host(input: &str) -> ParsedHost {
    let caps = URL_HOST_RE
        .captures(input)
        .unwrap_or_else(|| URL_HOST_RE.captures("").unwrap());

    ParsedHost {
        hostname: percent_decode_str(caps.get(1).map_or("", |m| m.as_str()))
            .decode_utf8_lossy()
            .to_string(),
        port: caps.get(2).map_or("", |m| m.as_str()).to_string(),
    }
}

/// Regex explanation:
/// ^ - Match start of string
/// [\s\w+.-] - Match any:
///   \s - whitespace character
///   \w - word character (letter, number, underscore)
///   +  - plus sign
///   .  - period
///   -  - hyphen
/// {2,} - Match 2 or more of the previous character set
/// :// - Match "://" literally
///
/// Examples that would match:
/// "http://"
/// "https://"
/// "ftp://"
/// "ws://"
/// "wss://"
fn has_protocol(input: &str) -> bool {
    Regex::new(r"^[\s\w+.-]{2,}://").unwrap().is_match(input)
}

#[derive(Default)]
pub struct ParsedURLConfig {
    pub trailing_slash: bool,
}

impl ParsedURLConfig {
    pub fn new() -> Self {
        Self::default()
    }

    pub fn with_trailing_slash(mut self, trailing_slash: bool) -> Self {
        self.trailing_slash = trailing_slash;
        self
    }
}

impl ParsedURL {
    fn format_search(&self) -> String {
        if self.search.starts_with('?') {
            self.search.clone()
        } else if !self.search.is_empty() {
            format!("?{}", self.search)
        } else {
            String::new()
        }
    }

    fn format_hash(&self) -> String {
        if !self.hash.is_empty() {
            self.hash.clone()
        } else {
            String::new()
        }
    }

    fn format_auth(&self) -> String {
        if self.auth.as_ref().map_or(true, |a| a.is_empty()) {
            String::new()
        } else {
            format!("{}@", self.auth.as_ref().unwrap())
        }
    }

    fn format_host(&self) -> String {
        self.host.as_ref().map_or(String::new(), |h| h.clone())
    }

    fn format_protocol(&self) -> String {
        if self.protocol_relative {
            "//".to_string()
        } else {
            self.protocol.as_ref().map_or(String::new(), |p| {
                if p.ends_with("://") {
                    p.clone()
                } else if !p.is_empty() {
                    format!("{}://", p)
                } else {
                    String::new()
                }
            })
        }
    }

    fn format_pathname(&self) -> String {
        if self.pathname == "/" {
            String::new()
        } else {
            self.pathname.clone()
        }
    }

    pub fn stringify(&self) -> String {
        format!(
            "{}{}{}{}{}{}",
            self.format_protocol(),
            self.format_auth(),
            self.format_host(),
            self.format_pathname(),
            self.format_search(),
            self.format_hash()
        )
    }
}

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

    #[test]
    fn test_parse_url() {
        let url = parse_url("https://example.com/path?query=value#fragment");
        assert_eq!(url.protocol, Some("https".to_string()));
        assert_eq!(url.host, Some("example.com".to_string()));
        assert_eq!(url.hostname, Some("example.com".to_string()));
        assert_eq!(url.pathname, "/path");
        assert_eq!(url.search, "?query=value");
        assert_eq!(url.hash, "#fragment");

        let url = parse_url("blob:https://example.com/some-path");
        assert_eq!(url.protocol, Some("blob".to_string()));
        assert_eq!(url.pathname, "https://example.com/some-path");
    }

    #[test]
    fn test_parse_url_with_protocol() {
        let parsed = parse_url_with_protocol("example.com/path", "https");
        assert_eq!(parsed.protocol, Some("https".to_string()));
        assert_eq!(parsed.host, Some("example.com".to_string()));
        assert_eq!(parsed.hostname, Some("example.com".to_string()));
        assert_eq!(parsed.pathname, "/path");

        let parsed = parse_url_with_protocol("http://example.com", "https");
        assert_eq!(parsed.protocol, Some("http".to_string()));

        let parsed = parse_url_with_protocol("user:pass@example.com", "https");
        assert_eq!(parsed.protocol, Some("https".to_string()));
        assert_eq!(parsed.auth, Some("user:pass".to_string()));

        let parsed = parse_url_with_protocol("localhost:8080/api", "http");
        assert_eq!(parsed.protocol, Some("http".to_string()));
        assert_eq!(parsed.host, Some("localhost:8080".to_string()));
        assert_eq!(parsed.hostname, Some("localhost".to_string()));
    }

    #[test]
    fn test_parse_path() {
        let parsed = parse_path("/path?query#hash");
        assert_eq!(parsed.pathname, "/path");
        assert_eq!(parsed.search, "?query");
        assert_eq!(parsed.hash, "#hash");

        let parsed = parse_path("/users/123/posts");
        assert_eq!(parsed.pathname, "/users/123/posts");

        let parsed = parse_path("/search?q=test&page=1&sort=desc#top");
        assert_eq!(parsed.pathname, "/search");
        assert_eq!(parsed.search, "?q=test&page=1&sort=desc");
        assert_eq!(parsed.hash, "#top");
    }

    #[test]
    fn test_parse_auth() {
        let auth = parse_auth("admin:secret123");
        assert_eq!(auth.username, "admin");
        assert_eq!(auth.password, "secret123");

        let auth = parse_auth("user%40example.com:pass%21word");
        assert_eq!(auth.username, "user@example.com");
        assert_eq!(auth.password, "pass!word");

        let auth = parse_auth("username");
        assert_eq!(auth.username, "username");
        assert_eq!(auth.password, "");
    }

    #[test]
    fn test_parse_host() {
        let host = parse_host("example.com:8080");
        assert_eq!(host.hostname, "example.com");
        assert_eq!(host.port, "8080");

        let host = parse_host("example.com");
        assert_eq!(host.hostname, "example.com");
        assert_eq!(host.port, "");

        let host = parse_host("sub.example%2Ecom:9000");
        assert_eq!(host.hostname, "sub.example.com");
        assert_eq!(host.port, "9000");
    }

    #[test]
    fn test_has_protocol() {
        assert!(has_protocol("http://example.com"));
        assert!(has_protocol("https://example.com"));
        assert!(has_protocol("ftp://files.example.com"));
        assert!(has_protocol("file:///path/to/file.txt"));
        assert!(has_protocol("myapp://open/resource"));
        assert!(!has_protocol("example.com"));
    }

    #[test]
    fn test_parsed_url_stringify() {
        let parsed = ParsedURL {
            protocol: Some("http".to_string()),
            host: Some("example.com".to_string()),
            hostname: Some("example.com".to_string()),
            auth: None,
            pathname: "/path".to_string(),
            search: "?query=1".to_string(),
            hash: "#hash".to_string(),
            href: None,
            protocol_relative: false,
        };
        assert_eq!(parsed.stringify(), "http://example.com/path?query=1#hash");

        let parsed = ParsedURL {
            protocol: Some("https".to_string()),
            host: Some("example.com".to_string()),
            hostname: Some("example.com".to_string()),
            auth: Some("user:pass".to_string()),
            pathname: "/".to_string(),
            search: String::new(),
            hash: String::new(),
            href: None,
            protocol_relative: false,
        };
        assert_eq!(parsed.stringify(), "https://user:pass@example.com");

        let parsed = ParsedURL {
            protocol: None,
            host: Some("cdn.example.com".to_string()),
            hostname: Some("cdn.example.com".to_string()),
            auth: None,
            pathname: "/assets/img.png".to_string(),
            search: String::new(),
            hash: String::new(),
            href: None,
            protocol_relative: true,
        };
        assert_eq!(parsed.stringify(), "//cdn.example.com/assets/img.png");

        let parsed = ParsedURL {
            protocol: Some("http".to_string()),
            host: Some("localhost:8080".to_string()),
            hostname: Some("localhost".to_string()),
            auth: None,
            pathname: "/api".to_string(),
            search: String::new(),
            hash: String::new(),
            href: None,
            protocol_relative: false,
        };
        assert_eq!(parsed.stringify(), "http://localhost:8080/api");

        let parsed = ParsedURL {
            protocol: Some("https".to_string()),
            host: Some("api.example.com".to_string()),
            hostname: Some("api.example.com".to_string()),
            auth: None,
            pathname: "/search".to_string(),
            search: "?q=test&page=1&sort=desc".to_string(),
            hash: "#results".to_string(),
            href: None,
            protocol_relative: false,
        };
        assert_eq!(
            parsed.stringify(),
            "https://api.example.com/search?q=test&page=1&sort=desc#results"
        );

        let parsed = ParsedURL {
            protocol: Some("file".to_string()),
            host: None,
            hostname: None,
            auth: None,
            pathname: "/path/to/my file.txt".to_string(),
            search: String::new(),
            hash: String::new(),
            href: None,
            protocol_relative: false,
        };
        assert_eq!(parsed.stringify(), "file:///path/to/my file.txt");
    }
}