icu_provider_source/currency/
essentials.rs

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
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
// 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::cldr_serde;
use crate::decimal::decimal_pattern::DecimalPattern;
use crate::IterableDataProviderCached;
use crate::SourceDataProvider;

use std::borrow::Cow;

use icu_pattern::DoublePlaceholderPattern;
use tinystr::TinyAsciiStr;

use std::collections::BTreeMap;
use std::collections::HashMap;
use std::collections::HashSet;
use std::str::FromStr;
use tinystr::UnvalidatedTinyAsciiStr;
use zerovec::VarZeroVec;
use zerovec::ZeroMap;

use icu_pattern::DoublePlaceholderKey;
use icu_pattern::PatternItemCow;

use icu::experimental::dimension::provider::ule::MAX_PLACEHOLDER_INDEX;
use icu::properties::props::{GeneralCategory, GeneralCategoryGroup};
use icu::properties::CodePointMapData;
use icu_provider::DataProvider;

use icu::experimental::dimension::provider::currency::*;
use icu_provider::prelude::*;

/// Returns the pattern selection for a currency.
/// For example:
///    if the pattern is ¤#,##0.00 and the symbol is EGP,
///    this means the return value will be PatternSelection::StandardAlphaNextToNumber
///    because the character closes to the number is a letter.
/// NOTE:
///   placeholder_value must not be empty.
fn currency_pattern_selection(
    provider: &SourceDataProvider,
    pattern: &str,
    placeholder_value: &str,
) -> Result<PatternSelection, DataError> {
    if placeholder_value.is_empty() {
        return Err(DataError::custom("Place holder value must not be empty"));
    }

    let currency_sign = '¤';
    let currency_sign_index = pattern.find(currency_sign).unwrap();
    let first_num_index = pattern.find(['0', '#']).unwrap();
    let last_num_index = pattern.rfind(['0', '#']).unwrap();

    let letters_set = CodePointMapData::<GeneralCategory>::try_new_unstable(provider)?
        .as_borrowed()
        .get_set_for_value_group(GeneralCategoryGroup::Letter);

    let char_closer_to_number = if currency_sign_index < first_num_index {
        placeholder_value.chars().next_back().unwrap()
    } else if currency_sign_index > last_num_index {
        placeholder_value.chars().next().unwrap()
    } else {
        return Err(DataError::custom(
            "Currency sign must not be in the middle of the pattern",
        ));
    };

    Ok(
        if letters_set.as_borrowed().contains(char_closer_to_number) {
            PatternSelection::StandardAlphaNextToNumber
        } else {
            PatternSelection::Standard
        },
    )
}

impl DataProvider<CurrencyEssentialsV1Marker> for SourceDataProvider {
    fn load(
        &self,
        req: DataRequest,
    ) -> Result<DataResponse<CurrencyEssentialsV1Marker>, DataError> {
        self.check_req::<CurrencyEssentialsV1Marker>(req)?;

        let currencies_resource: &cldr_serde::currencies::data::Resource =
            self.cldr()?
                .numbers()
                .read_and_parse(req.id.locale, "currencies.json")?;

        let numbers_resource: &cldr_serde::numbers::Resource = self
            .cldr()?
            .numbers()
            .read_and_parse(req.id.locale, "numbers.json")?;

        let result = extract_currency_essentials(self, currencies_resource, numbers_resource);

        Ok(DataResponse {
            metadata: Default::default(),
            payload: DataPayload::from_owned(result?),
        })
    }
}

impl IterableDataProviderCached<CurrencyEssentialsV1Marker> for SourceDataProvider {
    fn iter_ids_cached(&self) -> Result<HashSet<DataIdentifierCow<'static>>, DataError> {
        Ok(self
            .cldr()?
            .numbers()
            .list_locales()?
            .map(DataIdentifierCow::from_locale)
            .collect())
    }
}

