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
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
// 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 alloc::borrow::Cow;
use core::convert::TryFrom;
use fixed_decimal::{CompactDecimal, FixedDecimal};
use icu_decimal::{
    options::{FixedDecimalFormatterOptions, GroupingStrategy},
    FixedDecimalFormatter,
};
use icu_plurals::PluralRules;
use icu_provider::prelude::*;
use zerovec::maps::ZeroMap2dCursor;

use crate::{
    format::FormattedCompactDecimal,
    provider::{
        Count, ErasedCompactDecimalFormatDataV1Marker, LongCompactDecimalFormatDataV1Marker,
        PatternULE, ShortCompactDecimalFormatDataV1Marker,
    },
    CompactDecimalError,
};

/// A bag of options defining how numbers will be formatted by
/// [`CompactDecimalFormatter`](crate::CompactDecimalFormatter).
#[derive(Debug, Eq, PartialEq, Clone)]
#[non_exhaustive]
pub struct CompactDecimalFormatterOptions {
    /// Options to configure the inner [`FixedDecimalFormatter`].
    pub fixed_decimal_formatter_options: FixedDecimalFormatterOptions,
}

impl Default for CompactDecimalFormatterOptions {
    fn default() -> Self {
        Self {
            fixed_decimal_formatter_options: GroupingStrategy::Min2.into(),
        }
    }
}

impl From<FixedDecimalFormatterOptions> for CompactDecimalFormatterOptions {
    fn from(fixed_decimal_formatter_options: FixedDecimalFormatterOptions) -> Self {
        Self {
            fixed_decimal_formatter_options,
        }
    }
}

impl From<GroupingStrategy> for CompactDecimalFormatterOptions {
    fn from(grouping_strategy: GroupingStrategy) -> Self {
        Self {
            fixed_decimal_formatter_options: grouping_strategy.into(),
        }
    }
}

/// A formatter that renders locale-sensitive compact numbers.
///
/// # Examples
///
/// ```
/// use icu_compactdecimal::CompactDecimalFormatter;
/// use icu_locid::locale;
/// use writeable::assert_writeable_eq;
///
/// let short_french = CompactDecimalFormatter::try_new_short_unstable(
///    &icu_testdata::unstable(),
///    &locale!("fr").into(),
///    Default::default(),
/// ).unwrap();
///
/// let [long_french, long_japanese, long_bangla] = [locale!("fr"), locale!("ja"), locale!("bn")]
///     .map(|locale| {
///         CompactDecimalFormatter::try_new_long_unstable(
///             &icu_testdata::unstable(),
///             &locale.into(),
///             Default::default(),
///         )
///         .unwrap()
///     });
///
/// /// Supports short and long notations:
/// # // The following line contains U+00A0 NO-BREAK SPACE.
/// assert_writeable_eq!(short_french.format_i64(35_357_670), "35 M");
/// assert_writeable_eq!(long_french.format_i64(35_357_670), "35 millions");
/// /// The powers of ten used are locale-dependent:
/// assert_writeable_eq!(long_japanese.format_i64(3535_7670), "3536万");
/// /// So are the digits:
/// assert_writeable_eq!(long_bangla.format_i64(3_53_57_670), "৩.৫ কোটি");
///
/// /// The output does not always contain digits:
/// assert_writeable_eq!(long_french.format_i64(1000), "mille");
/// ```
#[derive(Debug)]
pub struct CompactDecimalFormatter {
    pub(crate) plural_rules: PluralRules,
    pub(crate) fixed_decimal_format: FixedDecimalFormatter,
    pub(crate) compact_data: DataPayload<ErasedCompactDecimalFormatDataV1Marker>,
}

