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
//! Phone type for Rust.

use phone_number_verifier::{
    verify_phone_number_with_country_code, verify_phone_number_without_country_code,
};
use std::fmt::{Display, Formatter};
use std::ops::Deref;

#[cfg(feature = "serde")]
pub mod serde_feature;

#[derive(Debug)]
pub struct ErrorInvalidPhone;

impl Display for ErrorInvalidPhone {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        write!(f, "error: invalid phone format")
    }
}

impl std::error::Error for ErrorInvalidPhone {}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Phone(String);

impl Phone {
    pub fn new(phone: &str) -> Result<Self, ErrorInvalidPhone> {
        if !verify_phone_number_without_country_code(phone) {
            return Err(ErrorInvalidPhone);
        }

        Ok(Self(phone.to_string()))
    }

    pub fn new_with_country(phone: &str) -> Result<Self, ErrorInvalidPhone> {
        if !verify_phone_number_with_country_code(phone) {
            return Err(ErrorInvalidPhone);
        }

        Ok(Self(phone.to_string()))
    }

    pub fn as_str(&self) -> &str {
        &self.0
    }
}

impl Display for Phone {
    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
        Display::fmt(&self.0, f)
    }
}

impl Deref for Phone {
    type Target = String;
    fn deref(&self) -> &Self::Target {
        &self.0
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn constructor_works() {
        let phone_result = Phone::new("111-111-1111");
        assert!(phone_result.is_ok(), "Invalid generic phone");

        let phone_result = Phone::new_with_country("+52 111 111 1111");
        assert!(phone_result.is_ok(), "Invalid phone with country code");
    }
}