fn extract_currency_essentials<'data>(
    provider: &SourceDataProvider,
    currencies_resource: &cldr_serde::currencies::data::Resource,
    numbers_resource: &cldr_serde::numbers::Resource,
) -> Result<CurrencyEssentialsV1<'data>, DataError> {
    let currencies = &currencies_resource.main.value.numbers.currencies;

    // TODO(#3838): these patterns might be numbering system dependent.
    let currency_formats = &&numbers_resource
        .main
        .value
        .numbers
        .numsys_data
        .currency_patterns
        .get("latn")
        .ok_or_else(|| DataError::custom("Could not find the standard pattern"))?;

    let standard = &currency_formats.standard;
    let standard_alpha_next_to_number = match &currency_formats.standard_alpha_next_to_number {
        Some(standard_alpha_next_to_number) => standard_alpha_next_to_number,
        None => "",
    };

    let mut currency_patterns_map =
        BTreeMap::<UnvalidatedTinyAsciiStr<3>, CurrencyPatternConfig>::new();
    let mut currency_patterns_standard_none =
        BTreeMap::<UnvalidatedTinyAsciiStr<3>, CurrencyPatternConfig>::new();
    let mut currency_patterns_standard_next_to_num =
        BTreeMap::<UnvalidatedTinyAsciiStr<3>, CurrencyPatternConfig>::new();
    let mut placeholders = Vec::<&str>::new();
    // A map to check if the place holder is already in the placeholders vector.
    let mut placeholders_checker_map = HashMap::<&str, u16>::new();

    for (iso, currency_pattern) in currencies {
        let short_placeholder_value = currency_pattern.short.as_ref().map(|short_placeholder| {
            if let Some(&index) = placeholders_checker_map.get(short_placeholder.as_str()) {
                PlaceholderValue::Index(index)
            } else if short_placeholder == iso {
                PlaceholderValue::ISO
            } else {
                let index = placeholders.len() as u16;
                placeholders.push(short_placeholder.as_str());
                placeholders_checker_map.insert(short_placeholder.as_str(), index);
                PlaceholderValue::Index(index)
            }
        });

        let narrow_placeholder_value = currency_pattern.narrow.as_ref().map(|narrow_placeholder| {
            if let Some(&index) = placeholders_checker_map.get(narrow_placeholder.as_str()) {
                PlaceholderValue::Index(index)
            } else if narrow_placeholder == iso {
                PlaceholderValue::ISO
            } else {
                let index = placeholders.len() as u16;
                placeholders.push(narrow_placeholder.as_ref());
                placeholders_checker_map.insert(narrow_placeholder.as_str(), index);
                PlaceholderValue::Index(index)
            }
        });

        // Ensure that short_placeholder_value and narrow_placeholder_value do not exceed MAX_PLACEHOLDER_INDEX.
        if let Some(PlaceholderValue::Index(index)) = short_placeholder_value {
            if index > MAX_PLACEHOLDER_INDEX {
                return Err(DataError::custom(
                    "short_placeholder_value exceeded MAX_PLACEHOLDER_INDEX",
                ));
            }
        }
        if let Some(PlaceholderValue::Index(index)) = narrow_placeholder_value {
            if index > MAX_PLACEHOLDER_INDEX {
                return Err(DataError::custom(
                    "narrow_placeholder_value exceeded MAX_PLACEHOLDER_INDEX",
                ));
            }
        }

        let determine_pattern_selection =
            |placeholder_index: Option<PlaceholderValue>| -> Result<PatternSelection, DataError> {
                if standard_alpha_next_to_number.is_empty() {
                    Ok(PatternSelection::Standard)
                } else {
                    let placeholder_value = match placeholder_index {
                        Some(PlaceholderValue::Index(index)) => {
                            placeholders.get(index as usize).unwrap()
                        }
                        Some(PlaceholderValue::ISO) | None => iso.as_str(),
                    };
                    currency_pattern_selection(provider, standard, placeholder_value)
                }
            };

        let short_pattern_selection: PatternSelection =
            determine_pattern_selection(short_placeholder_value)?;
        let narrow_pattern_selection: PatternSelection =
            determine_pattern_selection(narrow_placeholder_value)?;

        let currency_patterns = CurrencyPatternConfig {
            short_pattern_selection,
            narrow_pattern_selection,
            short_placeholder_value,
            narrow_placeholder_value,
        };

        let iso = TinyAsciiStr::try_from_str(iso).unwrap().to_unvalidated();
        match (short_pattern_selection, narrow_pattern_selection) {
            (PatternSelection::Standard, PatternSelection::Standard)
                if short_placeholder_value.is_none() && narrow_placeholder_value.is_none() =>
            {
                currency_patterns_standard_none.insert(iso, currency_patterns);
            }
            (
                PatternSelection::StandardAlphaNextToNumber,
                PatternSelection::StandardAlphaNextToNumber,
            ) if short_placeholder_value.is_none() && narrow_placeholder_value.is_none() => {
                currency_patterns_standard_next_to_num.insert(iso, currency_patterns);
            }
            _ => {
                currency_patterns_map.insert(iso, currency_patterns);
            }
        }
    }

    let default_pattern_config =
        if currency_patterns_standard_none.len() <= currency_patterns_standard_next_to_num.len() {
            currency_patterns_map.extend(currency_patterns_standard_none);
            CurrencyPatternConfig {
                short_pattern_selection: PatternSelection::StandardAlphaNextToNumber,
                narrow_pattern_selection: PatternSelection::StandardAlphaNextToNumber,
                short_placeholder_value: None,
                narrow_placeholder_value: None,
            }
        } else {
            currency_patterns_map.extend(currency_patterns_standard_next_to_num);
            CurrencyPatternConfig {
                short_pattern_selection: PatternSelection::Standard,
                narrow_pattern_selection: PatternSelection::Standard,
                short_placeholder_value: None,
                narrow_placeholder_value: None,
            }
        };

    /// Create a `DoublePlaceholderPattern` from a string pattern.
    fn create_pattern<'data>(
        pattern: &str,
    ) -> Result<Option<Cow<'data, DoublePlaceholderPattern>>, DataError> {
        if pattern.is_empty() {
            return Ok(None);
        }

        let decimal_pattern = DecimalPattern::from_str(pattern).map_err(|e| {
            DataError::custom("Could not parse the pattern").with_display_context(&e)
        })?;

        // TODO(#4677): Handle the negative sub pattern.
        let pattern_items = decimal_pattern
            .positive
            .to_pattern_items()
            .into_iter()
            .flat_map(|item| match item {
                PatternItemCow::Placeholder(_) => vec![item],
                PatternItemCow::Literal(s) if s.contains('¤') => {
                    itertools::Itertools::intersperse(
                        s.split('¤')
                            .map(|s| PatternItemCow::Literal(s.to_string().into())),
                        PatternItemCow::Placeholder(DoublePlaceholderKey::Place1),
                    )
                    .collect()
                }
                PatternItemCow::Literal(s) => vec![PatternItemCow::Literal(s)],
            });

        DoublePlaceholderPattern::try_from_items(pattern_items.into_iter())
            .map_err(|e| {
                DataError::custom("Could not parse standard pattern").with_display_context(&e)
            })
            .map(Cow::Owned)
            .map(Some)
    }

    Ok(CurrencyEssentialsV1 {
        pattern_config_map: ZeroMap::from_iter(currency_patterns_map.iter()),
        standard_pattern: create_pattern(standard.as_str())?,
        standard_alpha_next_to_number_pattern: create_pattern(standard_alpha_next_to_number)?,
        placeholders: VarZeroVec::from(&placeholders),
        default_pattern_config,
    })
}

