iref 4.0.0

Uniform & Internationalized Resource Identifiers (URIs/IRIs), borrowed and owned.
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
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
use core::{
	cmp::Ordering,
	fmt::Write,
	hash::{Hash, Hasher},
	ops::Deref,
};

use pct_str::PctStr;

/// URI authority host.
#[derive(static_automata::Validate, str_newtype::StrNewType)]
#[automaton(crate::uri::grammar::Host)]
#[newtype(
	no_deref,
	ord([u8], &[u8], str, &str, pct_str::PctStr, &pct_str::PctStr)
)]
#[cfg_attr(
	feature = "std",
	newtype(ord(Vec<u8>, String, pct_str::PctString), owned(HostBuf, derive(PartialEq, Eq, PartialOrd, Ord, Hash)))
)]
#[cfg_attr(feature = "serde", newtype(serde))]
pub struct Host(str);

impl Host {
	/// Returns the host as a percent-encoded string slice.
	#[inline]
	pub fn as_pct_str(&self) -> &PctStr {
		unsafe { PctStr::new_unchecked(self.as_str()) }
	}

	/// Returns `true` if this host is an IP-literal (IPv6 address or
	/// IPvFuture).
	///
	/// IP-literals are enclosed in brackets (`[...]`) as defined in
	/// RFC 3986.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::Host;
	///
	/// assert!(Host::new("[::1]").unwrap().is_ip_literal());
	/// assert!(!Host::new("example.org").unwrap().is_ip_literal());
	/// ```
	pub fn is_ip_literal(&self) -> bool {
		self.as_bytes().first() == Some(&b'[')
	}

	/// Returns `true` if this host is an IPv4 address.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::Host;
	///
	/// assert!(Host::new("127.0.0.1").unwrap().is_ipv4());
	/// assert!(!Host::new("[::1]").unwrap().is_ipv4());
	/// assert!(!Host::new("example.org").unwrap().is_ipv4());
	/// ```
	pub fn is_ipv4(&self) -> bool {
		let bytes = self.as_bytes();

		let Some(i) = parse_dec_octet(bytes, 0) else {
			return false;
		};
		if bytes.get(i) != Some(&b'.') {
			return false;
		}

		let Some(j) = parse_dec_octet(bytes, i + 1) else {
			return false;
		};
		if bytes.get(j) != Some(&b'.') {
			return false;
		}

		let Some(k) = parse_dec_octet(bytes, j + 1) else {
			return false;
		};
		if bytes.get(k) != Some(&b'.') {
			return false;
		}

		let Some(l) = parse_dec_octet(bytes, k + 1) else {
			return false;
		};
		l == bytes.len()
	}

	/// Returns `true` if this host is an IPv6 address.
	///
	/// IPv6 addresses are enclosed in brackets (`[...]`) and do not start
	/// with `[v` (which denotes IPvFuture).
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::Host;
	///
	/// assert!(Host::new("[::1]").unwrap().is_ipv6());
	/// assert!(Host::new("[2001:db8::1]").unwrap().is_ipv6());
	/// assert!(!Host::new("127.0.0.1").unwrap().is_ipv6());
	/// assert!(!Host::new("example.org").unwrap().is_ipv6());
	/// ```
	pub fn is_ipv6(&self) -> bool {
		let bytes = self.as_bytes();
		bytes.len() >= 4 && bytes[0] == b'[' && bytes[1] != b'v'
	}

	/// Parses this host as an IPv4 address and returns it as a `u32`.
	///
	/// Returns `None` if the host is not a valid IPv4 address.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::Host;
	///
	/// assert_eq!(Host::new("127.0.0.1").unwrap().to_ipv4(), Some(0x7f000001));
	/// assert_eq!(Host::new("0.0.0.0").unwrap().to_ipv4(), Some(0));
	/// assert_eq!(Host::new("[::1]").unwrap().to_ipv4(), None);
	/// ```
	pub fn to_ipv4(&self) -> Option<u32> {
		if !self.is_ipv4() {
			return None;
		}

		Some(parse_ipv4(self.as_str()))
	}

