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
// This file is part of ICU4X. For terms of use, please see the file
// called LICENSE at the top level of the ICU4X source tree
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ).

use crate::personnames::api::{
    NameField, NameFieldKind, PersonName, PersonNamesFormatterError, PreferredOrder,
};
use alloc::string::String;
use alloc::vec::Vec;
use icu_locale_core::Locale;
use litemap::LiteMap;

///
/// DefaultPersonName, default implementation provided for PersonNameFormatter.
pub struct DefaultPersonName {
    person_data: LiteMap<NameField, String>,
    locale: Option<Locale>,
    preferred_order: Option<PreferredOrder>,
}

impl PersonName for DefaultPersonName {
    fn name_locale(&self) -> Option<&Locale> {
        self.locale.as_ref()
    }

    fn preferred_order(&self) -> Option<&PreferredOrder> {
        self.preferred_order.as_ref()
    }

    fn get(&self, field: &NameField) -> &str {
        self.person_data
            .get(field)
            .map(String::as_ref)
            .unwrap_or("")
    }

    fn available_name_fields(&self) -> Vec<&NameField> {
        self.person_data.iter_keys().collect()
    }

    fn has_name_field_kind(&self, lookup_name_field: &NameFieldKind) -> bool {
        self.available_name_fields()
            .into_iter()
            .any(|field| &field.kind == lookup_name_field)
    }

    fn has_name_field(&self, lookup_name_field: &NameField) -> bool {
        self.available_name_fields()
            .into_iter()
            .any(|field| field == lookup_name_field)
    }
}

///
/// Default person name functions.
impl DefaultPersonName {
    ///
    /// Returns a new person name structure.
    pub fn new(
        person_data: LiteMap<NameField, String>,
        locale: Option<Locale>,
        preferred_order: Option<PreferredOrder>,
    ) -> Result<DefaultPersonName, PersonNamesFormatterError> {
        let result = DefaultPersonName {
            person_data,
            locale,
            preferred_order,
        };
        if !crate::personnames::formatter::validate_person_name(&result.available_name_fields()) {
            return Err(PersonNamesFormatterError::InvalidPersonName);
        }
        Ok(result)
    }
}