nourl 0.1.4

A simple Url primitive for no_std environments
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
#![no_std]
#[cfg(feature = "defmt")]
mod defmt_impl;
mod error;

pub use crate::error::Error;

use core::{
    net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr, SocketAddrV4, SocketAddrV6},
    str::FromStr,
};

#[derive(Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
/// A parsed URL to extract different parts of the URL.
pub struct Url<'a> {
    scheme: UrlScheme,
    host: &'a str,
    is_host_ipv6: bool,
    scope_id: Option<u32>,
    port: Option<u16>,
    path: &'a str,
}

impl core::fmt::Debug for Url<'_> {
    fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
        write!(f, "{}://", self.scheme.as_str())?;
        if self.is_host_ipv6 {
            write!(f, "[{}", self.host)?;
            if let Some(scope_id) = self.scope_id {
                write!(f, "%{}", scope_id)?;
            }
            write!(f, "]")?;
        } else {
            write!(f, "{}", self.host)?;
        }
        if let Some(port) = self.port {
            write!(f, ":{}", port)?
        }
        write!(f, "{}", self.path)
    }
}

#[cfg(feature = "defmt")]
impl defmt::Format for Url<'_> {
    fn format(&self, f: defmt::Formatter) {
        use defmt::write;
        write!(f, "{}://", self.scheme.as_str());
        if self.is_host_ipv6 {
            write!(f, "[{}", self.host);
            if let Some(scope_id) = self.scope_id {
                write!(f, "%{}", scope_id);
            }
            write!(f, "]");
        } else {
            write!(f, "{}", self.host);
        }
        if let Some(port) = self.port {
            write!(f, ":{}", port)
        }
        write!(f, "{}", self.path)
    }
}

#[derive(PartialEq, Eq, Clone, Copy, Debug, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "defmt", derive(defmt::Format))]
pub enum UrlScheme {
    /// HTTP scheme
    HTTP,
    /// HTTPS (HTTP + TLS) scheme
    HTTPS,
    /// MQTT scheme
    MQTT,
    /// MQTTS (MQTT + TLS) scheme
    MQTTS,
}

impl UrlScheme {
    /// str representation of the scheme
    ///
    /// The returned str is always lowercase
    pub fn as_str(&self) -> &str {
        match self {
            UrlScheme::HTTP => "http",
            UrlScheme::HTTPS => "https",
            UrlScheme::MQTT => "mqtt",
            UrlScheme::MQTTS => "mqtts",
        }
    }

    /// Get the default port for scheme
    pub const fn default_port(&self) -> u16 {
        match self {
            UrlScheme::HTTP => 80,
            UrlScheme::HTTPS => 443,
            UrlScheme::MQTT => 1883,
            UrlScheme::MQTTS => 8883,
        }
    }
}

impl<'a> Url<'a> {
    /// Parse the provided url
    ///
    /// The host may be an IP address. An IPv6 address has to be surrounded by square brackets.
    pub fn parse(url: &'a str) -> Result<Url<'a>, Error> {
        // Split out the scheme.
        let mut parts = url.split("://");
        // This can't fail, since `Split` always yields `Some` on the first iteration.
        let scheme = parts.next().unwrap();
        let host_port_path = parts.next().ok_or(Error::NoScheme)?;

        let scheme = if scheme.eq_ignore_ascii_case("http") {
            Ok(UrlScheme::HTTP)
        } else if scheme.eq_ignore_ascii_case("https") {
            Ok(UrlScheme::HTTPS)
        } else {
            Err(Error::UnsupportedScheme)
        }?;

        // Split host and path first
        let (host_port, path) = if let Some(path_delim) = host_port_path.find('/') {
            let host_port = &host_port_path[..path_delim];
            let path = &host_port_path[path_delim..];
            let path = if path.is_empty() { "/" } else { path };
            (host_port, path)
        } else {
            (host_port_path, "/")
        };

        // Now handle the host, port and scope ID.
        let (host, port, is_host_ipv6, scope_id) = if host_port.starts_with('[') {
            // If we are here, a '[' was found, indicating that the host is an IPv6 address. If
            // there is no closing ']' we return Ipv6AddressInvalid here.
            let address_block_end = host_port.find(']').ok_or(Error::Ipv6AddressInvalid)?;
            // The range in which the actual address is located.
            let mut address_range = 1..address_block_end;
            // Check if there's a scoped id and parse it if it's present. The address_range will
            // also be altered, to only contain the address.
            let scope_id = if let Some(scope_id_start) = host_port[address_range.clone()].find('%')
            {
                address_range = 1..scope_id_start + 1;
                Some(&host_port[scope_id_start + 2..address_block_end])
            } else {
                None
            };
            // Check if there's a port following the IPv6 address.
            let port = if let Some(port) = host_port
                .get(address_block_end + 1..)
                .filter(|port| !port.is_empty())
            {
                Some(
                    port.strip_prefix(':')
                        .ok_or(Error::LeftoverTokensAfterIpv6)?,
                )
            } else {
                None
            };
            (&host_port[address_range], port, true, scope_id)
        } else if let Some(port_delim) = host_port.find(':') {
            // The hostname is followed by a port, which we attempt to extract here.
            (
                &host_port[..port_delim],
                host_port.get(port_delim + 1..),
                false,
                None,
            )
        } else {
            // No port follows the hostname.
            (host_port, None, false, None)
        };
        if port == Some("") {
            return Err(Error::NoPortAfterColon);
        }
        if scope_id == Some("") {
            return Err(Error::NoScopeIdAfterPercent);
        }
        let port = port
            .map(|port| port.parse::<u16>())
            .transpose()
            .map_err(|_| Error::InvalidPort)?;
        let scope_id = scope_id
            .map(|scope_id| scope_id.parse::<u32>())
            .transpose()
            .map_err(|_| Error::InvalidScopeId)?;

        Ok(Self {
            scheme,
            host,
            scope_id,
            is_host_ipv6,
            path,
            port,
        })
    }

    /// Get the url scheme
    pub fn scheme(&self) -> UrlScheme {
        self.scheme
    }

    /// Get the url host
    pub fn host(&self) -> &'a str {
        self.host
    }

