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
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
// 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 displaydoc::Display;
use icu_locale::ParseError;
use icu_provider::DataLocale;
use std::hash::Hash;
use std::str::FromStr;
use writeable::Writeable;

/// A family of locales to export.
#[derive(Debug, Clone, PartialEq, Eq, Hash)]
pub struct DataLocaleFamily {
    pub(crate) locale: Option<DataLocale>,
    pub(crate) annotations: DataLocaleFamilyAnnotations,
}

impl DataLocaleFamily {
    /// The family containing all ancestors and descendants of the selected locale.
    ///
    /// This is the recommended family type since it reflects regional preferences.
    ///
    /// For example, the family `::with_descendants("en-001")` contains:
    ///
    /// - Self: "en-001"
    /// - Ancestors: "und", "en"
    /// - Descendants: "en-GB", "en-ZA", ...
    ///
    /// Stylized on the CLI as: "en-US"
    ///
    /// The `und` locale is treated specially and behaves like `::single("und")`.
    pub fn with_descendants(locale: DataLocale) -> Self {
        let annotations = if locale.is_default() {
            DataLocaleFamilyAnnotations::single()
        } else {
            DataLocaleFamilyAnnotations::with_descendants()
        };

        Self {
            locale: Some(locale),
            annotations,
        }
    }

    /// The family containing all ancestors of the selected locale.
    ///
    /// This family type does not include regional variants unless the selected locale is itself
    /// a regional variant.
    ///
    /// For example, the family `::without_descendants("en-001")` contains:
    ///
    /// - Self: "en-001"
    /// - Ancestors: "und", "en"
    ///
    /// Stylized on the CLI as: "^en-US"
    ///
    /// The `und` locale is treated specially and behaves like `::single("und")`.
    pub fn without_descendants(locale: DataLocale) -> Self {
        let annotations = if locale.is_default() {
            DataLocaleFamilyAnnotations::single()
        } else {
            DataLocaleFamilyAnnotations::without_descendants()
        };
        Self {
            locale: Some(locale),
            annotations,
        }
    }

    /// The family containing all descendants of the selected locale.
    ///
    /// This family may be useful if the root locale is not desired.
    ///
    /// For example, the family `::without_ancestors("en-001")` contains:
    ///
    /// - Self: "en-001"
    /// - Descendants: "en-GB", "en-ZA", ...
    ///
    /// but it does _not_ contain the ancestors "en" and "und".
    ///
    /// Stylized on the CLI as: "%en-US"
    ///
    /// The `und` locale is treated specially and behaves like `::single("und")`.
    pub fn without_ancestors(locale: DataLocale) -> Self {
        let annotations = if locale.is_default() {
            DataLocaleFamilyAnnotations::single()
        } else {
            DataLocaleFamilyAnnotations::without_ancestors()
        };
        Self {
            locale: Some(locale),
            annotations,
        }
    }

    /// The family containing only the selected locale.
    ///
    /// For example, the family `::single("en-001")` contains only "en-001".
    ///
    /// Stylized on the CLI as: "@en-US"
    pub const fn single(locale: DataLocale) -> Self {
        Self {
            locale: Some(locale),
            annotations: DataLocaleFamilyAnnotations::single(),
        }
    }

    /// The family containing all locales.
    ///
    /// Stylized on the CLI as: "full"
    pub const FULL: Self = Self {
        locale: None,
        annotations: DataLocaleFamilyAnnotations {
            include_ancestors: false,
            include_descendants: true,
        },
    };
}

impl Writeable for DataLocaleFamily {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
        if let Some(locale) = self.locale.as_ref() {
            self.annotations.write_to(sink)?;
            locale.write_to(sink)
        } else {
            sink.write_str("full")
        }
    }

    fn writeable_length_hint(&self) -> writeable::LengthHint {
        if let Some(locale) = self.locale.as_ref() {
            self.annotations.writeable_length_hint() + locale.writeable_length_hint()
        } else {
            writeable::LengthHint::exact(4)
        }
    }
}

writeable::impl_display_with_writeable!(DataLocaleFamily);