	/// Parses this host as an IPv6 address and returns it as a `u128`.
	///
	/// Returns `None` if the host is not an IPv6 address.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::Host;
	///
	/// assert_eq!(Host::new("[::1]").unwrap().to_ipv6(), Some(1));
	/// assert_eq!(
	///     Host::new("[2001:db8::1]").unwrap().to_ipv6(),
	///     Some(0x20010db8_00000000_00000000_00000001)
	/// );
	/// assert_eq!(Host::new("[::0]").unwrap().to_ipv6(), Some(0));
	/// assert_eq!(Host::new("127.0.0.1").unwrap().to_ipv6(), None);
	/// ```
	pub fn to_ipv6(&self) -> Option<u128> {
		if !self.is_ipv6() {
			return None;
		}

		let inner = &self.as_str()[1..self.as_str().len() - 1];

		let (left, right) = match inner.split_once("::") {
			Some((l, r)) => (l, Some(r)),
			None => (inner, None),
		};

		let mut result: u128 = 0;
		let mut count: u32 = 0;

		if !left.is_empty() {
			for g in left.split(':') {
				if g.contains('.') {
					let ipv4 = parse_ipv4(g);
					result = result << 32 | ipv4 as u128;
					count += 2;
				} else {
					result = result << 16 | u16::from_str_radix(g, 16).unwrap() as u128;
					count += 1;
				}
			}
		}

		if let Some(right) = right {
			let mut right_result: u128 = 0;

			if !right.is_empty() {
				for g in right.split(':') {
					if g.contains('.') {
						// Embedded IPv4 suffix, e.g. `192.168.1.1`.
						let ipv4 = parse_ipv4(g);
						right_result = right_result << 32 | ipv4 as u128;
					} else {
						right_result =
							right_result << 16 | u16::from_str_radix(g, 16).unwrap() as u128;
					}
				}
			}

			result = result.checked_shl((8 - count) * 16).unwrap_or(0) | right_result;
		}

		Some(result)
	}
}

/// Parses a `dec-octet` (RFC 3986) starting at position `i` in `bytes`.
///
/// ```text
/// dec-octet = DIGIT               ; 0-9
///           / %x31-39 DIGIT       ; 10-99
///           / "1" 2DIGIT          ; 100-199
///           / "2" %x30-34 DIGIT   ; 200-249
///           / "25" %x30-35        ; 250-255
/// ```
///
/// Returns `Some(end)` where `end` is the index past the last byte of the
/// octet, or `None` if no valid dec-octet starts at `i`.
fn parse_dec_octet(bytes: &[u8], i: usize) -> Option<usize> {
	let d0 = *bytes.get(i)?;
	if !d0.is_ascii_digit() {
		return None;
	}

	if d0 == b'0' {
		return Some(i + 1);
	}

	// d0 is 1-9
	let Some(&d1) = bytes.get(i + 1) else {
		return Some(i + 1);
	};
	if !d1.is_ascii_digit() {
		return Some(i + 1);
	}

	// d0 is 1-9, d1 is 0-9
	let Some(&d2) = bytes.get(i + 2) else {
		return Some(i + 2);
	};
	if !d2.is_ascii_digit() {
		return Some(i + 2);
	}

	// d0 d1 d2, all digits. Valid only if <= 255.
	if d0 == b'1' || (d0 == b'2' && (d1 <= b'4' || (d1 == b'5' && d2 <= b'5'))) {
		Some(i + 3)
	} else {
		None
	}
}

/// Parses an IPv4 address string into a `u32`.
///
/// The input must be exactly a valid IPv4 address (4 dec-octets separated
/// by dots, with nothing extra).
fn parse_ipv4(s: &str) -> u32 {
	let bytes = s.as_bytes();
	let mut result: u32 = 0;

	let i = parse_dec_octet(bytes, 0).unwrap();
	result |= (bytes[0..i]
		.iter()
		.fold(0u32, |a, &b| a * 10 + (b - b'0') as u32))
		<< 24;

	let j = parse_dec_octet(bytes, i + 1).unwrap();
	result |= (bytes[i + 1..j]
		.iter()
		.fold(0u32, |a, &b| a * 10 + (b - b'0') as u32))
		<< 16;

	let k = parse_dec_octet(bytes, j + 1).unwrap();
	result |= (bytes[j + 1..k]
		.iter()
		.fold(0u32, |a, &b| a * 10 + (b - b'0') as u32))
		<< 8;

	let l = parse_dec_octet(bytes, k + 1).unwrap();
	result |= bytes[k + 1..l]
		.iter()
		.fold(0u32, |a, &b| a * 10 + (b - b'0') as u32);

	result
}