    /// Attempt to get the url host as an IP address
    ///
    /// This will only work, if the url host was actually specified as an IP address.
    pub fn host_ip(&self) -> Option<IpAddr> {
        if self.is_host_ipv6 {
            Ipv6Addr::from_str(self.host).ok().map(|ip| ip.into())
        } else {
            Ipv4Addr::from_str(self.host).ok().map(|ip| ip.into())
        }
    }

    /// Attempt to get the url host socket address
    ///
    /// This will only work, if the url host was an IP address
    pub fn host_socket_address(&self) -> Option<SocketAddr> {
        Some(match self.host_ip()? {
            IpAddr::V4(address) => {
                SocketAddr::V4(SocketAddrV4::new(address, self.port_or_default()))
            }
            IpAddr::V6(address) => SocketAddr::V6(SocketAddrV6::new(
                address,
                self.port_or_default(),
                0,
                self.scope_id_or_default(),
            )),
        })
    }

    /// Get the url port if specified
    pub fn port(&self) -> Option<u16> {
        self.port
    }

    /// Get the url port or the default port for the scheme
    pub fn port_or_default(&self) -> u16 {
        self.port.unwrap_or_else(|| self.scheme.default_port())
    }

    /// Get the scope ID of the IPv6 address specified in the url
    pub fn scope_id(&self) -> Option<u32> {
        self.scope_id
    }

    /// Get the scope ID of the IPv6 address specified in the url or the default scope ID
    pub fn scope_id_or_default(&self) -> u32 {
        self.scope_id.unwrap_or(0)
    }

    /// Get the url path
    pub fn path(&self) -> &'a str {
        self.path
    }
}

#[cfg(test)]
mod tests {
    extern crate std;

    use super::*;

    #[test]
    fn test_parse_no_scheme() {
        assert_eq!(Error::NoScheme, Url::parse("").err().unwrap());
        assert_eq!(Error::NoScheme, Url::parse("http:/").err().unwrap());
    }

    #[test]
    fn test_parse_unsupported_scheme() {
        assert_eq!(
            Error::UnsupportedScheme,
            Url::parse("something://").err().unwrap()
        );
    }

    #[test]
    fn test_parse_no_host() {
        let url = Url::parse("http://").unwrap();
        assert_eq!(url.scheme(), UrlScheme::HTTP);
        assert_eq!(url.host(), "");
        assert_eq!(url.port_or_default(), 80);
        assert_eq!(url.path(), "/");
    }

    #[test]
    fn test_parse_minimal() {
        let url = Url::parse("http://localhost").unwrap();
        assert_eq!(url.scheme(), UrlScheme::HTTP);
        assert_eq!(url.host(), "localhost");
        assert_eq!(url.port_or_default(), 80);
        assert_eq!(url.path(), "/");

        assert_eq!("http://localhost/", std::format!("{:?}", url));
    }

    #[test]
    fn test_parse_path() {
        let url = Url::parse("http://localhost/foo/bar").unwrap();
        assert_eq!(url.scheme(), UrlScheme::HTTP);
        assert_eq!(url.host(), "localhost");
        assert_eq!(url.port_or_default(), 80);
        assert_eq!(url.path(), "/foo/bar");

        assert_eq!("http://localhost/foo/bar", std::format!("{:?}", url));
    }