#[test]
fn test_basic() {
    use tinystr::tinystr;
    use writeable::assert_writeable_eq;

    fn get_placeholders_of_currency(
        iso_code: UnvalidatedTinyAsciiStr<3>,
        locale: &DataResponse<CurrencyEssentialsV1Marker>,
        placeholders: &VarZeroVec<'_, str>,
    ) -> (String, String) {
        let default = CurrencyPatternConfig {
            short_pattern_selection: PatternSelection::Standard,
            narrow_pattern_selection: PatternSelection::Standard,
            short_placeholder_value: None,
            narrow_placeholder_value: None,
        };
        let owned = locale.payload.get().to_owned();
        let currency_pattern: CurrencyPatternConfig = owned
            .pattern_config_map
            .get_copied(&iso_code)
            .unwrap_or(default);

        let short_placeholder = match currency_pattern.short_placeholder_value {
            Some(PlaceholderValue::Index(index)) => placeholders
                .get(index as usize)
                .unwrap_or(&iso_code.try_into_tinystr().unwrap())
                .to_string(),
            Some(PlaceholderValue::ISO) => iso_code.try_into_tinystr().unwrap().to_string(),
            None => "".to_string(),
        };

        let narrow_placeholder = match currency_pattern.narrow_placeholder_value {
            Some(PlaceholderValue::Index(index)) => placeholders
                .get(index as usize)
                .unwrap_or(&iso_code.try_into_tinystr().unwrap())
                .to_string(),
            Some(PlaceholderValue::ISO) => iso_code.try_into_tinystr().unwrap().to_string(),
            None => "".to_string(),
        };

        (short_placeholder, narrow_placeholder)
    }

    use icu::experimental::dimension::provider::currency::*;
    use icu::locale::langid;

    let provider = SourceDataProvider::new_testing();

    let en: DataResponse<CurrencyEssentialsV1Marker> = provider
        .load(DataRequest {
            id: DataIdentifierBorrowed::for_locale(&langid!("en").into()),
            ..Default::default()
        })
        .unwrap();

    let en_payload = en.payload.get();

    assert_writeable_eq!(
        en_payload
            .standard_pattern
            .as_ref()
            .unwrap()
            .interpolate((3, "$")),
        "$3"
    );
    assert_writeable_eq!(
        en_payload
            .standard_alpha_next_to_number_pattern
            .as_ref()
            .unwrap()
            .interpolate((3, "$")),
        "$\u{a0}3"
    );

    let (en_usd_short, en_usd_narrow) = get_placeholders_of_currency(
        tinystr!(3, "USD").to_unvalidated(),
        &en,
        &en_payload.placeholders,
    );
    assert_eq!(en_usd_short, "$");
    assert_eq!(en_usd_narrow, "$");

    let (en_egp_short, en_egp_narrow) = get_placeholders_of_currency(
        tinystr!(3, "EGP").to_unvalidated(),
        &en,
        &en_payload.placeholders,
    );
    assert_eq!(en_egp_short, "");
    assert_eq!(en_egp_narrow, "E£");

    let ar_eg: DataResponse<CurrencyEssentialsV1Marker> = provider
        .load(DataRequest {
            id: DataIdentifierBorrowed::for_locale(&langid!("ar-EG").into()),
            ..Default::default()
        })
        .unwrap();

    let ar_eg_payload = ar_eg.payload.get();
    assert_writeable_eq!(
        ar_eg_payload
            .standard_pattern
            .as_ref()
            .unwrap()
            .interpolate((3, "$")),
        "\u{200f}3\u{a0}$"
    );
    assert!(ar_eg
        .payload
        .get()
        .standard_alpha_next_to_number_pattern
        .is_none());

    let (ar_eg_egp_short, ar_eg_egp_narrow) = get_placeholders_of_currency(
        tinystr!(3, "EGP").to_unvalidated(),
        &ar_eg,
        &ar_eg_payload.placeholders,
    );
    assert_eq!(ar_eg_egp_short, "ج.م.\u{200f}");
    assert_eq!(ar_eg_egp_narrow, "E£");

    let (ar_eg_usd_short, ar_eg_usd_narrow) = get_placeholders_of_currency(
        tinystr!(3, "USD").to_unvalidated(),
        &ar_eg,
        &ar_eg_payload.placeholders,
    );
    assert_eq!(ar_eg_usd_short, "US$");
    assert_eq!(ar_eg_usd_narrow, "US$");
}