impl Deref for Host {
	type Target = PctStr;

	fn deref(&self) -> &Self::Target {
		self.as_pct_str()
	}
}

impl PartialEq for Host {
	#[inline]
	fn eq(&self, other: &Host) -> bool {
		self.as_pct_str() == other.as_pct_str()
	}
}

impl Eq for Host {}

impl PartialOrd for Host {
	#[inline]
	fn partial_cmp(&self, other: &Host) -> Option<Ordering> {
		Some(self.cmp(other))
	}
}

impl Ord for Host {
	#[inline]
	fn cmp(&self, other: &Host) -> Ordering {
		self.as_pct_str().cmp(other.as_pct_str())
	}
}

impl Hash for Host {
	#[inline]
	fn hash<H: Hasher>(&self, hasher: &mut H) {
		self.as_pct_str().hash(hasher)
	}
}

#[cfg(feature = "std")]
impl HostBuf {
	pub fn into_pct_string(self) -> pct_str::PctString {
		unsafe { pct_str::PctString::new_unchecked(self.0) }
	}

	/// Creates a [`HostBuf`] from an IPv4 address represented as a `u32`.
	///
	/// The octets are extracted from the most significant byte first
	/// (e.g., `0x7f000001` becomes `"127.0.0.1"`).
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::HostBuf;
	///
	/// assert_eq!(HostBuf::from_ipv4(0x7f000001).as_str(), "127.0.0.1");
	/// assert_eq!(HostBuf::from_ipv4(0).as_str(), "0.0.0.0");
	/// ```
	pub fn from_ipv4(addr: u32) -> Self {
		let s = format!(
			"{}.{}.{}.{}",
			(addr >> 24) & 0xff,
			(addr >> 16) & 0xff,
			(addr >> 8) & 0xff,
			addr & 0xff
		);
		unsafe { Self::new_unchecked(s) }
	}

	/// Creates a [`HostBuf`] from an IPv6 address represented as a `u128`.
	///
	/// The address is formatted with `::` compression for the longest run
	/// of consecutive zero groups, enclosed in brackets as required by
	/// RFC 3986.
	///
	/// # Example
	///
	/// ```rust
	/// use iref::uri::HostBuf;
	///
	/// assert_eq!(HostBuf::from_ipv6(1).as_str(), "[::1]");
	/// assert_eq!(HostBuf::from_ipv6(0).as_str(), "[::]");
	/// ```
	pub fn from_ipv6(addr: u128) -> Self {
		let s = format!("[{}]", format_ipv6(addr));
		unsafe { Self::new_unchecked(s) }
	}
}

/// Formats an IPv6 address as a string with `::` compression for the
/// longest run of consecutive zero groups.
#[cfg(feature = "std")]
fn format_ipv6(addr: u128) -> String {
	let groups: [u16; 8] = core::array::from_fn(|i| (addr >> (112 - i * 16)) as u16);

	// Find the longest run of consecutive zero groups.
	let mut best_start = 0;
	let mut best_len = 0;
	let mut cur_start = 0;
	let mut cur_len = 0;
	for (i, &g) in groups.iter().enumerate() {
		if g == 0 {
			if cur_len == 0 {
				cur_start = i;
			}
			cur_len += 1;
			if cur_len > best_len {
				best_start = cur_start;
				best_len = cur_len;
			}
		} else {
			cur_len = 0;
		}
	}

	let mut s = String::new();

	let write_groups = |s: &mut String, groups: &[u16]| {
		for (i, g) in groups.iter().enumerate() {
			if i > 0 {
				s.push(':');
			}
			write!(s, "{:x}", g).unwrap();
		}
	};

	if best_len >= 2 {
		write_groups(&mut s, &groups[..best_start]);
		s.push_str("::");
		write_groups(&mut s, &groups[best_start + best_len..]);
	} else {
		write_groups(&mut s, &groups);
	}

	s
}

