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
// 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 ).

//! Experimental.

use fixed_decimal::SignedFixedDecimal;
use icu_plurals::{PluralRules, PluralRulesPreferences};
use icu_provider::prelude::*;

use crate::{
    compactdecimal::CompactDecimalFormatter,
    compactdecimal::CompactDecimalFormatterOptions,
    compactdecimal::CompactDecimalFormatterPreferences,
    dimension::provider::{
        currency_patterns::CurrencyPatternsDataV1Marker,
        extended_currency::CurrencyExtendedDataV1Marker,
    },
};
use icu_locale_core::preferences::{
    define_preferences, extensions::unicode::keywords::NumberingSystem, prefs_convert,
};

use super::{long_compact_format::FormattedLongCompactCurrency, CurrencyCode};

extern crate alloc;

define_preferences!(
    /// The preferences for currency formatting.
    [Copy]
    LongCompactCurrencyFormatterPreferences,
    {
        numbering_system: NumberingSystem
    }
);

prefs_convert!(
    LongCompactCurrencyFormatterPreferences,
    CompactDecimalFormatterPreferences,
    { numbering_system }
);
prefs_convert!(
    LongCompactCurrencyFormatterPreferences,
    PluralRulesPreferences
);

/// A formatter for monetary values.
///
/// [`LongCompactCurrencyFormatter`] supports:
///   1. Rendering in the locale's currency system.
///   2. Locale-sensitive grouping separator positions.
pub struct LongCompactCurrencyFormatter {
    /// Extended data for the currency formatter.
    extended: DataPayload<CurrencyExtendedDataV1Marker>,

    /// Formatting patterns for each currency plural category.
    patterns: DataPayload<CurrencyPatternsDataV1Marker>,

    /// A [`CompactDecimalFormatter`] to format the currency value in compact form.
    compact_decimal_formatter: CompactDecimalFormatter,

    /// A [`PluralRules`] to determine the plural category of the unit.
    plural_rules: PluralRules,
}

impl LongCompactCurrencyFormatter {
    icu_provider::gen_any_buffer_data_constructors!(
        (
            prefs: LongCompactCurrencyFormatterPreferences,
            currency_code: &CurrencyCode
        ) -> error: DataError,
        functions: [
            try_new: skip,
            try_new_with_any_provider,
            try_new_with_buffer_provider,
            try_new_unstable,
            Self
        ]
    );

    /// Creates a new [`LongCompactCurrencyFormatter`] from compiled locale data.
    ///
    /// ✨ *Enabled with the `compiled_data` Cargo feature.*
    ///
    /// [📚 Help choosing a constructor](icu_provider::constructors)
    #[cfg(feature = "compiled_data")]
    pub fn try_new(
        prefs: LongCompactCurrencyFormatterPreferences,
        currency_code: &CurrencyCode,
    ) -> Result<Self, DataError> {
        let compact_decimal_formatter = CompactDecimalFormatter::try_new_long(
            (&prefs).into(),
            CompactDecimalFormatterOptions::default(),
        )?;

        let marker_attributes = DataMarkerAttributes::try_from_str(currency_code.0.as_str())
            .map_err(|_| {
                DataErrorKind::IdentifierNotFound
                    .into_error()
                    .with_debug_context("failed to get data marker attribute from a `CurrencyCode`")
            })?;

        let locale = &DataLocale::from_preferences_locale::<CurrencyPatternsDataV1Marker>(
            prefs.locale_prefs,
        );

        let extended = crate::provider::Baked
            .load(DataRequest {
                id: DataIdentifierBorrowed::for_marker_attributes_and_locale(
                    marker_attributes,
                    locale,
                ),
                ..Default::default()
            })?
            .payload;

        let patterns = crate::provider::Baked.load(Default::default())?.payload;

        let plural_rules = PluralRules::try_new_cardinal((&prefs).into())?;

        Ok(Self {
            extended,
            patterns,
            compact_decimal_formatter,
            plural_rules,
        })
    }

    #[doc = icu_provider::gen_any_buffer_unstable_docs!(UNSTABLE, Self::try_new)]
    pub fn try_new_unstable<D>(
        provider: &D,
        prefs: LongCompactCurrencyFormatterPreferences,
        currency_code: &CurrencyCode,
    ) -> Result<Self, DataError>
    where
        D: ?Sized
            + DataProvider<
                crate::dimension::provider::extended_currency::CurrencyExtendedDataV1Marker,
            > + DataProvider<
                crate::dimension::provider::currency_patterns::CurrencyPatternsDataV1Marker,
            > + DataProvider<icu_decimal::provider::DecimalSymbolsV2Marker>
            + DataProvider<icu_decimal::provider::DecimalDigitsV1Marker>
            + DataProvider<icu_plurals::provider::CardinalV1Marker>
            + DataProvider<crate::compactdecimal::provider::LongCompactDecimalFormatDataV1Marker>,
    {
        let locale =
            DataLocale::from_preferences_locale::<CurrencyPatternsDataV1Marker>(prefs.locale_prefs);

        let marker_attributes = DataMarkerAttributes::try_from_str(currency_code.0.as_str())
            .map_err(|_| {
                DataErrorKind::IdentifierNotFound
                    .into_error()
                    .with_debug_context("failed to get data marker attribute from a `CurrencyCode`")
            })?;

        let extended = provider
            .load(DataRequest {
                id: DataIdentifierBorrowed::for_marker_attributes_and_locale(
                    marker_attributes,
                    &locale,
                ),
                ..Default::default()
            })?
            .payload;

        let patterns = provider.load(Default::default())?.payload;

        let plural_rules = PluralRules::try_new_cardinal_unstable(provider, (&prefs).into())?;

        let compact_decimal_formatter = CompactDecimalFormatter::try_new_long_unstable(
            provider,
            (&prefs).into(),
            CompactDecimalFormatterOptions::default(),
        )?;

        Ok(Self {
            extended,
            patterns,
            compact_decimal_formatter,
            plural_rules,
        })
    }

    /// Formats in the long format a [`SignedFixedDecimal`] value for the given currency code.
    ///
    /// # Examples
    /// ```
    /// use icu::experimental::dimension::currency::long_compact_formatter::LongCompactCurrencyFormatter;
    /// use icu::experimental::dimension::currency::CurrencyCode;
    /// use icu::locale::locale;
    /// use tinystr::*;
    /// use writeable::Writeable;
    ///
    /// let currency_prefs = locale!("en-US").into();
    /// let currency_code = CurrencyCode(tinystr!(3, "USD"));
    /// let fmt = LongCompactCurrencyFormatter::try_new(currency_prefs, &currency_code).unwrap();
    /// let value = "12345.67".parse().unwrap();
    /// let formatted_currency = fmt.format_fixed_decimal(&value, currency_code);
    /// let mut sink = String::new();
    /// formatted_currency.write_to(&mut sink).unwrap();
    /// assert_eq!(sink.as_str(), "12 thousand US dollars");
    /// ```
    pub fn format_fixed_decimal<'l>(
        &'l self,
        value: &'l SignedFixedDecimal,
        currency_code: CurrencyCode,
    ) -> FormattedLongCompactCurrency<'l> {
        FormattedLongCompactCurrency {
            signed_fixed_decimal: value,
            _currency_code: currency_code,
            extended: self.extended.get(),
            patterns: self.patterns.get(),
            compact_decimal_formatter: &self.compact_decimal_formatter,
            plural_rules: &self.plural_rules,
        }
    }
}