impl CompactDecimalFormatter {
    /// Constructor that takes a selected locale, reference to a
    /// [data provider] and a list of preferences, then collects all data
    /// necessary to format numbers in short compact decimal notation for
    /// the given locale.
    ///
    /// [📚 Help choosing a constructor](icu_provider::constructors)
    /// <div class="stab unstable">
    /// ⚠️ The bounds on this function may change over time, including in SemVer minor releases.
    /// </div>
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_compactdecimal::CompactDecimalFormatter;
    /// use icu_locid::locale;
    ///
    /// CompactDecimalFormatter::try_new_short_unstable(
    ///     &icu_testdata::unstable(),
    ///     &locale!("sv").into(),
    ///     Default::default(),
    /// );
    /// ```
    ///
    /// [data provider]: icu_provider
    pub fn try_new_short_unstable<D>(
        data_provider: &D,
        locale: &DataLocale,
        options: CompactDecimalFormatterOptions,
    ) -> Result<Self, CompactDecimalError>
    where
        D: DataProvider<ShortCompactDecimalFormatDataV1Marker>
            + DataProvider<icu_decimal::provider::DecimalSymbolsV1Marker>
            + DataProvider<icu_plurals::provider::CardinalV1Marker>
            + ?Sized,
    {
        Ok(Self {
            fixed_decimal_format: FixedDecimalFormatter::try_new_unstable(
                data_provider,
                locale,
                options.fixed_decimal_formatter_options,
            )?,
            plural_rules: PluralRules::try_new_cardinal_unstable(data_provider, locale)?,
            compact_data: DataProvider::<ShortCompactDecimalFormatDataV1Marker>::load(
                data_provider,
                DataRequest {
                    locale,
                    metadata: Default::default(),
                },
            )?
            .take_payload()?
            .cast(),
        })
    }

    icu_provider::gen_any_buffer_constructors!(
        locale: include,
        options: CompactDecimalFormatterOptions,
        error: CompactDecimalError,
        functions: [
            Self::try_new_short_unstable,
            try_new_short_with_any_provider,
            try_new_short_with_buffer_provider
        ]
    );

    /// Constructor that takes a selected locale, reference to a
    /// [data provider] and a list of preferences, then collects all data
    /// necessary to format numbers in short compact decimal notation for
    /// the given locale.
    ///
    /// [📚 Help choosing a constructor](icu_provider::constructors)
    /// <div class="stab unstable">
    /// ⚠️ The bounds on this function may change over time, including in SemVer minor releases.
    /// </div>
    ///
    /// # Examples
    ///
    /// ```
    /// use icu_compactdecimal::CompactDecimalFormatter;
    /// use icu_locid::locale;
    ///
    /// CompactDecimalFormatter::try_new_long_unstable(
    ///     &icu_testdata::unstable(),
    ///     &locale!("sv").into(),
    ///     Default::default(),
    /// );
    /// ```
    ///
    /// [data provider]: icu_provider
    pub fn try_new_long_unstable<D>(
        data_provider: &D,
        locale: &DataLocale,
        options: CompactDecimalFormatterOptions,
    ) -> Result<Self, CompactDecimalError>
    where
        D: DataProvider<LongCompactDecimalFormatDataV1Marker>
            + DataProvider<icu_decimal::provider::DecimalSymbolsV1Marker>
            + DataProvider<icu_plurals::provider::CardinalV1Marker>
            + ?Sized,
    {
        Ok(Self {
            fixed_decimal_format: FixedDecimalFormatter::try_new_unstable(
                data_provider,
                locale,
                options.fixed_decimal_formatter_options,
            )?,
            plural_rules: PluralRules::try_new_cardinal_unstable(data_provider, locale)?,
            compact_data: DataProvider::<LongCompactDecimalFormatDataV1Marker>::load(
                data_provider,
                DataRequest {
                    locale,
                    metadata: Default::default(),
                },
            )?
            .take_payload()?
            .cast(),
        })
    }

    icu_provider::gen_any_buffer_constructors!(
        locale: include,
        options: CompactDecimalFormatterOptions,
        error: CompactDecimalError,
        functions: [
            Self::try_new_long_unstable,
            try_new_long_with_any_provider,
            try_new_long_with_buffer_provider
        ]
    );

