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
93
94
95
96
97
98
99
100
101
102
103
104
105
use ::serde::Deserialize;
use ::serde::Deserializer;
use ::serde::Serialize;
use ::serde::Serializer;

use crate::Email;
use crate::EmailVisitor;

impl Serialize for Email {
    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
    where
        S: Serializer,
    {
        serializer.serialize_str(&self.raw_email)
    }
}

impl<'de> Deserialize<'de> for Email {
    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
    where
        D: Deserializer<'de>,
    {
        deserializer.deserialize_string(EmailVisitor)
    }
}

#[cfg(test)]
mod test_serialisation {
    use super::*;
    use ::serde::Deserialize;
    use ::serde::Serialize;
    use ::serde_json;

    #[derive(Serialize, Deserialize)]
    struct Person {
        name: String,
        email: Email,
    }

    #[test]
    fn it_should_serialise_email_from_string() {
        let email = Email::from_str("john@example.com").unwrap();
        let raw = serde_json::to_string(&email).unwrap();

        assert_eq!(raw, r#""john@example.com""#);
    }
}

#[cfg(test)]
mod test_deserialisation {
    use super::*;
    use ::serde::Deserialize;
    use ::serde::Serialize;
    use ::serde_json;

    #[derive(Serialize, Deserialize)]
    struct Person {
        name: String,
        email: Email,
    }

    #[test]
    fn it_should_not_deserialise_non_email_from_string() {
        let raw_email = "donkeys";

        let result = serde_json::from_str::<Email>(raw_email);

        assert!(result.is_err());
    }

    #[test]
    fn it_should_deserialise_not_structs_from_raw_with_non_email() {
        let data = r#"
        {
            "name": "John Doe",
            "email": "donkeys"
        }"#;

        let result = serde_json::from_str::<Person>(data);

        assert!(result.is_err());
    }

    #[test]
    fn it_should_deserialise_email_from_string() {
        let raw_json_email = r#""john@example.com""#;

        let email: Email = serde_json::from_str(raw_json_email).unwrap();

        assert_eq!(email, Email::from_str("john@example.com").unwrap());
    }

    #[test]
    fn it_should_deserialise_structs_from_raw() {
        let data = r#"
        {
            "name": "John Doe",
            "email": "john@example.com"
        }"#;

        let person = serde_json::from_str::<Person>(data).unwrap();

        assert_eq!(person.email, Email::from_str("john@example.com").unwrap());
    }
}