address 0.20.0-rc.3

Network address types with strict validation, owned & borrowed variants, and standard library conversions.
Documentation
use crate::parse_port;
use crate::{DomainRef, EndpointRef, ParseError, doc_lowercase_required, impl_parse_ref};

impl_parse_ref!(EndpointRef, doc_lowercase_required!(Endpoint));

impl<'a> TryFrom<&'a [u8]> for EndpointRef<'a> {
    type Error = ParseError;

    #[doc = doc_lowercase_required!(Endpoint)]
    fn try_from(endpoint: &'a [u8]) -> Result<Self, Self::Error> {
        let (domain, port): (&[u8], u16) = parse_port(endpoint)?;
        let domain: DomainRef = DomainRef::try_from(domain)?;
        Ok(Self::new(domain, port))
    }
}

#[cfg(test)]
mod tests {
    use crate::ParseError::InvalidDomain;
    use crate::{DomainRef, EndpointRef, ParseError};

    #[test]
    fn try_from_str() {
        let result: Result<EndpointRef, ParseError> = EndpointRef::try_from("localhost:80");
        let expected: Result<EndpointRef, ParseError> = Ok(EndpointRef::new(DomainRef::LOCALHOST, 80));
        assert_eq!(result, expected);

        let result: Result<EndpointRef, ParseError> = EndpointRef::try_from("LocalHost:80");
        let expected: Result<EndpointRef, ParseError> = Err(InvalidDomain);
        assert_eq!(result, expected);
    }

    #[test]
    fn try_from_slice() {
        let test_cases: &[(&[u8], Result<EndpointRef, ParseError>)] = &[
            (
                "localhost:80".as_bytes(),
                Ok(EndpointRef::new(DomainRef::LOCALHOST, 80)),
            ),
            ("LocalHost:80".as_bytes(), Err(InvalidDomain)),
            (b"\xFF:80".as_slice(), Err(InvalidDomain)),
            ("ΓΌ:80".as_bytes(), Err(InvalidDomain)),
        ];

        for (input, expected) in test_cases {
            let result: Result<EndpointRef, ParseError> = EndpointRef::try_from(*input);
            assert_eq!(result, *expected, "input={:?}", input);
        }
    }

    /// Each canonical string must parse and display back to the exact same string.
    #[test]
    fn round_trip() {
        let canonical: &[&str] = &["localhost:80", "example.com:443", "a.b.c:65535", "x:0"];

        for input in canonical {
            let value: EndpointRef = EndpointRef::try_from(*input).unwrap();
            assert_eq!(value.to_string(), *input, "input={}", input);
        }
    }
}