/// Parses a URI authority [`Host`] at compile time.
#[macro_export]
macro_rules! host {
	($value:literal) => {
		match $crate::uri::Host::from_str($value) {
			Ok(value) => value,
			Err(_) => panic!("invalid URI authority host"),
		}
	};
}

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

	#[test]
	fn is_ipv4_valid() {
		for input in [
			"0.0.0.0",
			"255.255.255.255",
			"127.0.0.1",
			"1.2.3.4",
			"249.249.249.249",
		] {
			assert!(
				Host::new(input).unwrap().is_ipv4(),
				"is_ipv4({input}) should be true"
			);
		}
	}

	#[test]
	fn is_ipv4_invalid() {
		for input in [
			"example.org",
			"[::1]",
			"1.2.3",
			"1.2.3.4.5",
			"999.0.0.1",
			"256.0.0.1",
		] {
			assert!(
				!Host::new(input).unwrap().is_ipv4(),
				"is_ipv4({input}) should be false"
			);
		}
	}

	#[test]
	fn to_ipv4() {
		let vectors: [(&str, Option<u32>); _] = [
			("0.0.0.0", Some(0)),
			("255.255.255.255", Some(0xFFFFFFFF)),
			("127.0.0.1", Some(0x7F000001)),
			("192.168.1.1", Some(0xC0A80101)),
			("10.0.0.1", Some(0x0A000001)),
			("1.2.3.4", Some(0x01020304)),
			// Not IPv4
			("[::1]", None),
			("example.org", None),
		];

		for (input, expected) in vectors {
			let host = Host::new(input).unwrap();
			assert_eq!(host.to_ipv4(), expected, "to_ipv4({input})");
		}
	}

	#[test]
	fn to_ipv6() {
		let vectors: [(&str, Option<u128>); _] = [
			// All zeros
			("[::]", Some(0)),
			// All ones
			("[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]", Some(u128::MAX)),
			// Loopback
			("[::1]", Some(1)),
			// Full address, no compression
			(
				"[2001:0db8:85a3:0000:0000:8a2e:0370:7334]",
				Some(0x20010db885a3000000008a2e03707334),
			),
			// Compression in the middle
			("[2001:db8::1]", Some(0x20010db8_00000000_00000000_00000001)),
			// Right-only expansion
			("[1:2:3::]", Some(0x00010002000300000000000000000000)),
			// Left-only expansion
			("[::1:2:3]", Some(0x00000000000000000000000100020003)),
			// Single group
			("[::ffff]", Some(0xffff)),
			// Embedded IPv4 suffix with ::
			("[::ffff:192.168.1.1]", Some(0x0000ffff_c0a80101)),
			// Embedded IPv4 suffix without ::
			("[0:0:0:0:0:ffff:192.168.1.1]", Some(0x0000ffff_c0a80101)),
			// Embedded IPv4 loopback
			("[::127.0.0.1]", Some(0x7f000001)),
			// Not IPv6
			("127.0.0.1", None),
			("example.org", None),
		];

		for (input, expected) in vectors {
			let host = Host::new(input).unwrap();
			assert_eq!(host.to_ipv6(), expected, "to_ipv6({input})");
		}
	}

	#[test]
	fn from_ipv4_round_trip() {
		let vectors: [(u32, &str); _] = [
			(0, "0.0.0.0"),
			(0xFFFFFFFF, "255.255.255.255"),
			(0x7F000001, "127.0.0.1"),
			(0xC0A80101, "192.168.1.1"),
			(0x0A000001, "10.0.0.1"),
		];

		for (addr, expected_str) in vectors {
			let host = HostBuf::from_ipv4(addr);
			assert_eq!(host.as_str(), expected_str, "from_ipv4(0x{addr:08x})");
			assert!(host.is_ipv4());
			assert_eq!(host.to_ipv4(), Some(addr));
		}
	}

	#[test]
	fn from_ipv6_round_trip() {
		let vectors: [(u128, &str); _] = [
			(0, "[::]"),
			(1, "[::1]"),
			(u128::MAX, "[ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff]"),
			(0x20010db8_00000000_00000000_00000001, "[2001:db8::1]"),
			// No compression for a single zero group
			(0x00010000000300040005000600070008, "[1:0:3:4:5:6:7:8]"),
			// Compression picks the longest run
			(0x00010002000000000000000000070008, "[1:2::7:8]"),
			// Compression picks the first longest run on tie
			(0x00010000000000040005000000000008, "[1::4:5:0:0:8]"),
		];

		for (addr, expected_str) in vectors {
			let host = HostBuf::from_ipv6(addr);
			assert_eq!(host.as_str(), expected_str, "from_ipv6(0x{addr:032x})");
			assert!(host.is_ipv6());
			assert_eq!(host.to_ipv6(), Some(addr));
		}
	}
}