    #[test]
    fn test_parse_path_with_colon() {
        let url = Url::parse("http://localhost/foo/bar:123").unwrap();
        assert_eq!(url.scheme(), UrlScheme::HTTP);
        assert_eq!(url.host(), "localhost");
        assert_eq!(url.port_or_default(), 80);
        assert_eq!(url.path(), "/foo/bar:123");

        assert_eq!("http://localhost/foo/bar:123", std::format!("{:?}", url));
    }

    #[test]
    fn test_parse_port() {
        let url = Url::parse("http://localhost:8088").unwrap();
        assert_eq!(url.scheme(), UrlScheme::HTTP);
        assert_eq!(url.host(), "localhost");
        assert_eq!(url.port().unwrap(), 8088);
        assert_eq!(url.path(), "/");

        assert_eq!("http://localhost:8088/", std::format!("{:?}", url));
    }

    #[test]
    fn test_parse_port_path() {
        let url = Url::parse("http://localhost:8088/foo/bar").unwrap();
        assert_eq!(url.scheme(), UrlScheme::HTTP);
        assert_eq!(url.host(), "localhost");
        assert_eq!(url.port().unwrap(), 8088);
        assert_eq!(url.path(), "/foo/bar");

        assert_eq!("http://localhost:8088/foo/bar", std::format!("{:?}", url));
    }

    #[test]
    fn test_parse_scheme() {
        let url = Url::parse("https://localhost/").unwrap();
        assert_eq!(url.scheme(), UrlScheme::HTTPS);
        assert_eq!(url.host(), "localhost");
        assert_eq!(url.port_or_default(), 443);
        assert_eq!(url.path(), "/");

        assert_eq!("https://localhost/", std::format!("{:?}", url));
    }
    #[test]
    fn test_parse_ipv4() {
        let url = Url::parse("https://127.0.0.1:1337/foo/bar").unwrap();
        assert_eq!(url.scheme(), UrlScheme::HTTPS);
        assert_eq!(url.host(), "127.0.0.1");
        assert_eq!(
            url.host_socket_address().unwrap(),
            SocketAddr::from_str("127.0.0.1:1337").unwrap()
        );
        assert_eq!(url.port_or_default(), 1337);
        assert_eq!(url.path(), "/foo/bar");

        assert_eq!("https://127.0.0.1:1337/foo/bar", std::format!("{:?}", url));
    }
    #[test]
    fn test_parse_ipv6() {
        let url = Url::parse("https://[fe80::%1]/foo/bar").unwrap();
        assert_eq!(url.scheme(), UrlScheme::HTTPS);
        assert_eq!(url.host(), "fe80::");
        assert_eq!(
            url.host_socket_address().unwrap(),
            SocketAddr::from_str("[fe80::%1]:443").unwrap()
        );
        assert_eq!(url.port_or_default(), 443);
        assert_eq!(url.path(), "/foo/bar");

        assert_eq!("https://[fe80::%1]/foo/bar", std::format!("{:?}", url));
    }
    #[test]
    fn test_parse_ipv6_port() {
        let url = Url::parse("https://[fe80::%1]:1337/foo/bar").unwrap();
        assert_eq!(url.scheme(), UrlScheme::HTTPS);
        assert_eq!(url.host(), "fe80::");
        assert_eq!(
            url.host_socket_address().unwrap(),
            SocketAddr::from_str("[fe80::%1]:1337").unwrap()
        );
        assert_eq!(url.port_or_default(), 1337);
        assert_eq!(url.path(), "/foo/bar");

        assert_eq!("https://[fe80::%1]:1337/foo/bar", std::format!("{:?}", url));
    }
    #[test]
    fn test_invalid_ipv6() {
        assert_eq!(
            Url::parse("http://[fe80::/"),
            Err(Error::Ipv6AddressInvalid)
        );
    }
    #[test]
    fn test_leftover_tokens_ipv6() {
        assert_eq!(
            Url::parse("http://[fe80]a/"),
            Err(Error::LeftoverTokensAfterIpv6)
        );
    }
    #[test]
    fn test_no_port_after_colon() {
        assert_eq!(
            Url::parse("http://localhost:/"),
            Err(Error::NoPortAfterColon)
        );
        assert_eq!(
            Url::parse("http://[fe80::]:/"),
            Err(Error::NoPortAfterColon)
        );
    }
    #[test]
    fn test_invalid_port() {
        assert_eq!(
            Url::parse("http://localhost:12E4/"),
            Err(Error::InvalidPort)
        );
        assert_eq!(Url::parse("http://[fe80::]:12E4/"), Err(Error::InvalidPort));
    }
}