use std::net::{IpAddr, Ipv4Addr, Ipv6Addr};
use crate::{Problem, Rule};
#[must_use]
pub const fn ip() -> Ip {
Ip {
version: IpVersion::Either,
}
}
#[must_use]
pub const fn ipv4() -> Ip {
Ip { version: IpVersion::V4 }
}
#[must_use]
pub const fn ipv6() -> Ip {
Ip { version: IpVersion::V6 }
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Ip {
version: IpVersion,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum IpVersion {
Either,
V4,
V6,
}
impl IpVersion {
fn is_address(self, text: &str) -> bool {
match self {
Self::Either => text.parse::<IpAddr>().is_ok(),
Self::V4 => text.parse::<Ipv4Addr>().is_ok(),
Self::V6 => text.parse::<Ipv6Addr>().is_ok(),
}
}
fn problem(self) -> Problem {
match self {
Self::Either => Problem::Ip,
Self::V4 => Problem::Ipv4,
Self::V6 => Problem::Ipv6,
}
}
}
#[diagnostic::do_not_recommend]
impl<T: AsRef<str> + ?Sized> Rule<T> for Ip {
fn check(&self, value: &T) -> Result<(), Problem> {
if self.version.is_address(value.as_ref()) {
return Ok(());
}
Err(self.version.problem())
}
fn problem(&self) -> Option<Problem> {
Some(self.version.problem())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn each_ip_rule_says_the_version_a_string_must_be_an_address_of() {
assert_eq!(
(
Rule::<str>::problem(&ip()),
Rule::<str>::problem(&ipv4()),
Rule::<str>::problem(&ipv6())
),
(Some(Problem::Ip), Some(Problem::Ipv4), Some(Problem::Ipv6))
);
}
#[test]
fn an_ipv4_address_follows_the_rule() {
assert_eq!(ip().check("192.0.2.1"), Ok(()));
}
#[test]
fn an_ipv6_address_follows_the_rule() {
assert_eq!(ip().check("2001:db8::1"), Ok(()));
}
#[test]
fn a_string_that_is_not_an_ip_address_breaks_the_rule() {
assert_eq!(ip().check("192.0.2"), Err(Problem::Ip));
}
#[test]
fn an_ipv4_address_follows_the_ipv4_rule() {
assert_eq!(ipv4().check("192.0.2.1"), Ok(()));
}
#[test]
fn an_ipv6_address_breaks_the_ipv4_rule() {
assert_eq!(ipv4().check("2001:db8::1"), Err(Problem::Ipv4));
}
#[test]
fn an_ipv6_address_follows_the_ipv6_rule() {
assert_eq!(ipv6().check("2001:db8::1"), Ok(()));
}
#[test]
fn an_ipv4_address_breaks_the_ipv6_rule() {
assert_eq!(ipv6().check("192.0.2.1"), Err(Problem::Ipv6));
}
}