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
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
use std::fmt::Display;

use serde::{Deserialize, Serialize};

#[derive(PartialEq, Eq, Clone, Debug, Serialize, Deserialize)]
pub struct ProfileName<S> {
    pub given_name: S,
    pub family_name: Option<S>,
}

// Implements ProfileName::getJoinedName
impl<S: AsRef<str>> Display for ProfileName<S> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        let given_name = self.given_name.as_ref();
        match (
            self.given_name.as_ref().is_empty(),
            self.family_name.as_ref().map(AsRef::as_ref),
        ) {
            (true, None) => Ok(()),
            (false, None) => write!(f, "{}", given_name),
            (true, Some(family_name)) => write!(f, "{}", family_name),
            (false, Some(family_name)) => {
                if self.is_cjkv() {
                    write!(f, "{} {}", family_name, given_name)
                } else {
                    write!(f, "{} {}", given_name, family_name)
                }
            },
        }
    }
}

impl<S: AsRef<str>> ProfileName<S> {
    pub fn as_ref(&self) -> ProfileName<&str> {
        ProfileName {
            given_name: self.given_name.as_ref(),
            family_name: self.family_name.as_ref().map(|x| x.as_ref()),
        }
    }

    pub fn is_cjkv(&self) -> bool {
        // XXX insert unicode magic here
        false
    }

    pub fn serialize(&self) -> Vec<u8> {
        if let Some(family_name) = self.family_name.as_ref() {
            self.given_name
                .as_ref()
                .as_bytes()
                .iter()
                .chain(std::iter::once(&0u8))
                .chain(family_name.as_ref().as_bytes())
                .copied()
                .collect()
        } else {
            self.given_name.as_ref().as_bytes().into()
        }
    }

    pub fn is_empty(&self) -> bool {
        self.given_name.as_ref() == "" && self.family_name.is_none()
    }
}

impl ProfileName<String> {
    /// Copying deserialization of a ProfileName.
    pub fn deserialize(
        data: &[u8],
    ) -> Result<Option<Self>, std::str::Utf8Error> {
        let parts: Vec<&[u8]> = data.split(|x| *x == 0).collect();
        match parts.len() {
            0 => Ok(None),
            1 => Ok(Some(Self {
                given_name: std::str::from_utf8(parts[0])?.to_string(),
                family_name: None,
            })),
            _ => Ok(Some(Self {
                given_name: std::str::from_utf8(parts[0])?.to_string(),
                family_name: Some(std::str::from_utf8(parts[1])?.to_string()),
            })),
        }
    }
}

impl<'de> ProfileName<&'de str> {
    pub fn empty() -> Self {
        ProfileName {
            given_name: "",
            family_name: None,
        }
    }

    /// Zero-copy deserialization of a ProfileName.
    pub fn deserialize<'inp: 'de>(
        data: &'inp [u8],
    ) -> Result<Option<Self>, std::str::Utf8Error> {
        let parts: Vec<&[u8]> = data.split(|x| *x == 0).collect();
        match parts.len() {
            0 => Ok(None),
            1 => Ok(Some(Self {
                given_name: std::str::from_utf8(parts[0])?,
                family_name: None,
            })),
            _ => Ok(Some(Self {
                given_name: std::str::from_utf8(parts[0])?,
                family_name: Some(std::str::from_utf8(parts[1])?),
            })),
        }
    }
}

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

    #[test]
    fn roundtrip_name() {
        let names = [
            ("foo", Some("bar")),
            ("foo", None),
            ("", None),
            ("", Some("bar")),
        ];

        for &(given_name, family_name) in &names {
            let uut_name = ProfileName::<&str> {
                given_name,
                family_name,
            };
            let ser = uut_name.serialize();
            let deserialized =
                ProfileName::<&str>::deserialize(&ser).expect("utf8");
            assert_eq!(Some(uut_name), deserialized);
        }
    }
}