1use std::sync::Arc;
4
5use crate::{Error, Result};
6
7mod data;
8
9pub(super) fn validate_token(value: &str, empty: bool) -> Result<()> {
10 if (!empty && value.is_empty())
11 || value
12 .chars()
13 .any(|c| c.is_control() || crate::text::is_nonrendering_mandatory_break(c))
14 {
15 return Err(Error::Data(
16 "numeric token must have valid single-line content".into(),
17 ));
18 }
19 Ok(())
20}
21
22#[derive(Debug, Clone, Copy, PartialEq, Eq)]
24pub enum NumericGroupRepeat {
25 Cycle,
27 Last,
29 Stop,
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35pub struct NumericGrouping {
36 separator: String,
37 sizes: Vec<usize>,
38 repeat: NumericGroupRepeat,
39}
40
41impl NumericGrouping {
42 pub fn new(
44 separator: impl Into<String>,
45 sizes: Vec<usize>,
46 repeat: NumericGroupRepeat,
47 ) -> Result<Self> {
48 let separator = separator.into();
49 validate_token(&separator, false)?;
50 if sizes.is_empty() || sizes.contains(&0) {
51 return Err(Error::Data(
52 "numeric grouping requires positive sizes".into(),
53 ));
54 }
55 Ok(Self {
56 separator,
57 sizes,
58 repeat,
59 })
60 }
61 pub fn separator(&self) -> &str {
63 &self.separator
64 }
65 pub fn sizes(&self) -> &[usize] {
67 &self.sizes
68 }
69 pub const fn repeat(&self) -> NumericGroupRepeat {
71 self.repeat
72 }
73 pub(super) fn size(&self, index: usize) -> Option<usize> {
74 self.sizes
75 .get(index)
76 .copied()
77 .or_else(|| match self.repeat {
78 NumericGroupRepeat::Cycle => Some(self.sizes[index % self.sizes.len()]),
79 NumericGroupRepeat::Last => self.sizes.last().copied(),
80 NumericGroupRepeat::Stop => None,
81 })
82 }
83}
84
85#[derive(Debug, Clone, PartialEq, Eq)]
87pub struct NumericSymbols {
88 positive: String,
89 negative: String,
90 percent: String,
91 per_mille: String,
92}
93
94impl NumericSymbols {
95 pub fn new(
97 positive: impl Into<String>,
98 negative: impl Into<String>,
99 percent: impl Into<String>,
100 per_mille: impl Into<String>,
101 ) -> Result<Self> {
102 let value = Self {
103 positive: positive.into(),
104 negative: negative.into(),
105 percent: percent.into(),
106 per_mille: per_mille.into(),
107 };
108 for token in [
109 &value.positive,
110 &value.negative,
111 &value.percent,
112 &value.per_mille,
113 ] {
114 validate_token(token, false)?;
115 }
116 Ok(value)
117 }
118 pub fn positive(&self) -> &str {
120 &self.positive
121 }
122 pub fn negative(&self) -> &str {
124 &self.negative
125 }
126 pub fn percent(&self) -> &str {
128 &self.percent
129 }
130 pub fn per_mille(&self) -> &str {
132 &self.per_mille
133 }
134}
135
136#[derive(Debug, Clone, PartialEq, Eq)]
138pub struct NumericCurrency {
139 prefix: String,
140 suffix: String,
141}
142
143impl NumericCurrency {
144 pub fn new(prefix: impl Into<String>, suffix: impl Into<String>) -> Result<Self> {
146 let value = Self {
147 prefix: prefix.into(),
148 suffix: suffix.into(),
149 };
150 validate_token(&value.prefix, true)?;
151 validate_token(&value.suffix, true)?;
152 Ok(value)
153 }
154 pub fn prefix(&self) -> &str {
156 &self.prefix
157 }
158 pub fn suffix(&self) -> &str {
160 &self.suffix
161 }
162}
163
164#[derive(Debug, PartialEq, Eq)]
165struct LocaleData {
166 decimal: String,
167 digits: [String; 10],
168 grouping: Option<NumericGrouping>,
169 symbols: NumericSymbols,
170 currency: NumericCurrency,
171}
172
173#[derive(Debug, Clone, PartialEq, Eq)]
175pub struct NumericLocale(Arc<LocaleData>);
176
177impl NumericLocale {
178 pub fn invariant() -> Self {
180 Self::custom(
181 ".",
182 std::array::from_fn(|i| {
183 char::from(b'0' + u8::try_from(i).expect("ten digits")).to_string()
184 }),
185 Some(
186 NumericGrouping::new(",", vec![3], NumericGroupRepeat::Cycle)
187 .expect("invariant grouping"),
188 ),
189 NumericSymbols::new("+", "-", "%", "‰").expect("invariant symbols"),
190 NumericCurrency::new("$", "").expect("invariant currency"),
191 )
192 .expect("invariant locale")
193 }
194 pub fn named(name: &str) -> Result<Self> {
196 data::named(name)
197 }
198 pub fn named_ids() -> &'static [&'static str] {
200 data::IDS
201 }
202 pub fn custom(
204 decimal: impl Into<String>,
205 digits: [String; 10],
206 grouping: Option<NumericGrouping>,
207 symbols: NumericSymbols,
208 currency: NumericCurrency,
209 ) -> Result<Self> {
210 let decimal = decimal.into();
211 validate_token(&decimal, false)?;
212 for (index, digit) in digits.iter().enumerate() {
213 validate_token(digit, false)?;
214 if digits[..index].contains(digit) {
215 return Err(Error::Data("numeric digit tokens must be distinct".into()));
216 }
217 }
218 Ok(Self(Arc::new(LocaleData {
219 decimal,
220 digits,
221 grouping,
222 symbols,
223 currency,
224 })))
225 }
226 pub fn decimal(&self) -> &str {
228 &self.0.decimal
229 }
230 pub fn digits(&self) -> &[String; 10] {
232 &self.0.digits
233 }
234 pub fn grouping(&self) -> Option<&NumericGrouping> {
236 self.0.grouping.as_ref()
237 }
238 pub fn symbols(&self) -> &NumericSymbols {
240 &self.0.symbols
241 }
242 pub fn currency(&self) -> &NumericCurrency {
244 &self.0.currency
245 }
246 pub(super) fn observe(&self, round: &mut crate::layout::kernel::FeedbackRound) -> Result<()> {
247 round.observe_string(self.decimal())?;
248 for token in self.digits() {
249 round.observe_string(token)?;
250 }
251 round.observe_count(usize::from(self.grouping().is_some()))?;
252 if let Some(grouping) = self.grouping() {
253 round.observe_string(grouping.separator())?;
254 round.observe_count(grouping.sizes().len())?;
255 for size in grouping.sizes() {
256 round.observe_count(*size)?;
257 }
258 round.observe_count(grouping.repeat() as usize)?;
259 }
260 for token in [
261 self.symbols().positive(),
262 self.symbols().negative(),
263 self.symbols().percent(),
264 self.symbols().per_mille(),
265 self.currency().prefix(),
266 self.currency().suffix(),
267 ] {
268 round.observe_string(token)?;
269 }
270 Ok(())
271 }
272}