Skip to main content

rustls_pki_types/
server_name.rs

1//! DNS name validation according to RFC1035, but with underscores allowed.
2
3#[cfg(all(feature = "alloc", feature = "std"))]
4use alloc::borrow::Cow;
5#[cfg(feature = "alloc")]
6use alloc::string::{String, ToString};
7use core::hash::{Hash, Hasher};
8use core::{fmt, mem, str};
9#[cfg(feature = "std")]
10use std::error::Error as StdError;
11
12/// Encodes ways a client can know the expected name of the server.
13///
14/// This currently covers knowing the DNS name of the server, but
15/// will be extended in the future to supporting privacy-preserving names
16/// for the server ("ECH").  For this reason this enum is `non_exhaustive`.
17///
18/// # Making one
19///
20/// If you have a DNS name as a `&str`, this type implements `TryFrom<&str>`,
21/// so you can do:
22///
23/// ```
24/// # use rustls_pki_types::ServerName;
25/// ServerName::try_from("example.com").expect("invalid DNS name");
26/// ```
27///
28/// If you have an owned `String`, you can use `TryFrom` directly:
29///
30/// ```
31/// # use rustls_pki_types::ServerName;
32/// let name = "example.com".to_string();
33/// #[cfg(feature = "alloc")]
34/// ServerName::try_from(name).expect("invalid DNS name");
35/// ```
36///
37/// which will yield a `ServerName<'static>` if successful.
38///
39/// or, alternatively...
40///
41/// ```
42/// # use rustls_pki_types::ServerName;
43/// let x: ServerName = "example.com".try_into().expect("invalid DNS name");
44/// ```
45#[non_exhaustive]
46#[derive(Clone, Eq, Hash, PartialEq)]
47pub enum ServerName<'a> {
48    /// The server is identified by a DNS name.  The name
49    /// is sent in the TLS Server Name Indication (SNI)
50    /// extension.
51    DnsName(DnsName<'a>),
52
53    /// The server is identified by an IP address. SNI is not
54    /// done.
55    IpAddress(IpAddr),
56}
57
58impl ServerName<'_> {
59    /// Produce an owned `ServerName` from this (potentially borrowed) `ServerName`.
60    #[cfg(feature = "alloc")]
61    pub fn to_owned(&self) -> ServerName<'static> {
62        match self {
63            Self::DnsName(d) => ServerName::DnsName(d.to_owned()),
64            Self::IpAddress(i) => ServerName::IpAddress(*i),
65        }
66    }
67
68    /// Return the string representation of this `ServerName`.
69    ///
70    /// In the case of a `ServerName::DnsName` instance, this function returns a borrowed `str`.
71    /// For a `ServerName::IpAddress` instance it returns an allocated `String`.
72    #[cfg(feature = "std")]
73    pub fn to_str(&self) -> Cow<'_, str> {
74        match self {
75            Self::DnsName(d) => d.as_ref().into(),
76            Self::IpAddress(i) => std::net::IpAddr::from(*i).to_string().into(),
77        }
78    }
79}
80
81impl fmt::Debug for ServerName<'_> {
82    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
83        match self {
84            Self::DnsName(d) => f.debug_tuple("DnsName").field(&d.as_ref()).finish(),
85            Self::IpAddress(i) => f.debug_tuple("IpAddress").field(i).finish(),
86        }
87    }
88}
89
90#[cfg(feature = "alloc")]
91impl TryFrom<String> for ServerName<'static> {
92    type Error = InvalidDnsNameError;
93
94    fn try_from(value: String) -> Result<Self, Self::Error> {
95        match DnsName::try_from_string(value) {
96            Ok(dns) => Ok(Self::DnsName(dns)),
97            Err(value) => match IpAddr::try_from(value.as_str()) {
98                Ok(ip) => Ok(Self::IpAddress(ip)),
99                Err(_) => Err(InvalidDnsNameError),
100            },
101        }
102    }
103}
104
105impl<'a> TryFrom<&'a [u8]> for ServerName<'a> {
106    type Error = InvalidDnsNameError;
107
108    fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
109        match str::from_utf8(value) {
110            Ok(s) => Self::try_from(s),
111            Err(_) => Err(InvalidDnsNameError),
112        }
113    }
114}
115
116/// Attempt to make a ServerName from a string by parsing as a DNS name or IP address.
117impl<'a> TryFrom<&'a str> for ServerName<'a> {
118    type Error = InvalidDnsNameError;
119    fn try_from(s: &'a str) -> Result<Self, Self::Error> {
120        match DnsName::try_from(s) {
121            Ok(dns) => Ok(Self::DnsName(dns)),
122            Err(InvalidDnsNameError) => match IpAddr::try_from(s) {
123                Ok(ip) => Ok(Self::IpAddress(ip)),
124                Err(_) => Err(InvalidDnsNameError),
125            },
126        }
127    }
128}
129
130impl From<IpAddr> for ServerName<'_> {
131    fn from(addr: IpAddr) -> Self {
132        Self::IpAddress(addr)
133    }
134}
135
136#[cfg(feature = "std")]
137impl From<std::net::IpAddr> for ServerName<'_> {
138    fn from(addr: std::net::IpAddr) -> Self {
139        Self::IpAddress(addr.into())
140    }
141}
142
143impl From<Ipv4Addr> for ServerName<'_> {
144    fn from(v4: Ipv4Addr) -> Self {
145        Self::IpAddress(IpAddr::V4(v4))
146    }
147}
148
149impl From<Ipv6Addr> for ServerName<'_> {
150    fn from(v6: Ipv6Addr) -> Self {
151        Self::IpAddress(IpAddr::V6(v6))
152    }
153}
154
155#[cfg(feature = "std")]
156impl From<std::net::Ipv4Addr> for ServerName<'_> {
157    fn from(v4: std::net::Ipv4Addr) -> Self {
158        Self::IpAddress(IpAddr::V4(v4.into()))
159    }
160}
161
162#[cfg(feature = "std")]
163impl From<std::net::Ipv6Addr> for ServerName<'_> {
164    fn from(v6: std::net::Ipv6Addr) -> Self {
165        Self::IpAddress(IpAddr::V6(v6.into()))
166    }
167}
168
169impl<'a> From<DnsName<'a>> for ServerName<'a> {
170    fn from(dns_name: DnsName<'a>) -> Self {
171        Self::DnsName(dns_name)
172    }
173}
174
175/// A type which encapsulates a string (borrowed or owned) that is a syntactically valid DNS name.
176///
177/// A single trailing dot is accepted when parsing, but is removed: `example.com.`
178/// parses to a `DnsName` that is identical to one parsed from `example.com`.
179/// [RFC 6066 section 3](https://www.rfc-editor.org/info/rfc6066#section-3)
180/// specifies that the name sent in the TLS Server Name Indication extension
181/// is "without a trailing dot", so `as_ref()` always gives a name suitable for
182/// that. Callers who must treat absolute names differently need to inspect
183/// the input before parsing.
184///
185/// Equality and hashing ignore ASCII case: `example.com` and `Example.COM` are equal.
186#[derive(Clone, Debug, Eq, Hash, PartialEq)]
187pub struct DnsName<'a>(DnsNameInner<'a>);
188
189impl<'a> DnsName<'a> {
190    /// Produce a borrowed `DnsName` from this owned `DnsName`.
191    pub fn borrow(&'a self) -> Self {
192        Self(match self {
193            Self(DnsNameInner::Borrowed(s)) => DnsNameInner::Borrowed(s),
194            #[cfg(feature = "alloc")]
195            Self(DnsNameInner::Owned(s)) => DnsNameInner::Borrowed(s.as_str()),
196        })
197    }
198
199    /// Copy this object to produce an owned `DnsName`, smashing the case to lowercase
200    /// in one operation.
201    #[cfg(feature = "alloc")]
202    pub fn to_lowercase_owned(&self) -> DnsName<'static> {
203        DnsName(DnsNameInner::Owned(self.as_ref().to_ascii_lowercase()))
204    }
205
206    /// Copy an owned `DnsName` from this (potentially borrowed) `DnsName`.
207    #[cfg(feature = "alloc")]
208    pub fn to_owned(&self) -> DnsName<'static> {
209        DnsName(DnsNameInner::Owned(match self {
210            Self(DnsNameInner::Borrowed(s)) => s.to_string(),
211            #[cfg(feature = "alloc")]
212            Self(DnsNameInner::Owned(s)) => s.clone(),
213        }))
214    }
215
216    /// Produce an owned `DnsName` from this (potentially borrowed) `DnsName`.
217    #[cfg(feature = "alloc")]
218    pub fn into_owned(self) -> DnsName<'static> {
219        DnsName(DnsNameInner::Owned(match self {
220            Self(DnsNameInner::Borrowed(s)) => s.to_string(),
221            #[cfg(feature = "alloc")]
222            Self(DnsNameInner::Owned(s)) => s,
223        }))
224    }
225
226    #[cfg(feature = "alloc")]
227    fn try_from_string(mut s: String) -> Result<Self, String> {
228        match validate(s.as_bytes()) {
229            Ok(_) => {
230                if s.ends_with('.') {
231                    s.pop();
232                }
233                Ok(Self(DnsNameInner::Owned(s)))
234            }
235            Err(_) => Err(s),
236        }
237    }
238
239    /// Produces a borrowed [`DnsName`] from a borrowed [`str`].
240    pub const fn try_from_str(s: &str) -> Result<DnsName<'_>, InvalidDnsNameError> {
241        match validate(s.as_bytes()) {
242            Ok(_) => Ok(DnsName(DnsNameInner::Borrowed(strip_trailing_dot(s)))),
243            Err(err) => Err(err),
244        }
245    }
246}
247
248#[cfg(feature = "alloc")]
249impl TryFrom<String> for DnsName<'static> {
250    type Error = InvalidDnsNameError;
251
252    fn try_from(value: String) -> Result<Self, Self::Error> {
253        Self::try_from_string(value).map_err(|_| InvalidDnsNameError)
254    }
255}
256
257impl<'a> TryFrom<&'a str> for DnsName<'a> {
258    type Error = InvalidDnsNameError;
259
260    fn try_from(value: &'a str) -> Result<Self, Self::Error> {
261        DnsName::try_from_str(value)
262    }
263}
264
265impl<'a> TryFrom<&'a [u8]> for DnsName<'a> {
266    type Error = InvalidDnsNameError;
267
268    fn try_from(value: &'a [u8]) -> Result<Self, Self::Error> {
269        validate(value)?;
270        let s = str::from_utf8(value).unwrap();
271        Ok(Self(DnsNameInner::Borrowed(strip_trailing_dot(s))))
272    }
273}
274
275impl AsRef<str> for DnsName<'_> {
276    fn as_ref(&self) -> &str {
277        match self {
278            Self(DnsNameInner::Borrowed(s)) => s,
279            #[cfg(feature = "alloc")]
280            Self(DnsNameInner::Owned(s)) => s.as_str(),
281        }
282    }
283}
284
285#[derive(Clone, Eq)]
286enum DnsNameInner<'a> {
287    Borrowed(&'a str),
288    #[cfg(feature = "alloc")]
289    Owned(String),
290}
291
292impl PartialEq<Self> for DnsNameInner<'_> {
293    fn eq(&self, other: &Self) -> bool {
294        match (self, other) {
295            (Self::Borrowed(s), Self::Borrowed(o)) => s.eq_ignore_ascii_case(o),
296            #[cfg(feature = "alloc")]
297            (Self::Borrowed(s), Self::Owned(o)) => s.eq_ignore_ascii_case(o.as_str()),
298            #[cfg(feature = "alloc")]
299            (Self::Owned(s), Self::Borrowed(o)) => s.eq_ignore_ascii_case(o),
300            #[cfg(feature = "alloc")]
301            (Self::Owned(s), Self::Owned(o)) => s.eq_ignore_ascii_case(o.as_str()),
302        }
303    }
304}
305
306impl Hash for DnsNameInner<'_> {
307    fn hash<H: Hasher>(&self, state: &mut H) {
308        let s = match self {
309            Self::Borrowed(s) => s,
310            #[cfg(feature = "alloc")]
311            Self::Owned(s) => s.as_str(),
312        };
313
314        s.chars().for_each(|c| c.to_ascii_lowercase().hash(state));
315    }
316}
317
318impl fmt::Debug for DnsNameInner<'_> {
319    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
320        match self {
321            Self::Borrowed(s) => f.write_fmt(format_args!("{s:?}")),
322            #[cfg(feature = "alloc")]
323            Self::Owned(s) => f.write_fmt(format_args!("{s:?}")),
324        }
325    }
326}
327
328/// The provided input could not be parsed because
329/// it is not a syntactically-valid DNS Name.
330#[allow(clippy::exhaustive_structs)]
331#[derive(Debug)]
332pub struct InvalidDnsNameError;
333
334impl fmt::Display for InvalidDnsNameError {
335    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
336        f.write_str("invalid dns name")
337    }
338}
339
340#[cfg(feature = "std")]
341impl StdError for InvalidDnsNameError {}
342
343const fn validate(input: &[u8]) -> Result<(), InvalidDnsNameError> {
344    enum LabelState {
345        /// The current label is still empty
346        Start,
347        /// The current label is known not to be a decimal or hex number
348        NonNumeric,
349        /// The current label is all-numeric so far
350        ///
351        /// (at least two digits or a first digit other than "0")
352        AllNumeric,
353        /// The current label is exactly "0" so far
354        Zero,
355        /// The current label is "0x" or "0X", followed by zero or more hex digits
356        HexNumber,
357        /// The last character was a hyphen
358        EndsInHyphen,
359    }
360
361    /// "Labels must be 63 characters or less."
362    const MAX_LABEL_LENGTH: usize = 63;
363
364    /// https://devblogs.microsoft.com/oldnewthing/20120412-00/?p=7873
365    const MAX_NAME_LENGTH: usize = 253;
366
367    if input.is_empty() || input.len() > MAX_NAME_LENGTH {
368        return Err(InvalidDnsNameError);
369    }
370
371    let mut start = 0;
372    let mut state = LabelState::Start;
373    let mut idx = 0;
374    loop {
375        let ch = match idx < input.len() {
376            true => Some(input[idx]),
377            false => None,
378        };
379
380        match ch {
381            Some(c @ (b'a'..=b'z' | b'A'..=b'Z' | b'_')) => {
382                state = match (state, c) {
383                    (LabelState::Zero, b'x' | b'X') => LabelState::HexNumber,
384                    (LabelState::HexNumber, b'a'..=b'f' | b'A'..=b'F') => LabelState::HexNumber,
385                    _ => LabelState::NonNumeric,
386                }
387            }
388            Some(c @ b'0'..=b'9') => {
389                state = match state {
390                    LabelState::Start if c == b'0' => LabelState::Zero,
391                    LabelState::Start | LabelState::AllNumeric | LabelState::Zero => {
392                        LabelState::AllNumeric
393                    }
394                    LabelState::HexNumber => LabelState::HexNumber,
395                    LabelState::NonNumeric | LabelState::EndsInHyphen => LabelState::NonNumeric,
396                }
397            }
398            Some(b'.') | None => {
399                let len = idx - start;
400                if len == 0 || len > MAX_LABEL_LENGTH || matches!(state, LabelState::EndsInHyphen) {
401                    return Err(InvalidDnsNameError);
402                }
403
404                // Break on a trailing dot as well as on the end of input, keeping
405                // `state` intact for the final numeric check below.
406                if idx + 1 >= input.len() {
407                    break;
408                }
409
410                idx += 1;
411                start = idx;
412                state = LabelState::Start;
413                continue;
414            }
415            Some(b'-') => match idx == start {
416                true => return Err(InvalidDnsNameError),
417                false => state = LabelState::EndsInHyphen,
418            },
419            _ => return Err(InvalidDnsNameError),
420        }
421
422        idx += 1;
423    }
424
425    // The final label (whether or not the name has a trailing dot) must
426    // not be all-numeric or a hex number, to avoid confusion with an IPv4
427    // address. This follows the "ends in a number" rule of the WHATWG URL
428    // standard <https://url.spec.whatwg.org/#ends-in-a-number-checker>, and
429    // the rule RFC 9849 section 6.1.7 gives for ECH public names
430    // <https://www.rfc-editor.org/info/rfc9849#section-6.1.7-7>.
431    match state {
432        LabelState::AllNumeric | LabelState::Zero | LabelState::HexNumber => {
433            Err(InvalidDnsNameError)
434        }
435        _ => Ok(()),
436    }
437}
438
439/// Remove one trailing dot from `s`, if present.
440///
441/// `validate()` rejects empty labels, so a validated name has at most one.
442const fn strip_trailing_dot(s: &str) -> &str {
443    match s.as_bytes() {
444        // SAFETY: `rest` is `s` minus a final ASCII byte, so is still valid UTF-8.
445        [rest @ .., b'.'] => unsafe { str::from_utf8_unchecked(rest) },
446        _ => s,
447    }
448}
449
450/// `no_std` implementation of `std::net::IpAddr`.
451///
452/// Note: because we intend to replace this type with `core::net::IpAddr` as soon as it is
453/// stabilized, the identity of this type should not be considered semver-stable. However, the
454/// attached interfaces are stable; they form a subset of those provided by `core::net::IpAddr`.
455#[allow(clippy::exhaustive_enums)]
456#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
457pub enum IpAddr {
458    /// An Ipv4 address.
459    V4(Ipv4Addr),
460    /// An Ipv6 address.
461    V6(Ipv6Addr),
462}
463
464impl TryFrom<&str> for IpAddr {
465    type Error = AddrParseError;
466
467    fn try_from(value: &str) -> Result<Self, Self::Error> {
468        match Ipv4Addr::try_from(value) {
469            Ok(v4) => Ok(Self::V4(v4)),
470            Err(_) => match Ipv6Addr::try_from(value) {
471                Ok(v6) => Ok(Self::V6(v6)),
472                Err(e) => Err(e),
473            },
474        }
475    }
476}
477
478#[cfg(feature = "std")]
479impl From<std::net::IpAddr> for IpAddr {
480    fn from(addr: std::net::IpAddr) -> Self {
481        match addr {
482            std::net::IpAddr::V4(v4) => Self::V4(v4.into()),
483            std::net::IpAddr::V6(v6) => Self::V6(v6.into()),
484        }
485    }
486}
487
488#[cfg(feature = "std")]
489impl From<IpAddr> for std::net::IpAddr {
490    fn from(value: IpAddr) -> Self {
491        match value {
492            IpAddr::V4(v4) => Self::from(std::net::Ipv4Addr::from(v4)),
493            IpAddr::V6(v6) => Self::from(std::net::Ipv6Addr::from(v6)),
494        }
495    }
496}
497
498#[cfg(feature = "std")]
499impl From<std::net::Ipv4Addr> for IpAddr {
500    fn from(v4: std::net::Ipv4Addr) -> Self {
501        Self::V4(v4.into())
502    }
503}
504
505#[cfg(feature = "std")]
506impl From<std::net::Ipv6Addr> for IpAddr {
507    fn from(v6: std::net::Ipv6Addr) -> Self {
508        Self::V6(v6.into())
509    }
510}
511
512/// `no_std` implementation of `std::net::Ipv4Addr`.
513///
514/// Note: because we intend to replace this type with `core::net::Ipv4Addr` as soon as it is
515/// stabilized, the identity of this type should not be considered semver-stable. However, the
516/// attached interfaces are stable; they form a subset of those provided by `core::net::Ipv4Addr`.
517#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
518pub struct Ipv4Addr([u8; 4]);
519
520impl From<[u8; 4]> for Ipv4Addr {
521    fn from(value: [u8; 4]) -> Self {
522        Self(value)
523    }
524}
525
526impl TryFrom<&str> for Ipv4Addr {
527    type Error = AddrParseError;
528
529    fn try_from(value: &str) -> Result<Self, Self::Error> {
530        // don't try to parse if too long
531        if value.len() > 15 {
532            Err(AddrParseError(AddrKind::Ipv4))
533        } else {
534            Parser::new(value.as_bytes()).parse_with(|p| p.read_ipv4_addr(), AddrKind::Ipv4)
535        }
536    }
537}
538
539#[cfg(feature = "std")]
540impl From<std::net::Ipv4Addr> for Ipv4Addr {
541    fn from(addr: std::net::Ipv4Addr) -> Self {
542        Self(addr.octets())
543    }
544}
545
546#[cfg(feature = "std")]
547impl From<Ipv4Addr> for std::net::Ipv4Addr {
548    fn from(value: Ipv4Addr) -> Self {
549        Self::from(value.0)
550    }
551}
552
553impl AsRef<[u8; 4]> for Ipv4Addr {
554    fn as_ref(&self) -> &[u8; 4] {
555        &self.0
556    }
557}
558
559/// `no_std` implementation of `std::net::Ipv6Addr`.
560///
561/// Note: because we intend to replace this type with `core::net::Ipv6Addr` as soon as it is
562/// stabilized, the identity of this type should not be considered semver-stable. However, the
563/// attached interfaces are stable; they form a subset of those provided by `core::net::Ipv6Addr`.
564#[derive(Clone, Copy, Debug, Eq, Hash, PartialEq)]
565pub struct Ipv6Addr([u8; 16]);
566
567impl TryFrom<&str> for Ipv6Addr {
568    type Error = AddrParseError;
569
570    fn try_from(value: &str) -> Result<Self, Self::Error> {
571        Parser::new(value.as_bytes()).parse_with(|p| p.read_ipv6_addr(), AddrKind::Ipv6)
572    }
573}
574
575impl From<[u16; 8]> for Ipv6Addr {
576    fn from(value: [u16; 8]) -> Self {
577        // Adapted from `std::net::Ipv6Addr::new()`
578        let addr16 = [
579            value[0].to_be(),
580            value[1].to_be(),
581            value[2].to_be(),
582            value[3].to_be(),
583            value[4].to_be(),
584            value[5].to_be(),
585            value[6].to_be(),
586            value[7].to_be(),
587        ];
588        Self(
589            // All elements in `addr16` are big endian.
590            // SAFETY: `[u16; 8]` is always safe to transmute to `[u8; 16]`.
591            unsafe { mem::transmute::<[u16; 8], [u8; 16]>(addr16) },
592        )
593    }
594}
595
596#[cfg(feature = "std")]
597impl From<std::net::Ipv6Addr> for Ipv6Addr {
598    fn from(addr: std::net::Ipv6Addr) -> Self {
599        Self(addr.octets())
600    }
601}
602
603#[cfg(feature = "std")]
604impl From<Ipv6Addr> for std::net::Ipv6Addr {
605    fn from(value: Ipv6Addr) -> Self {
606        Self::from(value.0)
607    }
608}
609
610impl AsRef<[u8; 16]> for Ipv6Addr {
611    fn as_ref(&self) -> &[u8; 16] {
612        &self.0
613    }
614}
615
616// Adapted from core, 2023-11-23
617//
618// https://github.com/rust-lang/rust/blob/fc13ca6d70f7381513c22443fc5aaee1d151ea45/library/core/src/net/parser.rs#L34
619mod parser {
620    use super::{AddrParseError, Ipv4Addr, Ipv6Addr};
621
622    pub(super) struct Parser<'a> {
623        // Parsing as ASCII, so can use byte array.
624        state: &'a [u8],
625    }
626
627    impl<'a> Parser<'a> {
628        pub(super) const fn new(input: &'a [u8]) -> Self {
629            Parser { state: input }
630        }
631
632        /// Run a parser, and restore the pre-parse state if it fails.
633        fn read_atomically<T, F>(&mut self, inner: F) -> Option<T>
634        where
635            F: FnOnce(&mut Parser<'_>) -> Option<T>,
636        {
637            let state = self.state;
638            let result = inner(self);
639            if result.is_none() {
640                self.state = state;
641            }
642            result
643        }
644
645        /// Run a parser, but fail if the entire input wasn't consumed.
646        /// Doesn't run atomically.
647        pub(super) fn parse_with<T, F>(
648            &mut self,
649            inner: F,
650            kind: AddrKind,
651        ) -> Result<T, AddrParseError>
652        where
653            F: FnOnce(&mut Parser<'_>) -> Option<T>,
654        {
655            let result = inner(self);
656            if self.state.is_empty() { result } else { None }.ok_or(AddrParseError(kind))
657        }
658
659        /// Peek the next character from the input
660        fn peek_char(&self) -> Option<char> {
661            self.state.first().map(|&b| char::from(b))
662        }
663
664        /// Read the next character from the input
665        fn read_char(&mut self) -> Option<char> {
666            self.state.split_first().map(|(&b, tail)| {
667                self.state = tail;
668                char::from(b)
669            })
670        }
671
672        #[must_use]
673        /// Read the next character from the input if it matches the target.
674        fn read_given_char(&mut self, target: char) -> Option<()> {
675            self.read_atomically(|p| {
676                p.read_char()
677                    .and_then(|c| if c == target { Some(()) } else { None })
678            })
679        }
680
681        /// Helper for reading separators in an indexed loop. Reads the separator
682        /// character iff index > 0, then runs the parser. When used in a loop,
683        /// the separator character will only be read on index > 0 (see
684        /// read_ipv4_addr for an example)
685        fn read_separator<T, F>(&mut self, sep: char, index: usize, inner: F) -> Option<T>
686        where
687            F: FnOnce(&mut Parser<'_>) -> Option<T>,
688        {
689            self.read_atomically(move |p| {
690                if index > 0 {
691                    p.read_given_char(sep)?;
692                }
693                inner(p)
694            })
695        }
696
697        // Read a number off the front of the input in the given radix, stopping
698        // at the first non-digit character or eof. Fails if the number has more
699        // digits than max_digits or if there is no number.
700        fn read_number<T: ReadNumberHelper>(
701            &mut self,
702            radix: u32,
703            max_digits: Option<usize>,
704            allow_zero_prefix: bool,
705        ) -> Option<T> {
706            self.read_atomically(move |p| {
707                let mut result = T::ZERO;
708                let mut digit_count = 0;
709                let has_leading_zero = p.peek_char() == Some('0');
710
711                while let Some(digit) = p.read_atomically(|p| p.read_char()?.to_digit(radix)) {
712                    result = result.checked_mul(radix)?;
713                    result = result.checked_add(digit)?;
714                    digit_count += 1;
715                    if let Some(max_digits) = max_digits {
716                        if digit_count > max_digits {
717                            return None;
718                        }
719                    }
720                }
721
722                if digit_count == 0 || (!allow_zero_prefix && has_leading_zero && digit_count > 1) {
723                    None
724                } else {
725                    Some(result)
726                }
727            })
728        }
729
730        /// Read an IPv4 address.
731        pub(super) fn read_ipv4_addr(&mut self) -> Option<Ipv4Addr> {
732            self.read_atomically(|p| {
733                let mut groups = [0; 4];
734
735                for (i, slot) in groups.iter_mut().enumerate() {
736                    *slot = p.read_separator('.', i, |p| {
737                        // Disallow octal number in IP string.
738                        // https://tools.ietf.org/html/rfc6943#section-3.1.1
739                        p.read_number(10, Some(3), false)
740                    })?;
741                }
742
743                Some(Ipv4Addr(groups))
744            })
745        }
746
747        /// Read an IPv6 Address.
748        pub(super) fn read_ipv6_addr(&mut self) -> Option<Ipv6Addr> {
749            /// Read a chunk of an IPv6 address into `groups`. Returns the number
750            /// of groups read, along with a bool indicating if an embedded
751            /// trailing IPv4 address was read. Specifically, read a series of
752            /// colon-separated IPv6 groups (0x0000 - 0xFFFF), with an optional
753            /// trailing embedded IPv4 address.
754            fn read_groups(p: &mut Parser<'_>, groups: &mut [u16]) -> (usize, bool) {
755                let limit = groups.len();
756
757                for (i, slot) in groups.iter_mut().enumerate() {
758                    // Try to read a trailing embedded IPv4 address. There must be
759                    // at least two groups left.
760                    if i < limit - 1 {
761                        let ipv4 = p.read_separator(':', i, |p| p.read_ipv4_addr());
762
763                        if let Some(v4_addr) = ipv4 {
764                            let [one, two, three, four] = v4_addr.0;
765                            groups[i] = u16::from_be_bytes([one, two]);
766                            groups[i + 1] = u16::from_be_bytes([three, four]);
767                            return (i + 2, true);
768                        }
769                    }
770
771                    let group = p.read_separator(':', i, |p| p.read_number(16, Some(4), true));
772
773                    match group {
774                        Some(g) => *slot = g,
775                        None => return (i, false),
776                    }
777                }
778                (groups.len(), false)
779            }
780
781            self.read_atomically(|p| {
782                // Read the front part of the address; either the whole thing, or up
783                // to the first ::
784                let mut head = [0; 8];
785                let (head_size, head_ipv4) = read_groups(p, &mut head);
786
787                if head_size == 8 {
788                    return Some(head.into());
789                }
790
791                // IPv4 part is not allowed before `::`
792                if head_ipv4 {
793                    return None;
794                }
795
796                // Read `::` if previous code parsed less than 8 groups.
797                // `::` indicates one or more groups of 16 bits of zeros.
798                p.read_given_char(':')?;
799                p.read_given_char(':')?;
800
801                // Read the back part of the address. The :: must contain at least one
802                // set of zeroes, so our max length is 7.
803                let mut tail = [0; 7];
804                let limit = 8 - (head_size + 1);
805                let (tail_size, _) = read_groups(p, &mut tail[..limit]);
806
807                // Concat the head and tail of the IP address
808                head[(8 - tail_size)..8].copy_from_slice(&tail[..tail_size]);
809
810                Some(head.into())
811            })
812        }
813    }
814
815    trait ReadNumberHelper: Sized {
816        const ZERO: Self;
817        fn checked_mul(&self, other: u32) -> Option<Self>;
818        fn checked_add(&self, other: u32) -> Option<Self>;
819    }
820
821    macro_rules! impl_helper {
822        ($($t:ty)*) => ($(impl ReadNumberHelper for $t {
823            const ZERO: Self = 0;
824            #[inline]
825            fn checked_mul(&self, other: u32) -> Option<Self> {
826                Self::checked_mul(*self, other.try_into().ok()?)
827            }
828            #[inline]
829            fn checked_add(&self, other: u32) -> Option<Self> {
830                Self::checked_add(*self, other.try_into().ok()?)
831            }
832        })*)
833    }
834
835    impl_helper! { u8 u16 u32 }
836
837    #[derive(Debug, Clone, Copy, Eq, PartialEq)]
838    pub(super) enum AddrKind {
839        Ipv4,
840        Ipv6,
841    }
842}
843
844use parser::{AddrKind, Parser};
845
846/// Failure to parse an IP address
847#[derive(Debug, Clone, Copy, Eq, PartialEq)]
848pub struct AddrParseError(AddrKind);
849
850impl fmt::Display for AddrParseError {
851    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
852        f.write_str(match self.0 {
853            AddrKind::Ipv4 => "invalid IPv4 address syntax",
854            AddrKind::Ipv6 => "invalid IPv6 address syntax",
855        })
856    }
857}
858
859#[cfg(feature = "std")]
860impl ::std::error::Error for AddrParseError {}
861
862#[cfg(test)]
863mod tests {
864    use super::*;
865    #[cfg(feature = "alloc")]
866    use alloc::format;
867
868    #[cfg(feature = "alloc")]
869    static TESTS: &[(&str, bool)] = &[
870        ("", false),
871        ("localhost", true),
872        ("LOCALHOST", true),
873        (".localhost", false),
874        ("..localhost", false),
875        ("1.2.3.4", false),
876        ("127.0.0.1", false),
877        ("absolute.", true),
878        ("absolute..", false),
879        ("multiple.labels.absolute.", true),
880        ("foo.bar.com", true),
881        ("infix-hyphen-allowed.com", true),
882        ("-prefixhypheninvalid.com", false),
883        ("suffixhypheninvalid--", false),
884        ("suffixhypheninvalid-.com", false),
885        ("foo.lastlabelendswithhyphen-", false),
886        ("infix_underscore_allowed.com", true),
887        ("_prefixunderscorevalid.com", true),
888        ("labelendswithnumber1.bar.com", true),
889        ("xn--bcher-kva.example", true),
890        (
891            "sixtythreesixtythreesixtythreesixtythreesixtythreesixtythreesix.com",
892            true,
893        ),
894        (
895            "sixtyfoursixtyfoursixtyfoursixtyfoursixtyfoursixtyfoursixtyfours.com",
896            false,
897        ),
898        (
899            "012345678901234567890123456789012345678901234567890123456789012.com",
900            true,
901        ),
902        (
903            "0123456789012345678901234567890123456789012345678901234567890123.com",
904            false,
905        ),
906        (
907            "01234567890123456789012345678901234567890123456789012345678901-.com",
908            false,
909        ),
910        (
911            "012345678901234567890123456789012345678901234567890123456789012-.com",
912            false,
913        ),
914        ("numeric-only-final-label.1", false),
915        ("numeric-only-final-label.absolute.1.", false),
916        ("1starts-with-number.com", true),
917        ("1Starts-with-number.com", true),
918        ("1.2.3.4.com", true),
919        ("123.numeric-only-first-label", true),
920        ("a123b.com", true),
921        ("numeric-only-middle-label.4.com", true),
922        ("0", false),
923        ("example.0", false),
924        ("example.00", false),
925        ("0x7f000001", false),
926        ("example.0x7f000001", false),
927        ("example.0X1f", false),
928        ("example.0xABCdef", false),
929        ("example.0x", false),
930        ("example.0x.", false),
931        ("example.0x1f.", false),
932        ("0x1f.example", true),
933        ("0xg.example", true),
934        ("example.0xg", true),
935        ("example.0x1g", true),
936        ("example.0xx", true),
937        ("example.0x-1", true),
938        ("example.00x1", true),
939        ("example.1x1", true),
940        ("example.x1", true),
941        ("1000-sans.badssl.com", true),
942        (
943            "twohundredandfiftythreecharacters.twohundredandfiftythreecharacters.twohundredandfiftythreecharacters.twohundredandfiftythreecharacters.twohundredandfiftythreecharacters.twohundredandfiftythreecharacters.twohundredandfiftythreecharacters.twohundredandfi",
944            true,
945        ),
946        (
947            "twohundredandfiftyfourcharacters.twohundredandfiftyfourcharacters.twohundredandfiftyfourcharacters.twohundredandfiftyfourcharacters.twohundredandfiftyfourcharacters.twohundredandfiftyfourcharacters.twohundredandfiftyfourcharacters.twohundredandfiftyfourc",
948            false,
949        ),
950    ];
951
952    #[cfg(feature = "alloc")]
953    #[test]
954    fn test_validation() {
955        for (input, expected) in TESTS {
956            #[cfg(feature = "std")]
957            println!("test: {input:?} expected valid? {expected:?}");
958            let name_ref = DnsName::try_from(*input);
959            assert_eq!(*expected, name_ref.is_ok());
960            let name = DnsName::try_from(input.to_string());
961            assert_eq!(*expected, name.is_ok());
962        }
963    }
964
965    #[cfg(feature = "alloc")]
966    #[test]
967    fn error_is_debug() {
968        assert_eq!(format!("{InvalidDnsNameError:?}"), "InvalidDnsNameError");
969    }
970
971    #[cfg(feature = "alloc")]
972    #[test]
973    fn error_is_display() {
974        assert_eq!(format!("{InvalidDnsNameError}"), "invalid dns name");
975    }
976
977    #[cfg(feature = "alloc")]
978    #[test]
979    fn dns_name_is_debug() {
980        let example = DnsName::try_from("example.com".to_string()).unwrap();
981        assert_eq!(format!("{example:?}"), "DnsName(\"example.com\")");
982    }
983
984    #[cfg(feature = "alloc")]
985    #[test]
986    fn dns_name_traits() {
987        let example = DnsName::try_from("example.com".to_string()).unwrap();
988        assert_eq!(example, example); // PartialEq
989
990        #[cfg(feature = "std")]
991        {
992            use std::collections::HashSet;
993            let mut h = HashSet::<DnsName<'_>>::new();
994            h.insert(example);
995        }
996    }
997
998    #[cfg(feature = "alloc")]
999    #[test]
1000    fn try_from_ascii_rejects_bad_utf8() {
1001        assert_eq!(
1002            format!("{:?}", DnsName::try_from(&b"\x80"[..])),
1003            "Err(InvalidDnsNameError)"
1004        );
1005    }
1006
1007    const fn ipv4_address(
1008        ip_address: &str,
1009        octets: [u8; 4],
1010    ) -> (&str, Result<Ipv4Addr, AddrParseError>) {
1011        (ip_address, Ok(Ipv4Addr(octets)))
1012    }
1013
1014    const IPV4_ADDRESSES: &[(&str, Result<Ipv4Addr, AddrParseError>)] = &[
1015        // Valid IPv4 addresses
1016        ipv4_address("0.0.0.0", [0, 0, 0, 0]),
1017        ipv4_address("1.1.1.1", [1, 1, 1, 1]),
1018        ipv4_address("205.0.0.0", [205, 0, 0, 0]),
1019        ipv4_address("0.205.0.0", [0, 205, 0, 0]),
1020        ipv4_address("0.0.205.0", [0, 0, 205, 0]),
1021        ipv4_address("0.0.0.205", [0, 0, 0, 205]),
1022        ipv4_address("0.0.0.20", [0, 0, 0, 20]),
1023        // Invalid IPv4 addresses
1024        ("", Err(AddrParseError(AddrKind::Ipv4))),
1025        ("...", Err(AddrParseError(AddrKind::Ipv4))),
1026        (".0.0.0.0", Err(AddrParseError(AddrKind::Ipv4))),
1027        ("0.0.0.0.", Err(AddrParseError(AddrKind::Ipv4))),
1028        ("0.0.0", Err(AddrParseError(AddrKind::Ipv4))),
1029        ("0.0.0.", Err(AddrParseError(AddrKind::Ipv4))),
1030        ("256.0.0.0", Err(AddrParseError(AddrKind::Ipv4))),
1031        ("0.256.0.0", Err(AddrParseError(AddrKind::Ipv4))),
1032        ("0.0.256.0", Err(AddrParseError(AddrKind::Ipv4))),
1033        ("0.0.0.256", Err(AddrParseError(AddrKind::Ipv4))),
1034        ("1..1.1.1", Err(AddrParseError(AddrKind::Ipv4))),
1035        ("1.1..1.1", Err(AddrParseError(AddrKind::Ipv4))),
1036        ("1.1.1..1", Err(AddrParseError(AddrKind::Ipv4))),
1037        ("025.0.0.0", Err(AddrParseError(AddrKind::Ipv4))),
1038        ("0.025.0.0", Err(AddrParseError(AddrKind::Ipv4))),
1039        ("0.0.025.0", Err(AddrParseError(AddrKind::Ipv4))),
1040        ("0.0.0.025", Err(AddrParseError(AddrKind::Ipv4))),
1041        ("1234.0.0.0", Err(AddrParseError(AddrKind::Ipv4))),
1042        ("0.1234.0.0", Err(AddrParseError(AddrKind::Ipv4))),
1043        ("0.0.1234.0", Err(AddrParseError(AddrKind::Ipv4))),
1044        ("0.0.0.1234", Err(AddrParseError(AddrKind::Ipv4))),
1045    ];
1046
1047    #[test]
1048    fn parse_ipv4_address_test() {
1049        for &(ip_address, expected_result) in IPV4_ADDRESSES {
1050            assert_eq!(Ipv4Addr::try_from(ip_address), expected_result);
1051        }
1052    }
1053
1054    const fn ipv6_address(
1055        ip_address: &str,
1056        octets: [u8; 16],
1057    ) -> (&str, Result<Ipv6Addr, AddrParseError>) {
1058        (ip_address, Ok(Ipv6Addr(octets)))
1059    }
1060
1061    const IPV6_ADDRESSES: &[(&str, Result<Ipv6Addr, AddrParseError>)] = &[
1062        // Valid IPv6 addresses
1063        ipv6_address(
1064            "2a05:d018:076c:b685:e8ab:afd3:af51:3aed",
1065            [
1066                0x2a, 0x05, 0xd0, 0x18, 0x07, 0x6c, 0xb6, 0x85, 0xe8, 0xab, 0xaf, 0xd3, 0xaf, 0x51,
1067                0x3a, 0xed,
1068            ],
1069        ),
1070        ipv6_address(
1071            "2A05:D018:076C:B685:E8AB:AFD3:AF51:3AED",
1072            [
1073                0x2a, 0x05, 0xd0, 0x18, 0x07, 0x6c, 0xb6, 0x85, 0xe8, 0xab, 0xaf, 0xd3, 0xaf, 0x51,
1074                0x3a, 0xed,
1075            ],
1076        ),
1077        ipv6_address(
1078            "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
1079            [
1080                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1081                0xff, 0xff,
1082            ],
1083        ),
1084        ipv6_address(
1085            "FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF:FFFF",
1086            [
1087                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1088                0xff, 0xff,
1089            ],
1090        ),
1091        ipv6_address(
1092            "FFFF:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
1093            [
1094                0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff, 0xff,
1095                0xff, 0xff,
1096            ],
1097        ),
1098        // Wrong hexadecimal characters on different positions
1099        (
1100            "ffgf:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
1101            Err(AddrParseError(AddrKind::Ipv6)),
1102        ),
1103        (
1104            "ffff:gfff:ffff:ffff:ffff:ffff:ffff:ffff",
1105            Err(AddrParseError(AddrKind::Ipv6)),
1106        ),
1107        (
1108            "ffff:ffff:fffg:ffff:ffff:ffff:ffff:ffff",
1109            Err(AddrParseError(AddrKind::Ipv6)),
1110        ),
1111        (
1112            "ffff:ffff:ffff:ffgf:ffff:ffff:ffff:ffff",
1113            Err(AddrParseError(AddrKind::Ipv6)),
1114        ),
1115        (
1116            "ffff:ffff:ffff:ffff:gfff:ffff:ffff:ffff",
1117            Err(AddrParseError(AddrKind::Ipv6)),
1118        ),
1119        (
1120            "ffff:ffff:ffff:ffff:ffff:fgff:ffff:ffff",
1121            Err(AddrParseError(AddrKind::Ipv6)),
1122        ),
1123        (
1124            "ffff:ffff:ffff:ffff:ffff:ffff:ffgf:ffff",
1125            Err(AddrParseError(AddrKind::Ipv6)),
1126        ),
1127        (
1128            "ffff:ffff:ffff:ffff:ffff:ffff:ffgf:fffg",
1129            Err(AddrParseError(AddrKind::Ipv6)),
1130        ),
1131        // Wrong colons on uncompressed addresses
1132        (
1133            ":ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
1134            Err(AddrParseError(AddrKind::Ipv6)),
1135        ),
1136        (
1137            "ffff::ffff:ffff:ffff:ffff:ffff:ffff:ffff",
1138            Err(AddrParseError(AddrKind::Ipv6)),
1139        ),
1140        (
1141            "ffff:ffff::ffff:ffff:ffff:ffff:ffff:ffff",
1142            Err(AddrParseError(AddrKind::Ipv6)),
1143        ),
1144        (
1145            "ffff:ffff:ffff::ffff:ffff:ffff:ffff:ffff",
1146            Err(AddrParseError(AddrKind::Ipv6)),
1147        ),
1148        (
1149            "ffff:ffff:ffff:ffff::ffff:ffff:ffff:ffff",
1150            Err(AddrParseError(AddrKind::Ipv6)),
1151        ),
1152        (
1153            "ffff:ffff:ffff:ffff:ffff::ffff:ffff:ffff",
1154            Err(AddrParseError(AddrKind::Ipv6)),
1155        ),
1156        (
1157            "ffff:ffff:ffff:ffff:ffff:ffff::ffff:ffff",
1158            Err(AddrParseError(AddrKind::Ipv6)),
1159        ),
1160        (
1161            "ffff:ffff:ffff:ffff:ffff:ffff:ffff::ffff",
1162            Err(AddrParseError(AddrKind::Ipv6)),
1163        ),
1164        // More colons than allowed
1165        (
1166            "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:",
1167            Err(AddrParseError(AddrKind::Ipv6)),
1168        ),
1169        (
1170            "ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff:ffff",
1171            Err(AddrParseError(AddrKind::Ipv6)),
1172        ),
1173        // v Invalid hexadecimal
1174        (
1175            "ga05:d018:076c:b685:e8ab:afd3:af51:3aed",
1176            Err(AddrParseError(AddrKind::Ipv6)),
1177        ),
1178        // Cannot start with colon
1179        (
1180            ":a05:d018:076c:b685:e8ab:afd3:af51:3aed",
1181            Err(AddrParseError(AddrKind::Ipv6)),
1182        ),
1183        // Cannot end with colon
1184        (
1185            "2a05:d018:076c:b685:e8ab:afd3:af51:3ae:",
1186            Err(AddrParseError(AddrKind::Ipv6)),
1187        ),
1188        // Cannot have more than seven colons
1189        (
1190            "2a05:d018:076c:b685:e8ab:afd3:af51:3a::",
1191            Err(AddrParseError(AddrKind::Ipv6)),
1192        ),
1193        // Cannot contain two colons in a row
1194        (
1195            "2a05::018:076c:b685:e8ab:afd3:af51:3aed",
1196            Err(AddrParseError(AddrKind::Ipv6)),
1197        ),
1198        // v Textual block size is longer
1199        (
1200            "2a056:d018:076c:b685:e8ab:afd3:af51:3ae",
1201            Err(AddrParseError(AddrKind::Ipv6)),
1202        ),
1203        // v Textual block size is shorter
1204        (
1205            "2a0:d018:076c:b685:e8ab:afd3:af51:3aed ",
1206            Err(AddrParseError(AddrKind::Ipv6)),
1207        ),
1208        // Shorter IPv6 address
1209        (
1210            "d018:076c:b685:e8ab:afd3:af51:3aed",
1211            Err(AddrParseError(AddrKind::Ipv6)),
1212        ),
1213        // Longer IPv6 address
1214        (
1215            "2a05:d018:076c:b685:e8ab:afd3:af51:3aed3aed",
1216            Err(AddrParseError(AddrKind::Ipv6)),
1217        ),
1218    ];
1219
1220    #[test]
1221    fn parse_ipv6_address_test() {
1222        for &(ip_address, expected_result) in IPV6_ADDRESSES {
1223            assert_eq!(Ipv6Addr::try_from(ip_address), expected_result);
1224        }
1225    }
1226
1227    #[test]
1228    fn try_from_ascii_ip_address_test() {
1229        const IP_ADDRESSES: &[(&str, Result<IpAddr, AddrParseError>)] = &[
1230            // Valid IPv4 addresses
1231            ("127.0.0.1", Ok(IpAddr::V4(Ipv4Addr([127, 0, 0, 1])))),
1232            // Invalid IPv4 addresses
1233            (
1234                // Ends with a dot; misses one octet
1235                "127.0.0.",
1236                Err(AddrParseError(AddrKind::Ipv6)),
1237            ),
1238            // Valid IPv6 addresses
1239            (
1240                "0000:0000:0000:0000:0000:0000:0000:0001",
1241                Ok(IpAddr::V6(Ipv6Addr([
1242                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1243                ]))),
1244            ),
1245            // Something else
1246            (
1247                // A hostname
1248                "example.com",
1249                Err(AddrParseError(AddrKind::Ipv6)),
1250            ),
1251        ];
1252        for &(ip_address, expected_result) in IP_ADDRESSES {
1253            assert_eq!(IpAddr::try_from(ip_address), expected_result)
1254        }
1255    }
1256
1257    #[test]
1258    fn try_from_ascii_str_ip_address_test() {
1259        const IP_ADDRESSES: &[(&str, Result<IpAddr, AddrParseError>)] = &[
1260            // Valid IPv4 addresses
1261            ("127.0.0.1", Ok(IpAddr::V4(Ipv4Addr([127, 0, 0, 1])))),
1262            // Invalid IPv4 addresses
1263            (
1264                // Ends with a dot; misses one octet
1265                "127.0.0.",
1266                Err(AddrParseError(AddrKind::Ipv6)),
1267            ),
1268            // Valid IPv6 addresses
1269            (
1270                "0000:0000:0000:0000:0000:0000:0000:0001",
1271                Ok(IpAddr::V6(Ipv6Addr([
1272                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1,
1273                ]))),
1274            ),
1275            // Something else
1276            (
1277                // A hostname
1278                "example.com",
1279                Err(AddrParseError(AddrKind::Ipv6)),
1280            ),
1281        ];
1282        for &(ip_address, expected_result) in IP_ADDRESSES {
1283            assert_eq!(IpAddr::try_from(ip_address), expected_result)
1284        }
1285    }
1286
1287    #[test]
1288    #[cfg(feature = "std")]
1289    fn to_str() {
1290        let domain_str = "example.com";
1291        let domain_servername = ServerName::try_from(domain_str).unwrap();
1292        assert_eq!(domain_str, domain_servername.to_str());
1293
1294        let ipv4_str = "127.0.0.1";
1295        let ipv4_servername = ServerName::try_from("127.0.0.1").unwrap();
1296        assert_eq!(ipv4_str, ipv4_servername.to_str());
1297
1298        let ipv6_str = "::1";
1299        let ipv6_servername = ServerName::try_from(ipv6_str).unwrap();
1300        assert_eq!("::1", ipv6_servername.to_str());
1301    }
1302}