    /// Formats an integer in compact decimal notation using the default
    /// precision settings.
    ///
    /// The result may have a fractional digit only if it is compact and its
    /// significand is less than 10. Trailing fractional 0s are omitted, and
    /// a sign is shown only for negative values.
    /// ```
    /// # use icu_compactdecimal::CompactDecimalFormatter;
    /// # use icu_locid::locale;
    /// # use writeable::assert_writeable_eq;
    /// #
    /// # let short_english = CompactDecimalFormatter::try_new_short_unstable(
    /// #    &icu_testdata::unstable(),
    /// #    &locale!("en").into(),
    /// #    Default::default(),
    /// # ).unwrap();
    /// assert_writeable_eq!(short_english.format_i64(0), "0");
    /// assert_writeable_eq!(short_english.format_i64(2), "2");
    /// assert_writeable_eq!(short_english.format_i64(843), "843");
    /// assert_writeable_eq!(short_english.format_i64(2207), "2.2K");
    /// assert_writeable_eq!(short_english.format_i64(15_127), "15K");
    /// assert_writeable_eq!(short_english.format_i64(3_010_349), "3M");
    /// assert_writeable_eq!(short_english.format_i64(-13_132), "-13K");
    /// ```
    /// The result is the nearest such compact number, with halfway cases-
    /// rounded towards the number with an even least significant digit.
    /// ```
    /// # use icu_compactdecimal::CompactDecimalFormatter;
    /// # use icu_locid::locale;
    /// # use writeable::assert_writeable_eq;
    /// #
    /// # let short_english = CompactDecimalFormatter::try_new_short_unstable(
    /// #    &icu_testdata::unstable(),
    /// #    &locale!("en").into(),
    /// #    Default::default(),
    /// # ).unwrap();
    /// assert_writeable_eq!(short_english.format_i64(999_499), "999K");
    /// assert_writeable_eq!(short_english.format_i64(999_500), "1M");
    /// assert_writeable_eq!(short_english.format_i64(1650), "1.6K");
    /// assert_writeable_eq!(short_english.format_i64(1750), "1.8K");
    /// assert_writeable_eq!(short_english.format_i64(1950), "2K");
    /// assert_writeable_eq!(short_english.format_i64(-1_172_700), "-1.2M");
    /// ```
    pub fn format_i64(&self, value: i64) -> FormattedCompactDecimal<'_> {
        let unrounded = FixedDecimal::from(value);
        let log10_type = unrounded.nonzero_magnitude_start();
        let (mut plural_map, mut exponent) = self.plural_map_and_exponent_for_magnitude(log10_type);
        let mut significand = unrounded.multiplied_pow10(-i16::from(exponent));
        // If we have just one digit before the decimal point…
        if significand.nonzero_magnitude_start() == 0 {
            // …round to one fractional digit…
            significand.half_even(-1);
        } else {
            // …otherwise, we have at least 2 digits before the decimal point,
            // so round to eliminate the fractional part.
            significand.half_even(0);
        }
        let rounded_magnitude = significand.nonzero_magnitude_start() + i16::from(exponent);
        if rounded_magnitude > log10_type {
            // We got bumped up a magnitude by rounding.
            // This means that `significand` is a power of 10.
            let old_exponent = exponent;
            // NOTE(egg): We could inline `plural_map_and_exponent_for_magnitude`
            // to avoid iterating twice (we only need to look at the next key),
            // but this obscures the logic and the map is tiny.
            (plural_map, exponent) = self.plural_map_and_exponent_for_magnitude(rounded_magnitude);
            significand =
                significand.multiplied_pow10(i16::from(old_exponent) - i16::from(exponent));
            // There is no need to perform any rounding: `significand`, being
            // a power of 10, is as round as it gets, and since `exponent` can
            // only have become larger, it is already the correct rounding of
            // `unrounded` to the precision we want to show.
        }
        significand.trim_end();
        FormattedCompactDecimal {
            formatter: self,
            plural_map,
            value: Cow::Owned(CompactDecimal::from_significand_and_exponent(
                significand,
                exponent,
            )),
        }
    }

    /// Formats a [`CompactDecimal`] object according to locale data.
    ///
    /// This is an advanced API; prefer using [`Self::format_i64()`] in simple
    /// cases.
    ///
    /// Since the caller specifies the exact digits that are displayed, this
    /// allows for arbitrarily complex rounding rules.
    /// However, contrary to [`FixedDecimalFormatter::format()`], this operation
    /// can fail, because the given [`CompactDecimal`] can be inconsistent with
    /// the locale data; for instance, if the locale uses lakhs and crores and
    /// millions are requested, or vice versa, this function returns an error.
    ///
    /// The given [`CompactDecimal`] should be constructed using
    /// [`Self::compact_exponent_for_magnitude()`] on the same
    /// [`CompactDecimalFormatter`] object.
    /// Specifically, `formatter.format_compact_decimal(n)` requires that `n.exponent()`
    /// be equal to `formatter.compact_exponent_for_magnitude(n.significand().nonzero_magnitude_start() + n.exponent())`.
    ///
    /// # Examples
    /// ```
    /// # use icu_compactdecimal::CompactDecimalFormatter;
    /// # use icu_locid::locale;
    /// # use writeable::assert_writeable_eq;
    /// # use std::str::FromStr;
    /// use fixed_decimal::CompactDecimal;
    ///
    /// # let short_french = CompactDecimalFormatter::try_new_short_unstable(
    /// #    &icu_testdata::unstable(),
    /// #    &locale!("fr").into(),
    /// #    Default::default(),
    /// # ).unwrap();
    /// # let [long_french, long_bangla] = [locale!("fr"), locale!("bn")]
    /// #     .map(|locale| {
    /// #         CompactDecimalFormatter::try_new_long_unstable(
    /// #             &icu_testdata::unstable(),
    /// #             &locale.into(),
    /// #             Default::default(),
    /// #         )
    /// #         .unwrap()
    /// #     });
    /// #
    /// let about_a_million = CompactDecimal::from_str("1.20c6").unwrap();
    /// let three_million = CompactDecimal::from_str("+3c6").unwrap();
    /// let ten_lakhs = CompactDecimal::from_str("10c5").unwrap();
    /// # // The following line contains U+00A0 NO-BREAK SPACE.
    /// assert_writeable_eq!(
    ///     short_french
    ///         .format_compact_decimal(&about_a_million)
    ///         .unwrap(),
    ///     "1,20 M"
    /// );
    /// assert_writeable_eq!(
    ///     long_french
    ///         .format_compact_decimal(&about_a_million)
    ///         .unwrap(),
    ///     "1,20 million"
    /// );
    ///
    /// # // The following line contains U+00A0 NO-BREAK SPACE.
    /// assert_writeable_eq!(
    ///     short_french.format_compact_decimal(&three_million).unwrap(),
    ///     "+3 M"
    /// );
    /// assert_writeable_eq!(
    ///     long_french.format_compact_decimal(&three_million).unwrap(),
    ///     "+3 millions"
    /// );
    ///
    /// assert_writeable_eq!(
    ///     long_bangla.format_compact_decimal(&ten_lakhs).unwrap(),
    ///     "১০ লাখ"
    /// );
    ///
    /// assert_eq!(
    ///     long_bangla
    ///         .format_compact_decimal(&about_a_million)
    ///         .err()
    ///         .unwrap()
    ///         .to_string(),
    ///     "Expected compact exponent 5 for 10^6, got 6",
    /// );
    /// assert_eq!(
    ///     long_french
    ///         .format_compact_decimal(&ten_lakhs)
    ///         .err()
    ///         .unwrap()
    ///         .to_string(),
    ///     "Expected compact exponent 6 for 10^6, got 5",
    /// );
    ///
    /// /// Some patterns omit the digits; in those cases, the output does not
    /// /// contain the sequence of digits specified by the CompactDecimal.
    /// let a_thousand = CompactDecimal::from_str("1c3").unwrap();
    /// assert_writeable_eq!(
    ///     long_french.format_compact_decimal(&a_thousand).unwrap(),
    ///     "mille"
    /// );
    /// ```
    pub fn format_compact_decimal<'l>(
        &'l self,
        value: &'l CompactDecimal,
    ) -> Result<FormattedCompactDecimal<'l>, CompactDecimalError> {
        let log10_type = value.significand().nonzero_magnitude_start() + value.exponent();

        let (plural_map, expected_exponent) =
            self.plural_map_and_exponent_for_magnitude(log10_type);
        if value.exponent() != i16::from(expected_exponent) {
            return Err(CompactDecimalError::Exponent {
                actual: value.exponent(),
                expected: i16::from(expected_exponent),
                log10_type,
            });
        }

        Ok(FormattedCompactDecimal {
            formatter: self,
            plural_map,
            value: Cow::Borrowed(value),
        })
    }

    /// Returns the compact decimal exponent that should be used for a number of
    /// the given magnitude when using this formatter.
    ///
    /// # Examples
    /// ```
    /// use icu_compactdecimal::CompactDecimalFormatter;
    /// use icu_locid::locale;
    ///
    /// let [long_french, long_japanese, long_bangla] =
    ///     [locale!("fr"), locale!("ja"), locale!("bn")].map(|locale| {
    ///         CompactDecimalFormatter::try_new_long_unstable(
    ///             &icu_testdata::unstable(),
    ///             &locale.into(),
    ///             Default::default(),
    ///         )
    ///         .unwrap()
    ///     });
    /// /// French uses millions.
    /// assert_eq!(long_french.compact_exponent_for_magnitude(6), 6);
    /// /// Bangla uses lakhs.
    /// assert_eq!(long_bangla.compact_exponent_for_magnitude(6), 5);
    /// /// Japanese uses myriads.
    /// assert_eq!(long_japanese.compact_exponent_for_magnitude(6), 4);
    /// ```
    pub fn compact_exponent_for_magnitude(&self, magnitude: i16) -> u8 {
        let (_, exponent) = self.plural_map_and_exponent_for_magnitude(magnitude);
        exponent
    }

    fn plural_map_and_exponent_for_magnitude(
        &self,
        magnitude: i16,
    ) -> (Option<ZeroMap2dCursor<i8, Count, PatternULE>>, u8) {
        let plural_map = self
            .compact_data
            .get()
            .patterns
            .iter0()
            .filter(|cursor| i16::from(*cursor.key0()) <= magnitude)
            .last();
        let exponent = plural_map
            .as_ref()
            .and_then(|map| {
                map.get1(&Count::Other)
                    .and_then(|pattern| u8::try_from(pattern.exponent).ok())
            })
            .unwrap_or(0);
        (plural_map, exponent)
    }
}

