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
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
use core::{
fmt,
net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr},
};
use crate::std::{self as std, borrow::Cow, string::String, vec::Vec};
use super::{Domain, DomainAddress, Host, OptPort, SocketAddress, parse_utils};
use crate::Protocol;
use crate::address::HostWithPort;
use rama_core::error::BoxErrorExt as _;
use rama_core::error::{BoxError, ErrorContext};
use rama_utils::macros::generate_set_and_with;
/// A [`Host`] with optionally a port.
///
/// ## Examples
///
/// - `example.com`
/// - `127.0.0.1`
/// - `::`
/// - `example.com:80`
/// - `127.0.0.1:80`
/// - `[::]:80`
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct HostWithOptPort {
pub host: Host,
pub port: OptPort,
}
impl HostWithOptPort {
/// Creates a new [`HostWithOptPort`] from a [`Host`].
#[must_use]
#[inline(always)]
pub const fn new(host: Host) -> Self {
Self {
host,
port: OptPort::Unset,
}
}
/// Creates a new [`HostWithOptPort`] from a [`Host`] and port.
#[must_use]
#[inline(always)]
pub const fn new_with_port(host: Host, port: u16) -> Self {
Self {
host,
port: OptPort::Set(port),
}
}
/// Relaxed view of the port — `Set(n) → Some(n)`, everything else
/// `None`. Use when the `Unset` vs `Empty` distinction doesn't matter.
#[must_use]
#[inline]
pub const fn port_u16(&self) -> Option<u16> {
self.port.as_u16()
}
/// Resolve into a [`HostWithPort`], falling back to `default_port` when no
/// explicit port is set.
#[must_use]
pub fn into_host_with_port_or(self, default_port: u16) -> HostWithPort {
let port = self.port.as_u16().unwrap_or(default_port);
HostWithPort {
host: self.host,
port,
}
}
/// Resolve into a [`HostWithPort`] when a port is known — the explicit port
/// if set, otherwise `fallback`. `None` if neither yields a port.
#[must_use]
pub fn into_host_with_port(self, fallback: Option<u16>) -> Option<HostWithPort> {
let port = self.port.as_u16().or(fallback)?;
Some(HostWithPort {
host: self.host,
port,
})
}
/// Whether this authority's explicit port equals the default port of
/// `protocol`. Used to decide whether a port needs to be rendered.
#[must_use]
pub fn has_default_port_for(&self, protocol: Option<&Protocol>) -> bool {
protocol.and_then(Protocol::default_port) == self.port.as_u16()
}
/// Drop the port when it is `protocol`'s default, so rendering yields a bare
/// host (e.g. `example.com` instead of `example.com:443` for HTTPS).
#[must_use]
pub fn without_default_port_for(self, protocol: Option<&Protocol>) -> Self {
if self.has_default_port_for(protocol) {
Self::new(self.host)
} else {
self
}
}
/// creates a new local ipv4 [`HostWithOptPort`] without a port.
///
/// # Example
///
/// ```
/// use rama_net::address::HostWithOptPort;
///
/// let addr = HostWithOptPort::local_ipv4();
/// assert_eq!("127.0.0.1", addr.to_string());
/// ```
#[must_use]
#[inline(always)]
pub const fn local_ipv4() -> Self {
Self::new(Host::LOCALHOST_IPV4)
}
/// creates a new local ipv4 [`HostWithOptPort`] with the given port
///
/// # Example
///
/// ```
/// use rama_net::address::HostWithOptPort;
///
/// let addr = HostWithOptPort::local_ipv4_with_port(8080);
/// assert_eq!("127.0.0.1:8080", addr.to_string());
/// ```
#[must_use]
#[inline(always)]
pub const fn local_ipv4_with_port(port: u16) -> Self {
Self::new_with_port(Host::LOCALHOST_IPV4, port)
}
/// creates a new local ipv6 [`HostWithOptPort`] without a port.
///
/// IPv6 addresses always render with `[…]` brackets even with no
/// port — see the type's `Display` impl for the rationale.
///
/// # Example
///
/// ```
/// use rama_net::address::HostWithOptPort;
///
/// let addr = HostWithOptPort::local_ipv6();
/// assert_eq!("[::1]", addr.to_string());
/// ```
#[must_use]
#[inline(always)]
pub const fn local_ipv6() -> Self {
Self::new(Host::LOCALHOST_IPV6)
}
/// creates a new local ipv6 [`HostWithOptPort`] with the given port.
///
/// # Example
///
/// ```
/// use rama_net::address::HostWithOptPort;
///
/// let addr = HostWithOptPort::local_ipv6_with_port(8080);
/// assert_eq!("[::1]:8080", addr.to_string());
/// ```
#[must_use]
#[inline(always)]
pub const fn local_ipv6_with_port(port: u16) -> Self {
Self::new_with_port(Host::LOCALHOST_IPV6, port)
}
/// creates a default ipv4 [`HostWithOptPort`] without a port
///
/// # Example
///
/// ```
/// use rama_net::address::HostWithOptPort;
///
/// let addr = HostWithOptPort::default_ipv4_with_port(8080);
/// assert_eq!("0.0.0.0:8080", addr.to_string());
/// ```
#[must_use]
#[inline(always)]
pub const fn default_ipv4() -> Self {
Self::new(Host::DEFAULT_IPV4)
}
/// creates a default ipv4 [`HostWithOptPort`] with the given port
///
/// # Example
///
/// ```
/// use rama_net::address::HostWithOptPort;
///
/// let addr = HostWithOptPort::default_ipv4_with_port(8080);
/// assert_eq!("0.0.0.0:8080", addr.to_string());
/// ```
#[must_use]
#[inline(always)]
pub const fn default_ipv4_with_port(port: u16) -> Self {
Self::new_with_port(Host::DEFAULT_IPV4, port)
}
/// creates a new default ipv6 [`HostWithOptPort`] without a port.
///
/// IPv6 addresses always render with `[…]` brackets — see the
/// type's `Display` impl for the rationale.
///
/// # Example
///
/// ```
/// use rama_net::address::HostWithOptPort;
///
/// let addr = HostWithOptPort::default_ipv6();
/// assert_eq!("[::]", addr.to_string());
/// ```
#[must_use]
#[inline(always)]
pub const fn default_ipv6() -> Self {
Self::new(Host::DEFAULT_IPV6)
}
/// creates a new default ipv6 [`HostWithOptPort`] with the given port.
///
/// # Example
///
/// ```
/// use rama_net::address::HostWithOptPort;
///
/// let addr = HostWithOptPort::default_ipv6_with_port(8080);
/// assert_eq!("[::]:8080", addr.to_string());
/// ```
#[must_use]
#[inline(always)]
pub const fn default_ipv6_with_port(port: u16) -> Self {
Self::new_with_port(Host::DEFAULT_IPV6, port)
}
/// creates a new broadcast ipv4 [`HostWithOptPort`] without a port
///
/// # Example
///
/// ```
/// use rama_net::address::HostWithOptPort;
///
/// let addr = HostWithOptPort::broadcast_ipv4();
/// assert_eq!("255.255.255.255", addr.to_string());
/// ```
#[must_use]
#[inline(always)]
pub const fn broadcast_ipv4() -> Self {
Self::new(Host::BROADCAST_IPV4)
}
/// creates a new broadcast ipv4 [`HostWithOptPort`] with the given port
///
/// # Example
///
/// ```
/// use rama_net::address::HostWithOptPort;
///
/// let addr = HostWithOptPort::broadcast_ipv4_with_port(8080);
/// assert_eq!("255.255.255.255:8080", addr.to_string());
/// ```
#[must_use]
#[inline(always)]
pub const fn broadcast_ipv4_with_port(port: u16) -> Self {
Self::new_with_port(Host::BROADCAST_IPV4, port)
}
/// Creates a new example domain [`HostWithOptPort`] without a port.
#[must_use]
#[inline(always)]
pub const fn example_domain() -> Self {
Self {
host: Host::EXAMPLE_NAME,
port: OptPort::Unset,
}
}
/// Creates a new example domain [`HostWithOptPort`] for the `http` default port.
#[must_use]
#[inline(always)]
pub const fn example_domain_http() -> Self {
Self::example_domain_with_port(Protocol::HTTP_DEFAULT_PORT)
}
/// Creates a new example domain [`HostWithOptPort`] for the `https` default port.
#[must_use]
#[inline(always)]
pub const fn example_domain_https() -> Self {
Self::example_domain_with_port(Protocol::HTTPS_DEFAULT_PORT)
}
/// Creates a new example domain [`HostWithOptPort`] for the given port.
#[must_use]
#[inline(always)]
pub const fn example_domain_with_port(port: u16) -> Self {
Self {
host: Host::EXAMPLE_NAME,
port: OptPort::Set(port),
}
}
/// Creates a new localhost domain [`HostWithOptPort`] without a port.
#[must_use]
#[inline(always)]
pub const fn localhost_domain() -> Self {
Self {
host: Host::LOCALHOST_NAME,
port: OptPort::Unset,
}
}
/// Creates a new localhost domain [`HostWithOptPort`] for the `http` default port.
#[must_use]
#[inline(always)]
pub const fn localhost_domain_http() -> Self {
Self::localhost_domain_with_port(Protocol::HTTP_DEFAULT_PORT)
}
/// Creates a new localhost domain [`HostWithOptPort`] for the `https` default port.
#[must_use]
#[inline(always)]
pub const fn localhost_domain_https() -> Self {
Self::localhost_domain_with_port(Protocol::HTTPS_DEFAULT_PORT)
}
/// Creates a new localhost domain [`HostWithOptPort`] for the given port.
#[must_use]
#[inline(always)]
pub const fn localhost_domain_with_port(port: u16) -> Self {
Self {
host: Host::LOCALHOST_NAME,
port: OptPort::Set(port),
}
}
generate_set_and_with! {
/// Set [`Host`] of [`HostWithOptPort`]. Accepts any [`Into<Host>`].
pub fn host(mut self, host: impl Into<Host>) -> Self {
self.host = host.into();
self
}
}
generate_set_and_with! {
/// Set the port. Accepts `u16`, `OptPort`, or `Option<u16>` via
/// [`Into<OptPort>`]. Pass `OptPort::Unset` to clear.
pub fn port(mut self, port: impl Into<OptPort>) -> Self {
self.port = port.into();
self
}
}
}
impl From<(Domain, u16)> for HostWithOptPort {
#[inline(always)]
fn from((domain, port): (Domain, u16)) -> Self {
(Host::Name(domain), port).into()
}
}
impl From<(IpAddr, u16)> for HostWithOptPort {
#[inline(always)]
fn from((ip, port): (IpAddr, u16)) -> Self {
(Host::Address(ip), port).into()
}
}
impl From<(Ipv4Addr, u16)> for HostWithOptPort {
#[inline(always)]
fn from((ip, port): (Ipv4Addr, u16)) -> Self {
(Host::Address(IpAddr::V4(ip)), port).into()
}
}
impl From<([u8; 4], u16)> for HostWithOptPort {
#[inline(always)]
fn from((ip, port): ([u8; 4], u16)) -> Self {
(Host::Address(IpAddr::V4(ip.into())), port).into()
}
}
impl From<(Ipv6Addr, u16)> for HostWithOptPort {
#[inline(always)]
fn from((ip, port): (Ipv6Addr, u16)) -> Self {
(Host::Address(IpAddr::V6(ip)), port).into()
}
}
impl From<([u8; 16], u16)> for HostWithOptPort {
#[inline(always)]
fn from((ip, port): ([u8; 16], u16)) -> Self {
(Host::Address(IpAddr::V6(ip.into())), port).into()
}
}
impl From<Host> for HostWithOptPort {
#[inline(always)]
fn from(host: Host) -> Self {
Self::new(host)
}
}
impl From<(Host, u16)> for HostWithOptPort {
#[inline(always)]
fn from((host, port): (Host, u16)) -> Self {
Self::new_with_port(host, port)
}
}
impl From<HostWithOptPort> for Host {
#[inline(always)]
fn from(hwop: HostWithOptPort) -> Self {
hwop.host
}
}
impl From<SocketAddr> for HostWithOptPort {
#[inline(always)]
fn from(addr: SocketAddr) -> Self {
Self::new_with_port(Host::Address(addr.ip()), addr.port())
}
}
impl From<&SocketAddr> for HostWithOptPort {
#[inline(always)]
fn from(addr: &SocketAddr) -> Self {
Self::new_with_port(Host::Address(addr.ip()), addr.port())
}
}
impl From<HostWithPort> for HostWithOptPort {
#[inline(always)]
fn from(addr: HostWithPort) -> Self {
let HostWithPort { host, port } = addr;
Self::new_with_port(host, port)
}
}
impl From<SocketAddress> for HostWithOptPort {
#[inline(always)]
fn from(addr: SocketAddress) -> Self {
let SocketAddress { ip_addr, port } = addr;
Self::new_with_port(Host::Address(ip_addr), port)
}
}
impl From<&SocketAddress> for HostWithOptPort {
#[inline(always)]
fn from(addr: &SocketAddress) -> Self {
Self::new_with_port(Host::Address(addr.ip_addr), addr.port)
}
}
impl From<DomainAddress> for HostWithOptPort {
#[inline(always)]
fn from(addr: DomainAddress) -> Self {
let DomainAddress { domain, port } = addr;
Self::from((domain, port))
}
}
impl fmt::Display for HostWithOptPort {
/// Renders `host[:port]` with IPv6 addresses **always** bracketed
/// (`[ip]`), regardless of whether a port follows.
///
/// Without the brackets, IPv6 + port is ambiguous: `::1:8080`
/// could parse as the IPv6 address `::1` with port `8080`, or as
/// the IPv6 address `::1:8080` with no port. RFC 3986 §3.2.2
/// resolves this with the `IP-literal = "[" IPv6address "]"`
/// rule; we apply it consistently across all `Display` contexts
/// (URI authority and standalone address spec alike) so callers
/// never accidentally emit ambiguous bytes.
///
/// `UninterpretedHost`'s own `Display` already brackets IP-literal
/// forms and renders reg-name bytes verbatim.
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match &self.host {
Host::Address(IpAddr::V6(ip)) => write!(f, "[{ip}]")?,
other => other.fmt(f)?,
}
// `OptPort::Display` handles all three variants — Unset emits
// nothing, Empty emits bare `:`, Set(n) emits `:n`.
self.port.fmt(f)
}
}
impl core::str::FromStr for HostWithOptPort {
type Err = BoxError;
fn from_str(s: &str) -> Result<Self, Self::Err> {
Self::try_from(s)
}
}
impl TryFrom<String> for HostWithOptPort {
type Error = BoxError;
#[inline(always)]
fn try_from(s: String) -> Result<Self, Self::Error> {
try_from_maybe_borrowed_str(s.into())
}
}
impl TryFrom<&str> for HostWithOptPort {
type Error = BoxError;
#[inline(always)]
fn try_from(s: &str) -> Result<Self, Self::Error> {
try_from_maybe_borrowed_str(s.into())
}
}
/// Reg-name fallback for inputs `Domain::try_from` rejects but the
/// URI reg-name grammar accepts. Shares byte-set validation with
/// the URI parser without constructing a `Uri`.
fn try_as_uninterpreted_host(host_str: &str) -> Result<Host, BoxError> {
let host = super::UninterpretedHost::try_from_reg_name_str(host_str)
.context("parse host as reg-name")?;
Ok(Host::Uninterpreted(host))
}
fn try_from_maybe_borrowed_str(maybe_borrowed: Cow<'_, str>) -> Result<HostWithOptPort, BoxError> {
let s = maybe_borrowed.as_ref();
if s.is_empty() {
return Err(BoxError::from_static_str(
"empty string is invalid host (with opt port)",
));
}
let host;
let mut port = OptPort::Unset;
// Standalone bracketed IP-literal (no trailing port): `[::1]` or
// `[v1.fe80::a]`. Without this fast-path the colon-split below
// treats the final `:` inside the address as a port separator.
if s.starts_with('[') && s.ends_with(']') {
let inside = &s[1..s.len() - 1];
if inside.is_empty() {
return Err(BoxError::from_static_str("empty bracketed IP-literal"));
}
// IPvFuture: `[v1.xxx]` — stored as `Uninterpreted(bracketed=true)`
// verbatim, matching the URI authority parser's shape.
if matches!(inside.as_bytes().first(), Some(b'v' | b'V')) {
crate::uri::parser::authority::validate_ipvfuture(inside.as_bytes())
.map_err(BoxError::from)
.context("parse bracketed IPvFuture")?;
return Ok(HostWithOptPort {
host: Host::Uninterpreted(super::UninterpretedHost::from_validated_bytes(
rama_core::bytes::Bytes::copy_from_slice(inside.as_bytes()),
true,
)),
port: OptPort::Unset,
});
}
if parse_utils::ipv6_bracket_has_zone(inside.as_bytes()) {
return Err(BoxError::from_static_str(
"ipv6 zone identifiers (RFC 6874) are not supported",
));
}
let addr = inside
.parse::<Ipv6Addr>()
.context("parse bracketed ipv6 host without port")?;
return Ok(HostWithOptPort {
host: Host::Address(IpAddr::V6(addr)),
port: OptPort::Unset,
});
}
if let Some(last_colon) = s.as_bytes().iter().rposition(|c| *c == b':') {
let first_part = &s[..last_colon];
if first_part.contains(':') {
// ipv6 (bare or bracketed, possibly with trailing port)
let (addr, parsed_port) = parse_utils::parse_bracketed_ipv6_with_port(s, last_colon)
.context("host-with-opt-port: parse ipv6 host")?;
host = Host::Address(IpAddr::V6(addr));
port = parsed_port;
} else {
// Reject `:port` (empty host before colon). The URI authority
// parser rejects the same shape — keep the eager paths
// symmetric.
if first_part.is_empty() {
return Err(BoxError::from_static_str(
"empty host before ':port' is invalid",
));
}
let port_str = &s[last_colon + 1..];
port = if port_str.is_empty() {
OptPort::Empty
} else {
OptPort::Set(
port_str
.parse()
.context("parse host-with-opt-port's port string as u16")?,
)
};
// try ipv4 first, domain afterwards, then Uninterpreted via URI parser
host = if let Ok(ipv4) = first_part.parse::<Ipv4Addr>() {
Host::Address(IpAddr::V4(ipv4))
} else {
let mut owned_vec = maybe_borrowed.into_owned().into_bytes();
owned_vec.truncate(last_colon);
let owned_str = String::from_utf8(owned_vec)
.context("interpret host-with-opt-port's host as utf-8 str")?;
match Domain::try_from(owned_str.as_str()) {
Ok(domain) => Host::Name(domain),
Err(_) => try_as_uninterpreted_host(&owned_str)?,
}
};
};
} else {
// no port, so either IpAddr, Domain, or Uninterpreted fallback
host = if let Ok(ip) = s.parse::<IpAddr>() {
Host::Address(ip)
} else {
let owned_str = maybe_borrowed.into_owned();
match Domain::try_from(owned_str.as_str()) {
Ok(domain) => Host::Name(domain),
Err(_) => try_as_uninterpreted_host(&owned_str)?,
}
};
}
Ok(HostWithOptPort { host, port })
}
impl TryFrom<Vec<u8>> for HostWithOptPort {
type Error = BoxError;
fn try_from(bytes: Vec<u8>) -> Result<Self, Self::Error> {
let s = String::from_utf8(bytes).context("parse host-with-opt-port from bytes")?;
s.try_into()
}
}
impl TryFrom<&[u8]> for HostWithOptPort {
type Error = BoxError;
fn try_from(bytes: &[u8]) -> Result<Self, Self::Error> {
let s = core::str::from_utf8(bytes).context("parse host-with-opt-port from bytes")?;
s.try_into()
}
}
use rama_utils::macros::serde_str::impl_serde_str;
impl_serde_str!(display HostWithOptPort);
#[cfg(test)]
mod tests {
use super::*;
#[expect(clippy::needless_pass_by_value)]
fn assert_eq(s: &str, hwop: HostWithOptPort, host: &str, port: OptPort) {
assert_eq!(hwop.host, host, "parsing: {s}");
assert_eq!(hwop.port, port, "parsing: {s}");
}
#[test]
fn test_parse_valid() {
for (s, (expected_host, expected_port)) in [
("example.com", ("example.com", OptPort::Unset)),
("example.com:80", ("example.com", OptPort::Set(80))),
("example.com:", ("example.com", OptPort::Empty)),
("::1", ("::1", OptPort::Unset)),
// Standalone bracketed IPv6 — typed Address, NOT Uninterpreted.
("[::1]", ("::1", OptPort::Unset)),
("[2001:db8::1]", ("2001:db8::1", OptPort::Unset)),
("[::1]:80", ("::1", OptPort::Set(80))),
// Standalone bracketed IPvFuture — surfaces as Uninterpreted
// (matches the URI authority parser). Display brackets it.
("[v1.fe80::a]", ("[v1.fe80::a]", OptPort::Unset)),
("127.0.0.1", ("127.0.0.1", OptPort::Unset)),
("127.0.0.1:80", ("127.0.0.1", OptPort::Set(80))),
(
"2001:db8:3333:4444:5555:6666:7777:8888",
("2001:db8:3333:4444:5555:6666:7777:8888", OptPort::Unset),
),
(
"[2001:db8:3333:4444:5555:6666:7777:8888]:80",
("2001:db8:3333:4444:5555:6666:7777:8888", OptPort::Set(80)),
),
] {
let msg = format!("parsing '{s}'");
assert_eq(s, s.parse().expect(&msg), expected_host, expected_port);
assert_eq(s, s.try_into().expect(&msg), expected_host, expected_port);
assert_eq(
s,
s.to_owned().try_into().expect(&msg),
expected_host,
expected_port,
);
assert_eq(
s,
s.as_bytes().try_into().expect(&msg),
expected_host,
expected_port,
);
assert_eq(
s,
s.as_bytes().to_vec().try_into().expect(&msg),
expected_host,
expected_port,
);
}
}
#[test]
fn test_parse_invalid() {
for s in [
"",
// Empty host with port — eager and lazy paths agree on
// rejection (the URI authority parser does too).
":80",
// Empty bracketed IP-literal.
"[]",
"2001:db8:3333:4444:5555:6666:7777:8888]",
"[2001:db8:3333:4444:5555:6666:7777:8888",
"example.com:-1",
"example.com:999999",
"example:com",
"[127.0.0.1]:80",
"2001:db8:3333:4444:5555:6666:7777:8888:80",
] {
let msg = format!("parsing '{s}'");
assert!(s.parse::<HostWithOptPort>().is_err(), "{msg}");
assert!(HostWithOptPort::try_from(s).is_err(), "{msg}");
assert!(HostWithOptPort::try_from(s.to_owned()).is_err(), "{msg}");
assert!(HostWithOptPort::try_from(s.as_bytes()).is_err(), "{msg}");
assert!(
HostWithOptPort::try_from(s.as_bytes().to_vec()).is_err(),
"{msg}"
);
}
}
#[test]
fn test_parse_display() {
for (s, expected) in [
("example.com", "example.com"),
("example.com:80", "example.com:80"),
("example.com:", "example.com:"),
("[::1]:80", "[::1]:80"),
// IPv6 always brackets — even with no port — to avoid
// the `::1:8080` ambiguity. See the `Display` impl above
// for the single-source-of-truth rationale.
("::1", "[::1]"),
("127.0.0.1:80", "127.0.0.1:80"),
("127.0.0.1", "127.0.0.1"),
] {
let msg = format!("parsing '{s}'");
let hwop: HostWithOptPort = s.parse().expect(&msg);
assert_eq!(hwop.to_string(), expected, "{msg}");
}
}
}