sxurl 0.1.0

Fixed-length, sliceable URL identifier system for efficient database storage and querying
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
//! Essential URL parsing and manipulation utilities.
//!
//! This module provides convenient functions for common URL operations that aren't
//! easily available in the standard `url` crate or require combining multiple operations.

use url::Url;
use crate::error::SxurlError;
use crate::url::psl::split_host_with_psl;
use std::collections::HashMap;

/// Complete URL parts extracted from a URL string.
#[derive(Debug, Clone, PartialEq)]
pub struct UrlParts {
    /// URL scheme (https, http, ftp)
    pub scheme: String,
    /// Full hostname (api.example.com)
    pub host: String,
    /// Port number (if specified or non-default)
    pub port: Option<u16>,
    /// Path component (/api/v1/users)
    pub path: String,
    /// Query string without the '?' (foo=bar&baz=qux)
    pub query: Option<String>,
    /// Anchor/fragment without the '#' (section1)
    pub anchor: Option<String>,
    /// Domain name only (example)
    pub domain: String,
    /// Top-level domain (com, org, co.uk)
    pub tld: String,
    /// Subdomain if present (api, www)
    pub subdomain: Option<String>,
}

/// Parse a URL into all its components at once.
///
/// This is more convenient than calling multiple methods on a `Url` object
/// and provides domain splitting using the Public Suffix List.
///
/// # Examples
///
/// ```
/// use sxurl::split_url;
///
/// let parts = split_url("https://api.github.com/repos?page=1#readme").unwrap();
/// assert_eq!(parts.scheme, "https");
/// assert_eq!(parts.domain, "github");
/// assert_eq!(parts.subdomain, Some("api".to_string()));
/// assert_eq!(parts.anchor, Some("readme".to_string()));
/// ```
pub fn split_url(url: &str) -> Result<UrlParts, SxurlError> {
    let parsed = Url::parse(url)?;

    // Get basic components
    let scheme = parsed.scheme().to_string();
    let host = parsed.host_str().ok_or(SxurlError::HostNotDns)?.to_string();

    // Handle port - if explicitly specified in URL, include it even if it's the default
    let port = if url.contains(&format!("{}:", &host)) {
        // Port is explicitly specified in the URL
        Some(parsed.port().unwrap_or_else(|| {
            // If parsed.port() is None but we detected a colon, it's a default port
            match scheme.as_str() {
                "https" => 443,
                "http" => 80,
                "ftp" => 21,
                _ => 80,
            }
        }))
    } else {
        parsed.port()
    };

    let path = parsed.path().to_string();
    let query = parsed.query().map(|q| q.to_string());
    let anchor = parsed.fragment().map(|f| f.to_string());

    // Split domain using PSL
    let (tld, domain, subdomain_str) = split_host_with_psl(&host)?;
    let subdomain = if subdomain_str.is_empty() {
        None
    } else {
        Some(subdomain_str)
    };

    Ok(UrlParts {
        scheme,
        host,
        port,
        path,
        query,
        anchor,
        domain,
        tld,
        subdomain,
    })
}

/// Split a URL's domain into subdomain, domain, and TLD parts.
///
/// Uses the Public Suffix List for accurate domain splitting.
///
/// # Examples
///
/// ```
/// use sxurl::split_domain;
///
/// let (sub, domain, tld) = split_domain("https://api.github.com").unwrap();
/// assert_eq!(sub, Some("api".to_string()));
/// assert_eq!(domain, "github");
/// assert_eq!(tld, "com");
/// ```
///
/// # Returns
///
/// Returns `(subdomain, domain, tld)` where subdomain is `None` if not present.
pub fn split_domain(url: &str) -> Result<(Option<String>, String, String), SxurlError> {
    let parsed = Url::parse(url)?;
    let host = parsed.host_str().ok_or(SxurlError::HostNotDns)?;

    let (tld, domain, subdomain_str) = split_host_with_psl(host)?;
    let subdomain = if subdomain_str.is_empty() {
        None
    } else {
        Some(subdomain_str)
    };

    Ok((subdomain, domain, tld))
}

/// Split a URL's path into segments.
///
/// Removes empty segments and decodes percent-encoded characters.
///
/// # Examples
///
/// ```
/// use sxurl::get_path_segments;
///
/// let segments = get_path_segments("https://example.com/api/v1/users").unwrap();
/// assert_eq!(segments, vec!["api", "v1", "users"]);
/// ```
pub fn get_path_segments(url: &str) -> Result<Vec<String>, SxurlError> {
    let parsed = Url::parse(url)?;
    Ok(parsed.path_segments()
        .unwrap_or_else(|| "".split('/'))
        .filter(|s| !s.is_empty())
        .map(|s| s.to_string())
        .collect())
}

