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
// 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 fixed_decimal::{FixedDecimal, Sign};
use icu_decimal::FixedDecimalFormatter;

use crate::alloc::borrow::ToOwned;
use alloc::borrow::Cow;
use writeable::Writeable;

use crate::dimension::provider::percent::PercentEssentialsV1;

use super::options::{Display, PercentFormatterOptions};

struct Append<W1, W2>(W1, W2);
// This allows us to combines two writeables together.
impl<W1: Writeable, W2: Writeable> Writeable for Append<W1, W2> {
    fn write_to<W>(&self, sink: &mut W) -> core::result::Result<(), core::fmt::Error>
    where
        W: core::fmt::Write + ?Sized,
    {
        self.0.write_to(sink)?;
        self.1.write_to(sink)
    }
}

pub struct FormattedPercent<'l> {
    pub(crate) value: &'l FixedDecimal,
    pub(crate) essential: &'l PercentEssentialsV1<'l>,
    pub(crate) options: &'l PercentFormatterOptions,
    pub(crate) fixed_decimal_formatter: &'l FixedDecimalFormatter,
}

impl Writeable for FormattedPercent<'_> {
    fn write_to<W>(&self, sink: &mut W) -> core::result::Result<(), core::fmt::Error>
    where
        W: core::fmt::Write + ?Sized,
    {
        // Removing the sign from the value
        let abs_value = match self.value.sign() {
            Sign::Negative => self.value.clone().with_sign(Sign::None),
            _ => self.value.to_owned(),
        };

        let value = self.fixed_decimal_formatter.format(&abs_value);

        match self.options.display {
            // In the Standard display, we take the unsigned pattern only when the value is positive.
            Display::Standard => {
                if self.value.sign() == Sign::Negative {
                    self.essential
                        .signed_pattern
                        .interpolate((value, &self.essential.minus_sign))
                        .write_to(sink)?
                } else {
                    self.essential
                        .unsigned_pattern
                        .interpolate([value])
                        .write_to(sink)?
                };
            }
            Display::Approximate => {
                let sign = if self.value.sign() == Sign::Negative {
                    // The approximate sign gets pre-pended
                    Append(
                        &self.essential.approximately_sign,
                        &self.essential.minus_sign,
                    )
                } else {
                    Append(&self.essential.approximately_sign, &Cow::Borrowed(""))
                };

                self.essential
                    .signed_pattern
                    .interpolate((value, sign))
                    .write_to(sink)?;
            }
            Display::ExplicitSign => self
                .essential
                .signed_pattern
                .interpolate((
                    value,
                    if self.value.sign() == Sign::Negative {
                        &self.essential.minus_sign
                    } else {
                        &self.essential.plus_sign
                    },
                ))
                .write_to(sink)?,
        };

        Ok(())
    }
}

writeable::impl_display_with_writeable!(FormattedPercent<'_>);

#[cfg(test)]
mod tests {
    use icu_locale_core::locale;
    use writeable::assert_writeable_eq;

    use crate::dimension::percent::{
        formatter::{PercentFormatter, PercentFormatterPreferences},
        options::{Display, PercentFormatterOptions},
    };

    #[test]
    pub fn test_en_us() {
        let prefs: PercentFormatterPreferences = locale!("en-US").into();
        // Positive case
        let positive_value = "12345.67".parse().unwrap();
        let default_fmt = PercentFormatter::try_new(prefs, Default::default()).unwrap();
        let formatted_percent = default_fmt.format(&positive_value);
        assert_writeable_eq!(formatted_percent, "12,345.67%");

        // Negative case
        let neg_value = "-12345.67".parse().unwrap();
        let formatted_percent = default_fmt.format(&neg_value);
        assert_writeable_eq!(formatted_percent, "-12,345.67%");

        // Approximate Case
        let approx_value = "12345.67".parse().unwrap();
        let approx_fmt = PercentFormatter::try_new(
            prefs,
            PercentFormatterOptions {
                display: Display::Approximate,
            },
        )
        .unwrap();
        let formatted_percent = approx_fmt.format(&approx_value);
        assert_writeable_eq!(formatted_percent, "~12,345.67%");

        // ExplicitSign Case
        let explicit_fmt = PercentFormatter::try_new(
            prefs,
            PercentFormatterOptions {
                display: Display::ExplicitSign,
            },
        )
        .unwrap();
        let formatted_percent = explicit_fmt.format(&positive_value);
        assert_writeable_eq!(formatted_percent, "+12,345.67%");
    }

    #[test]
    pub fn test_tr() {
        let prefs: PercentFormatterPreferences = locale!("tr").into();
        // Positive case
        let positive_value = "12345.67".parse().unwrap();
        let default_fmt = PercentFormatter::try_new(prefs, Default::default()).unwrap();
        let formatted_percent = default_fmt.format(&positive_value);
        assert_writeable_eq!(formatted_percent, "%12.345,67");

        // Negative case
        let neg_value = "-12345.67".parse().unwrap();
        let formatted_percent = default_fmt.format(&neg_value);
        assert_writeable_eq!(formatted_percent, "-%12.345,67");

        // Approximate Case
        let approx_value = "12345.67".parse().unwrap();
        let approx_fmt = PercentFormatter::try_new(
            prefs,
            PercentFormatterOptions {
                display: Display::Approximate,
            },
        )
        .unwrap();
        let formatted_percent = approx_fmt.format(&approx_value);
        assert_writeable_eq!(formatted_percent, "~%12.345,67");

        // ExplicitSign Case
        let explicit_fmt = PercentFormatter::try_new(
            prefs,
            PercentFormatterOptions {
                display: Display::ExplicitSign,
            },
        )
        .unwrap();
        let formatted_percent = explicit_fmt.format(&positive_value);
        assert_writeable_eq!(formatted_percent, "+%12.345,67");
    }

    #[test]
    pub fn test_blo() {
        let prefs: PercentFormatterPreferences = locale!("blo").into();
        // Positive case
        let positive_value = "12345.67".parse().unwrap();
        let default_fmt = PercentFormatter::try_new(prefs, Default::default()).unwrap();
        let formatted_percent = default_fmt.format(&positive_value);
        assert_writeable_eq!(formatted_percent, "%\u{a0}12\u{a0}345,67");

        // Negative case
        let neg_value = "-12345.67".parse().unwrap();
        let formatted_percent = default_fmt.format(&neg_value);
        assert_writeable_eq!(formatted_percent, "%\u{a0}-12\u{a0}345,67");

        // Approximate Case
        let approx_value = "12345.67".parse().unwrap();
        let approx_fmt = PercentFormatter::try_new(
            prefs,
            PercentFormatterOptions {
                display: Display::Approximate,
            },
        )
        .unwrap();
        let formatted_percent = approx_fmt.format(&approx_value);
        assert_writeable_eq!(formatted_percent, "%\u{a0}~12\u{a0}345,67");

        // ExplicitSign Case
        let explicit_fmt = PercentFormatter::try_new(
            prefs,
            PercentFormatterOptions {
                display: Display::ExplicitSign,
            },
        )
        .unwrap();
        let formatted_percent = explicit_fmt.format(&positive_value);
        assert_writeable_eq!(formatted_percent, "%\u{a0}+12\u{a0}345,67");
    }
}