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
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
use std::fmt;
use std::fmt::Display;

#[cfg(feature = "read_write")]
use crate::read_write::component::Component;

/// A name
///
/// Stored with all the properties required for the
/// VCard specification.
///
/// Name implements `Display` which allows it to
/// be formatted in the style of: "Prefix Given
/// Additional(s) Family Suffix." Additional names
/// will be separated by spaces.
///
/// # Examples
///
/// Create a contact with the name "John Doe"
///
/// ```rust
/// use contack::{Name, Contact};
/// 
/// let contact = Contact::new(Name {
///    given: vec!["John".to_string()],
///    family: vec!["Doe".to_string()],
///    ..Default::default()
/// });
/// ```
#[derive(Debug, Clone, PartialEq, PartialOrd, Default)]
pub struct Name {
    /// The given name.
    ///
    /// Sometimes called a first name.
    /// The "John" in "John Doe".
    pub given: Vec<String>,
    /// Additional names.
    ///
    /// Sometimes are called "middle" names. You
    /// often have more than one.
    pub additional: Vec<String>,
    /// The family name.
    ///
    /// Sometimes called "last" names. The "Doe" in "John Doe"
    pub family: Vec<String>,
    /// Prefixes.
    ///
    /// Often times these are things such as "Ms", "Mr" or "Mx",
    /// although in some cases they can be more advanced, such as
    /// "Doctor" or "Seargant".
    pub prefixes: Vec<String>,
    /// Suffixes
    ///
    /// The opposite of prefixes. An example is "Esq".
    /// Not that common  in English.
    pub suffixes: Vec<String>,
}

impl Name {
    /// Creates a new `Name`
    ///
    /// For most cases it is probably clearer
    /// to instantiate the name manually for clarity.
    ///
    /// # Example
    ///
    /// Create a new name for "John Doe"
    /// 
    /// ```rust
    /// use contack::Name;
    /// 
    /// let name = Name::new(
    ///     Some("John".to_string()),
    ///     Some("Doe".to_string()),
    ///     None,
    ///     None,
    ///     None
    /// );
    /// ```
    #[must_use]
    pub fn new(
        given: Option<String>,
        additional: Option<String>,
        family: Option<String>,
        prefixes: Option<String>,
        suffixes: Option<String>,
    ) -> Self {
        Self {
            given: given.map_or(Vec::new(), |x| vec![x]),
            additional: additional.map_or(Vec::new(), |x| vec![x]),
            family: family.map_or(Vec::new(), |x| vec![x]),
            prefixes: prefixes.map_or(Vec::new(), |x| vec![x]),
            suffixes: suffixes.map_or(Vec::new(), |x| vec![x]),
        }
    }

    /// Converts the name to a single string escaped by spaces.
    ///
    /// Each subname is separated by a space, and if
    /// they contain a space they are prefixed with
    /// a `\ `. This only exists to be used in the sql
    /// backend because of backwards compatability.
    ///
    /// # Example
    ///
    /// Escape someone who has a name with spaces.
    /// 
    /// ```rust
    /// use contack::Name;
    /// let name = vec!["Mary Rose", "Bee", "a\\"];
    /// assert_eq!(
    ///     Some(String::from(r#"Mary\ Rose Bee a\\"#)),
    ///     Name::escape_with_spaces(name.into_iter())
    /// );
    /// ```
    pub fn escape_with_spaces<'a>(vec: impl Iterator<Item=&'a str>) -> Option<String> {
        let mut string = String::new();
        for substring in vec {
            string.push_str(&substring.replace('\\', "\\\\").replace(' ', r#"\ "#));
            string.push(' ');
        }
        string.pop();
        if string.is_empty() {
            None
        } else {
            Some(string)
        }
    }

    /// Unescapes a name with spaces.
    ///
    /// Performs the opposite of [`Name::escape_with_spaces`]
    ///
    /// # Example
    ///
    /// Unescape someone who has a name with spaces.
    /// 
    /// ```rust
    /// use contack::Name;
    /// let name = r#"Mary\ Rose Bee a\\"#;
    /// assert_eq!(vec!["Mary Rose", "Bee", "a\\"], Name::unescape_with_spaces(name));
    /// ```
    ///
    /// # Panics
    ///
    /// It doesn't, just clippy thinks it does.
    #[must_use] pub fn unescape_with_spaces(string: &str) -> Vec<String> {
        let mut in_escape = false;
        let mut vec = vec![String::new()];
        for chr in string.chars() {
            match chr {
                '\\' if in_escape => vec.last_mut().unwrap().push('\\'),
                '\\' if !in_escape => in_escape = true,
                ' ' if in_escape => vec.last_mut().unwrap().push(' '),
                ' ' if !in_escape => vec.push(String::new()),
                other => {
                    vec.last_mut().unwrap().push(other);
                    in_escape = false;
                }
            }
        }
        vec
    }
}

impl Display for Name {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let mut string = String::new();
        if !self.prefixes.is_empty() {
            string.push(' ');
            string.push_str(&self.prefixes.join(" "))
        }
        if !self.given.is_empty() {
            string.push(' ');
            string.push_str(&self.given.join(" "))
        }
        if !self.additional.is_empty() {
            string.push(' ');
            string.push_str(&self.additional.join(" "))
        }
        if !self.family.is_empty() {
            string.push(' ');
            string.push_str(&self.family.join(" "))
        }
        if !self.suffixes.is_empty() {
            string.push(' ');
            string.push_str(&self.suffixes.join(" "))
        }

        write!(f, "{}", string.trim())
    }
}

/// Allows a name to be translated into a component.
///
/// You should never need to call this directly and should
/// prefer turning a whole contact into a VCard.
///
/// # Example
///
/// Convert a name into a contact and print it out.
/// 
/// 
/// ```rust
/// use contack::Name;
/// use contack::read_write::component::Component;
/// 
/// let name = Name {
///    given: vec!["John".to_string()],
///    family: vec!["Doe".to_string()],
///    ..Default::default()
/// };
///
/// let component: Component = name.into();
///
/// // NAME:Doe;John;;;;
/// println!("{}", component);
/// ```
#[cfg(feature = "read_write")]
#[cfg_attr(feature = "dox", doc(cfg(feature = "read_write")))]
impl From<Name> for Component {
    fn from(name: Name) -> Self {
        Self {
            name: "N".to_string(),
            values: vec![
                name.family,
                name.given,
                name.additional,
                name.prefixes,
                name.suffixes,
            ],
            ..Self::default()
        }
    }
}

#[cfg(feature = "read_write")]
impl From<Component> for Name {
    fn from(mut comp: Component) -> Self {
        comp.values.truncate(5);
        Self {
            suffixes: comp.values.pop().unwrap_or_default(),
            prefixes: comp.values.pop().unwrap_or_default(),
            additional: comp.values.pop().unwrap_or_default(),
            given: comp.values.pop().unwrap_or_default(),
            family: comp.values.pop().unwrap_or_default(),
        }
    }
}