#[cfg(feature = "serde")]
#[cfg(test)]
mod tests {
    use super::*;
    use icu_locid::locale;
    use writeable::assert_writeable_eq;

    #[allow(non_snake_case)]
    #[test]
    fn test_grouping() {
        // https://unicode-org.atlassian.net/browse/ICU-22254
        #[derive(Debug)]
        struct TestCase<'a> {
            short: bool,
            options: CompactDecimalFormatterOptions,
            expected1T: &'a str,
            expected10T: &'a str,
        }
        let cases = [
            TestCase {
                short: true,
                options: Default::default(),
                expected1T: "1000T",
                expected10T: "10,000T",
            },
            TestCase {
                short: true,
                options: GroupingStrategy::Always.into(),
                expected1T: "1,000T",
                expected10T: "10,000T",
            },
            TestCase {
                short: true,
                options: GroupingStrategy::Never.into(),
                expected1T: "1000T",
                expected10T: "10000T",
            },
            TestCase {
                short: false,
                options: Default::default(),
                expected1T: "1000 trillion",
                expected10T: "10,000 trillion",
            },
            TestCase {
                short: false,
                options: GroupingStrategy::Always.into(),
                expected1T: "1,000 trillion",
                expected10T: "10,000 trillion",
            },
            TestCase {
                short: false,
                options: GroupingStrategy::Never.into(),
                expected1T: "1000 trillion",
                expected10T: "10000 trillion",
            },
        ];
        for case in cases {
            let provider = icu_testdata::buffer();
            let formatter = if case.short {
                CompactDecimalFormatter::try_new_short_with_buffer_provider(
                    &provider,
                    &locale!("en").into(),
                    case.options.clone(),
                )
            } else {
                CompactDecimalFormatter::try_new_long_with_buffer_provider(
                    &provider,
                    &locale!("en").into(),
                    case.options.clone(),
                )
            }
            .unwrap();
            let result1T = formatter.format_i64(1_000_000_000_000_000);
            assert_writeable_eq!(result1T, case.expected1T, "{:?}", case);
            let result10T = formatter.format_i64(10_000_000_000_000_000);
            assert_writeable_eq!(result10T, case.expected10T, "{:?}", case);
        }
    }
}