/// Extract the filename from a URL path.
///
/// Returns the last path segment if it appears to be a filename
/// (contains a dot or is the last non-empty segment).
///
/// # Examples
///
/// ```
/// use sxurl::get_filename;
///
/// let filename = get_filename("https://example.com/docs/file.pdf").unwrap();
/// assert_eq!(filename, Some("file.pdf".to_string()));
///
/// let no_file = get_filename("https://example.com/api/users/").unwrap();
/// assert_eq!(no_file, None);
/// ```
pub fn get_filename(url: &str) -> Result<Option<String>, SxurlError> {
    let segments = get_path_segments(url)?;

    if let Some(last) = segments.last() {
        // Consider it a filename if it has an extension or is the only segment
        if last.contains('.') || segments.len() == 1 {
            Ok(Some(last.clone()))
        } else {
            Ok(None)
        }
    } else {
        Ok(None)
    }
}

/// Parse query string into a HashMap of key-value pairs.
///
/// Handles URL decoding of both keys and values.
///
/// # Examples
///
/// ```
/// use sxurl::parse_query;
///
/// let params = parse_query("https://example.com?foo=bar&page=1").unwrap();
/// assert_eq!(params.get("foo"), Some(&"bar".to_string()));
/// assert_eq!(params.get("page"), Some(&"1".to_string()));
/// ```
pub fn parse_query(url: &str) -> Result<HashMap<String, String>, SxurlError> {
    let parsed = Url::parse(url)?;

    let mut params = HashMap::new();
    for (key, value) in parsed.query_pairs() {
        params.insert(key.to_string(), value.to_string());
    }

    Ok(params)
}

/// Get a specific query parameter value.
///
/// # Examples
///
/// ```
/// use sxurl::get_query_value;
///
/// let value = get_query_value("https://example.com?page=2&sort=name", "page").unwrap();
/// assert_eq!(value, Some("2".to_string()));
///
/// let missing = get_query_value("https://example.com?page=2", "missing").unwrap();
/// assert_eq!(missing, None);
/// ```
pub fn get_query_value(url: &str, key: &str) -> Result<Option<String>, SxurlError> {
    let params = parse_query(url)?;
    Ok(params.get(key).cloned())
}

/// Get the anchor (fragment) from a URL.
///
/// Returns the fragment component without the '#' character.
///
/// # Examples
///
/// ```
/// use sxurl::get_anchor;
///
/// let anchor = get_anchor("https://docs.rs/serde#examples").unwrap();
/// assert_eq!(anchor, Some("examples".to_string()));
///
/// let no_anchor = get_anchor("https://example.com").unwrap();
/// assert_eq!(no_anchor, None);
/// ```
pub fn get_anchor(url: &str) -> Result<Option<String>, SxurlError> {
    let parsed = Url::parse(url)?;
    Ok(parsed.fragment().map(|f| f.to_string()))
}

/// Remove the anchor (fragment) from a URL.
///
/// # Examples
///
/// ```
/// use sxurl::strip_anchor;
///
/// let clean = strip_anchor("https://example.com/page#section").unwrap();
/// assert_eq!(clean, "https://example.com/page");
/// ```
pub fn strip_anchor(url: &str) -> Result<String, SxurlError> {
    let mut parsed = Url::parse(url)?;
    parsed.set_fragment(None);
    Ok(parsed.to_string())
}

/// Join a base URL with a path segment.
///
/// Properly handles trailing slashes and relative path resolution.
///
/// # Examples
///
/// ```
/// use sxurl::join_url_path;
///
/// let url1 = join_url_path("https://api.example.com/v1", "users").unwrap();
/// assert_eq!(url1, "https://api.example.com/v1/users");
///
/// let url2 = join_url_path("https://api.example.com/v1/", "users").unwrap();
/// assert_eq!(url2, "https://api.example.com/v1/users");
/// ```
pub fn join_url_path(base_url: &str, path: &str) -> Result<String, SxurlError> {
    let mut base = Url::parse(base_url)?;

    // Ensure the base path ends with a slash for proper joining
    let mut base_path = base.path().to_string();
    if !base_path.ends_with('/') {
        base_path.push('/');
        base.set_path(&base_path);
    }

    let joined = base.join(path)?;
    Ok(joined.to_string())
}

/// Check if a URL uses HTTPS scheme.
///
/// # Examples
///
/// ```
/// use sxurl::is_https;
///
/// assert!(is_https("https://example.com"));
/// assert!(!is_https("http://example.com"));
/// ```
pub fn is_https(url: &str) -> bool {
    url.starts_with("https://")
}

/// Check if a URL has a query string.
///
/// # Examples
///
/// ```
/// use sxurl::has_query;
///
/// assert!(has_query("https://example.com?foo=bar"));
/// assert!(!has_query("https://example.com"));
/// ```
pub fn has_query(url: &str) -> bool {
    url.contains('?')
}