/// Inner fields of a [`DataLocaleFamily`].
#[derive(Debug, Copy, Clone, PartialEq, Eq, Hash)]
pub(crate) struct DataLocaleFamilyAnnotations {
    pub(crate) include_ancestors: bool,
    pub(crate) include_descendants: bool,
}

impl DataLocaleFamilyAnnotations {
    #[inline]
    pub(crate) const fn with_descendants() -> Self {
        Self {
            include_ancestors: true,
            include_descendants: true,
        }
    }

    #[inline]
    pub(crate) const fn without_descendants() -> Self {
        Self {
            include_ancestors: true,
            include_descendants: false,
        }
    }

    #[inline]
    pub(crate) const fn without_ancestors() -> Self {
        Self {
            include_ancestors: false,
            include_descendants: true,
        }
    }

    #[inline]
    pub(crate) const fn single() -> Self {
        Self {
            include_ancestors: false,
            include_descendants: false,
        }
    }
}

impl Writeable for DataLocaleFamilyAnnotations {
    fn write_to<W: core::fmt::Write + ?Sized>(&self, sink: &mut W) -> core::fmt::Result {
        match (self.include_ancestors, self.include_descendants) {
            (true, true) => Ok(()),
            (true, false) => sink.write_char('^'),
            (false, true) => sink.write_char('%'),
            (false, false) => sink.write_char('@'),
        }
    }

    fn writeable_length_hint(&self) -> writeable::LengthHint {
        writeable::LengthHint::exact(match (self.include_ancestors, self.include_descendants) {
            (true, true) => 0,
            _ => 1,
        })
    }
}

/// An error while parsing a [`DataLocaleFamily`].
#[derive(Debug, Copy, Clone, PartialEq, Display)]
#[non_exhaustive]
pub enum DataLocaleFamilyParseError {
    /// An error bubbled up from parsing a [`DataLocale`].
    #[displaydoc("{0}")]
    Locale(ParseError),
    /// Some other error specific to parsing the family, such as an invalid lead byte.
    #[displaydoc("Invalid locale family")]
    InvalidFamily,
}

impl From<ParseError> for DataLocaleFamilyParseError {
    fn from(err: ParseError) -> Self {
        Self::Locale(err)
    }
}

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

impl DataLocaleFamily {
    /// Parses a [`DataLocaleFamily`] from a UTF-8 slice.
    pub fn try_from_utf8(code_units: &[u8]) -> Result<Self, DataLocaleFamilyParseError> {
        if code_units == b"full" {
            return Ok(Self::FULL);
        }
        let (annotation, mut locale) = code_units
            .split_first()
            .ok_or(DataLocaleFamilyParseError::InvalidFamily)?;
        let annotations = match annotation {
            b'^' => DataLocaleFamilyAnnotations::without_descendants(),
            b'%' => DataLocaleFamilyAnnotations::without_ancestors(),
            b'@' => DataLocaleFamilyAnnotations::single(),
            _ => {
                locale = code_units;
                DataLocaleFamilyAnnotations::with_descendants()
            }
        };

        Ok(Self {
            locale: Some(DataLocale::try_from_utf8(locale)?),
            annotations,
        })
    }

    #[inline]
    /// Parses a [`DataLocaleFamily`].
    pub fn try_from_str(s: &str) -> Result<Self, DataLocaleFamilyParseError> {
        Self::try_from_utf8(s.as_bytes())
    }
}

impl FromStr for DataLocaleFamily {
    type Err = DataLocaleFamilyParseError;
    #[inline]
    fn from_str(s: &str) -> Result<Self, Self::Err> {
        Self::try_from_str(s)
    }
}

#[test]
fn test_locale_family_parsing() {
    let valid_families = ["und", "de-CH", "^es", "@pt-BR", "%en-001", "full"];
    let invalid_families = ["invalid", "@invalid", "-foo", "@full", "full-001"];
    for family_str in valid_families {
        let family = family_str.parse::<DataLocaleFamily>().unwrap();
        let family_to_str = family.to_string();
        assert_eq!(family_str, family_to_str);
    }
    for family_str in invalid_families {
        assert!(family_str.parse::<DataLocaleFamily>().is_err());
    }
}