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
use std::convert::TryFrom;
use std::fmt::{Display, Formatter, Result as FmtResult};

use regex::Regex;

#[derive(Debug, PartialEq, Eq)]
pub enum DomainError {
    LabelLength,
    DomainNameLength,
    Regex,
}

#[derive(Debug, PartialEq, Clone, Eq, Hash)]
pub struct DomainName {
    pub(crate) domain_name: String,
}

impl DomainName {
    pub fn append_label(&mut self, label: &str) -> Result<(), DomainError> {
        lazy_static! {
            static ref LABEL_REGEX: Regex =
                Regex::new(r"[0-9a-zA-Z]([0-9a-zA-Z-]*[0-9a-zA-Z])?").unwrap();
        }

        let label_length = label.len();
        if label_length >= 64 {
            return Err(DomainError::LabelLength);
        }

        let domain_name_length = self.domain_name.len();
        if domain_name_length + label_length >= 256 {
            return Err(DomainError::DomainNameLength);
        }

        if LABEL_REGEX.is_match(label) {
            let label = label.to_lowercase();
            if &self.domain_name == "." {
                self.domain_name.insert_str(0, &label);
            } else {
                self.domain_name.push_str(&label);
                self.domain_name.push('.');
            }
            Ok(())
        } else {
            Err(DomainError::Regex)
        }
    }
}

impl TryFrom<&str> for DomainName {
    type Error = DomainError;

    fn try_from(string: &str) -> Result<Self, DomainError> {
        let string_relativ = if let Some(string_relativ) = string.strip_suffix('.') {
            string_relativ
        } else {
            string
        };

        let mut domain_name = DomainName::default();
        for label in string_relativ.split('.') {
            domain_name.append_label(label)?;
        }
        Ok(domain_name)
    }
}

impl Default for DomainName {
    fn default() -> Self {
        DomainName {
            domain_name: ".".to_string(),
        }
    }
}

impl From<DomainName> for String {
    fn from(domain_name: DomainName) -> Self {
        domain_name.domain_name
    }
}

impl PartialEq<&str> for DomainName {
    fn eq(&self, other: &&str) -> bool {
        self.domain_name == other.to_lowercase()
    }
}

impl Display for DomainName {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        write!(f, "{}", self.domain_name)
    }
}