/// Check if a URL has an anchor (fragment).
///
/// # Examples
///
/// ```
/// use sxurl::has_anchor;
///
/// assert!(has_anchor("https://example.com#section"));
/// assert!(!has_anchor("https://example.com"));
/// ```
pub fn has_anchor(url: &str) -> bool {
    url.contains('#')
}

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

    #[test]
    fn test_split_url_complete() {
        let parts = split_url("https://api.github.com:443/repos?page=1&sort=name#readme").unwrap();

        assert_eq!(parts.scheme, "https");
        assert_eq!(parts.host, "api.github.com");
        assert_eq!(parts.port, Some(443));
        assert_eq!(parts.path, "/repos");
        assert_eq!(parts.query, Some("page=1&sort=name".to_string()));
        assert_eq!(parts.anchor, Some("readme".to_string()));
        assert_eq!(parts.domain, "github");
        assert_eq!(parts.tld, "com");
        assert_eq!(parts.subdomain, Some("api".to_string()));
    }

    #[test]
    fn test_split_url_minimal() {
        let parts = split_url("https://example.com").unwrap();

        assert_eq!(parts.scheme, "https");
        assert_eq!(parts.host, "example.com");
        assert_eq!(parts.port, None);
        assert_eq!(parts.path, "/");
        assert_eq!(parts.query, None);
        assert_eq!(parts.anchor, None);
        assert_eq!(parts.domain, "example");
        assert_eq!(parts.tld, "com");
        assert_eq!(parts.subdomain, None);
    }

    #[test]
    fn test_split_domain() {
        let (sub, domain, tld) = split_domain("https://api.github.com").unwrap();
        assert_eq!(sub, Some("api".to_string()));
        assert_eq!(domain, "github");
        assert_eq!(tld, "com");

        let (sub2, domain2, tld2) = split_domain("https://example.co.uk").unwrap();
        assert_eq!(sub2, None);
        assert_eq!(domain2, "example");
        assert_eq!(tld2, "co.uk");
    }

    #[test]
    fn test_get_path_segments() {
        let segments = get_path_segments("https://example.com/api/v1/users").unwrap();
        assert_eq!(segments, vec!["api", "v1", "users"]);

        let empty = get_path_segments("https://example.com/").unwrap();
        assert_eq!(empty, Vec::<String>::new());
    }

    #[test]
    fn test_get_filename() {
        let filename = get_filename("https://example.com/docs/file.pdf").unwrap();
        assert_eq!(filename, Some("file.pdf".to_string()));

        let no_file = get_filename("https://example.com/api/users/").unwrap();
        assert_eq!(no_file, None);

        let single_segment = get_filename("https://example.com/file").unwrap();
        assert_eq!(single_segment, Some("file".to_string()));
    }

    #[test]
    fn test_parse_query() {
        let params = parse_query("https://example.com?foo=bar&page=1").unwrap();
        assert_eq!(params.get("foo"), Some(&"bar".to_string()));
        assert_eq!(params.get("page"), Some(&"1".to_string()));

        let empty = parse_query("https://example.com").unwrap();
        assert!(empty.is_empty());
    }

    #[test]
    fn test_get_query_value() {
        let value = get_query_value("https://example.com?page=2&sort=name", "page").unwrap();
        assert_eq!(value, Some("2".to_string()));

        let missing = get_query_value("https://example.com?page=2", "missing").unwrap();
        assert_eq!(missing, None);
    }

    #[test]
    fn test_anchor_operations() {
        let anchor = get_anchor("https://docs.rs/serde#examples").unwrap();
        assert_eq!(anchor, Some("examples".to_string()));

        let no_anchor = get_anchor("https://example.com").unwrap();
        assert_eq!(no_anchor, None);

        let clean = strip_anchor("https://example.com/page#section").unwrap();
        assert_eq!(clean, "https://example.com/page");
    }

    #[test]
    fn test_join_url_path() {
        let url1 = join_url_path("https://api.example.com/v1", "users").unwrap();
        assert_eq!(url1, "https://api.example.com/v1/users");

        let url2 = join_url_path("https://api.example.com/v1/", "users").unwrap();
        assert_eq!(url2, "https://api.example.com/v1/users");

        let url3 = join_url_path("https://api.example.com", "../other").unwrap();
        assert_eq!(url3, "https://api.example.com/other");
    }

    #[test]
    fn test_url_checks() {
        assert!(is_https("https://example.com"));
        assert!(!is_https("http://example.com"));

        assert!(has_query("https://example.com?foo=bar"));
        assert!(!has_query("https://example.com"));

        assert!(has_anchor("https://example.com#section"));
        assert!(!has_anchor("https://example.com"));
    }
}