1use super::decimal::{NumericNotation, NumericRadix};
4use super::locale::{validate_token, NumericGroupRepeat, NumericGrouping, NumericLocale};
5use crate::{Error, Result};
6
7#[derive(Debug, Clone, Copy, PartialEq, Eq)]
9pub enum NumericSign {
10 NegativeOnly,
12 Always,
14 Space,
16 Accounting,
18}
19
20#[derive(Debug, Clone, Copy, PartialEq, Eq)]
22pub enum NumericSymbol {
23 None,
25 Currency,
27 RadixPrefix,
29}
30
31#[derive(Debug, Clone, Copy, PartialEq, Eq)]
33pub enum NumericAlignment {
34 Left,
36 Right,
38 Center,
40 AfterSign,
42}
43
44#[derive(Debug, Clone, PartialEq, Eq)]
46pub struct NumericField {
47 pub(super) width: usize,
48 pub(super) fill: char,
49 pub(super) alignment: NumericAlignment,
50}
51
52impl NumericField {
53 pub fn new(width: usize, fill: char, alignment: NumericAlignment) -> Result<Self> {
55 let mut bytes = [0; 4];
56 validate_token(fill.encode_utf8(&mut bytes), false)?;
57 Ok(Self {
58 width,
59 fill,
60 alignment,
61 })
62 }
63}
64
65#[derive(Debug, Clone, Copy, PartialEq, Eq)]
67pub enum NumericRate {
68 Value,
70 Percent,
72 PerMille,
74}
75
76impl NumericRate {
77 pub(super) const fn shift(self) -> i16 {
78 match self {
79 Self::Value => 0,
80 Self::Percent => 2,
81 Self::PerMille => 3,
82 }
83 }
84}
85
86#[derive(Debug, Clone, PartialEq, Eq)]
87pub(super) struct Presentation {
88 pub(super) locale: NumericLocale,
89 pub(super) grouping: bool,
90 pub(super) sign: NumericSign,
91 pub(super) symbol: NumericSymbol,
92 pub(super) field: Option<NumericField>,
93}
94
95#[derive(Clone, Copy)]
96pub(super) struct Affixes<'a> {
97 pub(super) outer_prefix: &'a str,
98 pub(super) outer_suffix: &'a str,
99 pub(super) prefix: &'a str,
100 pub(super) suffix: &'a str,
101}
102
103impl Default for Presentation {
104 fn default() -> Self {
105 Self {
106 locale: NumericLocale::invariant(),
107 grouping: false,
108 sign: NumericSign::NegativeOnly,
109 symbol: NumericSymbol::None,
110 field: None,
111 }
112 }
113}
114
115pub(super) fn append(out: &mut String, text: &str) -> Result<()> {
116 out.try_reserve(text.len())
117 .map_err(|e| Error::Render(format!("numeric text allocation: {e}")))?;
118 out.push_str(text);
119 Ok(())
120}
121
122fn fill(out: &mut String, scalar: char, count: usize) -> Result<()> {
123 let bytes = count
124 .checked_mul(scalar.len_utf8())
125 .ok_or_else(length_error)?;
126 out.try_reserve_exact(bytes)
127 .map_err(|e| Error::Render(format!("numeric field allocation: {e}")))?;
128 out.extend(std::iter::repeat_n(scalar, count));
129 Ok(())
130}
131
132fn length_error() -> Error {
133 Error::Render("numeric field or token length overflow".into())
134}
135
136fn digit(out: &mut String, byte: u8, locale: &NumericLocale) -> Result<()> {
137 if byte.is_ascii_digit() {
138 append(out, &locale.digits()[usize::from(byte - b'0')])
139 } else {
140 let mut bytes = [0; 4];
141 append(out, char::from(byte).encode_utf8(&mut bytes))
142 }
143}
144
145fn separators(count: usize, grouping: &NumericGrouping) -> Result<usize> {
146 if count == 0 {
147 return Ok(0);
148 }
149 let mut remaining = count;
150 let mut groups = 0_usize;
151 for &size in grouping.sizes() {
152 if remaining <= size {
153 return Ok(groups);
154 }
155 remaining -= size;
156 groups = groups.checked_add(1).ok_or_else(length_error)?;
157 }
158 match grouping.repeat() {
159 NumericGroupRepeat::Stop => Ok(groups),
160 NumericGroupRepeat::Last => groups
161 .checked_add((remaining - 1) / grouping.sizes()[grouping.sizes().len() - 1])
162 .ok_or_else(length_error),
163 NumericGroupRepeat::Cycle => {
164 let cycle = grouping
165 .sizes()
166 .iter()
167 .try_fold(0_usize, |n, &s| n.checked_add(s))
168 .ok_or_else(length_error)?;
169 let full = (remaining - 1) / cycle;
170 groups = groups
171 .checked_add(
172 full.checked_mul(grouping.sizes().len())
173 .ok_or_else(length_error)?,
174 )
175 .ok_or_else(length_error)?;
176 remaining -= full * cycle;
177 for &size in grouping.sizes() {
178 if remaining <= size {
179 break;
180 }
181 remaining -= size;
182 groups = groups.checked_add(1).ok_or_else(length_error)?;
183 }
184 Ok(groups)
185 }
186 }
187}
188
189fn integer_scalars(
190 integer: &str,
191 zeros: usize,
192 locale: &NumericLocale,
193 grouping: Option<&NumericGrouping>,
194) -> Result<usize> {
195 let mut count = zeros
196 .checked_mul(locale.digits()[0].chars().count())
197 .ok_or_else(length_error)?;
198 for byte in integer.bytes() {
199 count = count
200 .checked_add(if byte.is_ascii_digit() {
201 locale.digits()[usize::from(byte - b'0')].chars().count()
202 } else {
203 1
204 })
205 .ok_or_else(length_error)?;
206 }
207 if let Some(grouping) = grouping {
208 count = count
209 .checked_add(
210 separators(
211 integer.len().checked_add(zeros).ok_or_else(length_error)?,
212 grouping,
213 )?
214 .checked_mul(grouping.separator().chars().count())
215 .ok_or_else(length_error)?,
216 )
217 .ok_or_else(length_error)?;
218 }
219 Ok(count)
220}
221
222fn integer_text(
223 integer: &str,
224 zeros: usize,
225 locale: &NumericLocale,
226 grouping: Option<&NumericGrouping>,
227) -> Result<String> {
228 let total = integer.len().checked_add(zeros).ok_or_else(length_error)?;
229 let mut cuts = Vec::new();
230 let count = grouping.map_or(Ok(0), |g| separators(total, g))?;
231 crate::data::source::reserve_source(&mut cuts, count)?;
232 let mut remaining = total;
233 if let Some(grouping) = grouping {
234 for index in 0..count {
235 remaining -= grouping.size(index).ok_or_else(length_error)?;
236 cuts.push(remaining);
237 }
238 }
239 let mut output = String::new();
240 let max_digit = locale.digits().iter().map(String::len).max().unwrap_or(1);
242 let bytes = total
243 .checked_mul(max_digit)
244 .and_then(|n| {
245 n.checked_add(count.checked_mul(grouping.map_or(0, |g| g.separator().len()))?)
246 })
247 .ok_or_else(length_error)?;
248 output
249 .try_reserve_exact(bytes)
250 .map_err(|e| Error::Render(format!("numeric integer tokens: {e}")))?;
251 for index in 0..total {
252 if cuts.last() == Some(&index) {
253 append(&mut output, grouping.expect("grouped cut").separator())?;
254 cuts.pop();
255 }
256 digit(
257 &mut output,
258 if index < zeros {
259 b'0'
260 } else {
261 integer.as_bytes()[index - zeros]
262 },
263 locale,
264 )?;
265 }
266 Ok(output)
267}
268
269impl Presentation {
270 pub(super) fn observe(&self, round: &mut crate::layout::kernel::FeedbackRound) -> Result<()> {
271 self.locale.observe(round)?;
272 round.observe_count(usize::from(self.grouping))?;
273 round.observe_count(self.sign as usize)?;
274 round.observe_count(self.symbol as usize)?;
275 round.observe_count(usize::from(self.field.is_some()))?;
276 if let Some(field) = &self.field {
277 round.observe_count(field.width)?;
278 round.observe_count(field.fill as usize)?;
279 round.observe_count(field.alignment as usize)?;
280 }
281 Ok(())
282 }
283 #[expect(
284 clippy::too_many_lines,
285 reason = "one normalized emission order owns sign, grouping, locale tokens and final scalar padding"
286 )]
287 pub(super) fn emit(
288 &self,
289 ascii: &str,
290 notation: NumericNotation,
291 rate: NumericRate,
292 affixes: Affixes<'_>,
293 ) -> Result<String> {
294 let negative = ascii.starts_with('-');
295 let magnitude = ascii.strip_prefix('-').unwrap_or(ascii);
296 let (mantissa, exponent) = if matches!(notation, NumericNotation::Integer(_)) {
297 (magnitude, None)
298 } else {
299 magnitude
300 .split_once('e')
301 .map_or((magnitude, None), |(m, e)| (m, Some(e)))
302 };
303 let (integer, fraction) = mantissa
304 .split_once('.')
305 .map_or((mantissa, None), |(i, f)| (i, Some(f)));
306 let mut leading = String::new();
307 append(&mut leading, affixes.outer_prefix)?;
308 append(&mut leading, affixes.prefix)?;
309 append(
310 &mut leading,
311 match (negative, self.sign) {
312 (true, NumericSign::Accounting) => "(",
313 (true, _) => self.locale.symbols().negative(),
314 (false, NumericSign::Always) => self.locale.symbols().positive(),
315 (false, NumericSign::Space) => " ",
316 _ => "",
317 },
318 )?;
319 let radix = match (self.symbol, notation) {
320 (NumericSymbol::RadixPrefix, NumericNotation::Integer(NumericRadix::Binary)) => "0b",
321 (NumericSymbol::RadixPrefix, NumericNotation::Integer(NumericRadix::Octal)) => "0o",
322 (
323 NumericSymbol::RadixPrefix,
324 NumericNotation::Integer(NumericRadix::HexLower | NumericRadix::HexUpper),
325 ) => "0x",
326 _ => "",
327 };
328 append(
329 &mut leading,
330 if self.symbol == NumericSymbol::Currency {
331 self.locale.currency().prefix()
332 } else {
333 radix
334 },
335 )?;
336 let mut trailing = String::new();
337 if let Some(fraction) = fraction {
338 append(&mut trailing, self.locale.decimal())?;
339 for byte in fraction.bytes() {
340 digit(&mut trailing, byte, &self.locale)?;
341 }
342 }
343 if let Some(exponent) = exponent {
344 append(&mut trailing, "e")?;
345 for byte in exponent.bytes() {
346 if byte == b'-' {
347 append(&mut trailing, self.locale.symbols().negative())?;
348 } else {
349 digit(&mut trailing, byte, &self.locale)?;
350 }
351 }
352 }
353 append(
354 &mut trailing,
355 if self.symbol == NumericSymbol::Currency {
356 self.locale.currency().suffix()
357 } else {
358 match rate {
359 NumericRate::Value => "",
360 NumericRate::Percent => self.locale.symbols().percent(),
361 NumericRate::PerMille => self.locale.symbols().per_mille(),
362 }
363 },
364 )?;
365 if negative && self.sign == NumericSign::Accounting {
366 append(&mut trailing, ")")?;
367 }
368 append(&mut trailing, affixes.suffix)?;
369 append(&mut trailing, affixes.outer_suffix)?;
370 let grouping = self.grouping.then(|| self.locale.grouping()).flatten();
371 let fixed = leading
372 .chars()
373 .count()
374 .checked_add(trailing.chars().count())
375 .ok_or_else(length_error)?;
376 let mut zeros = 0;
377 if let Some(field) = &self.field {
378 if field.fill == '0' && field.alignment == NumericAlignment::AfterSign {
379 let (mut low, mut high) = (0_usize, field.width);
380 while low < high {
381 let middle = low + (high - low) / 2;
382 if fixed
383 .checked_add(integer_scalars(integer, middle, &self.locale, grouping)?)
384 .ok_or_else(length_error)?
385 < field.width
386 {
387 low = middle + 1;
388 } else {
389 high = middle;
390 }
391 }
392 zeros = low;
393 }
394 }
395 let numeric = integer_text(integer, zeros, &self.locale, grouping)?;
396 let length = fixed
397 .checked_add(numeric.chars().count())
398 .ok_or_else(length_error)?;
399 let mut output = String::new();
400 let padding = self
401 .field
402 .as_ref()
403 .map_or(0, |field| field.width.saturating_sub(length));
404 let (before, after, inside, scalar) =
405 self.field
406 .as_ref()
407 .map_or((0, 0, 0, ' '), |field| match field.alignment {
408 NumericAlignment::Left => (0, padding, 0, field.fill),
409 NumericAlignment::Right => (padding, 0, 0, field.fill),
410 NumericAlignment::Center => (padding / 2, padding - padding / 2, 0, field.fill),
411 NumericAlignment::AfterSign => (0, 0, padding, field.fill),
412 });
413 fill(&mut output, scalar, before)?;
414 append(&mut output, &leading)?;
415 fill(&mut output, scalar, inside)?;
416 append(&mut output, &numeric)?;
417 append(&mut output, &trailing)?;
418 fill(&mut output, scalar, after)?;
419 Ok(output)
420 }
421}
422
423#[cfg(test)]
424mod tests {
425 use super::*;
426 use crate::{NumericFormat, NumericPrecision};
427
428 #[test]
429 fn locale_signs_rates_currency_and_literal_affixes_follow_one_emission_order() {
430 let format = NumericFormat::new(NumericNotation::Decimal, NumericPrecision::Fractional(1))
431 .unwrap()
432 .locale(NumericLocale::named("fr-FR").unwrap())
433 .unwrap()
434 .grouping(true)
435 .unwrap()
436 .rate(NumericRate::Percent)
437 .unwrap()
438 .symbol(NumericSymbol::Currency)
439 .unwrap()
440 .sign(NumericSign::Accounting)
441 .unwrap()
442 .prefix("[")
443 .unwrap()
444 .suffix(" 00]")
445 .unwrap();
446 assert_eq!(
447 format.format_singleton(-12.5, false).unwrap(),
448 "[(1\u{a0}250,0\u{a0}€) 00]"
449 );
450 let rate = format
451 .clone()
452 .symbol(NumericSymbol::None)
453 .unwrap()
454 .sign(NumericSign::Always)
455 .unwrap();
456 assert_eq!(
457 rate.format_singleton(0.125, false).unwrap(),
458 "[+12,5\u{202f}% 00]"
459 );
460 let per_mille = NumericFormat::default()
461 .rate(NumericRate::PerMille)
462 .unwrap();
463 assert_eq!(per_mille.format_singleton(0.125, false).unwrap(), "125.00‰");
464 assert_eq!(per_mille.format_singleton(0.0, true).unwrap(), "1000.00‰");
465 let arabic = NumericFormat::default()
466 .locale(NumericLocale::named("ar-001").unwrap())
467 .unwrap()
468 .notation(NumericNotation::Scientific)
469 .unwrap()
470 .prefix("ID 012: ")
471 .unwrap();
472 assert_eq!(
473 arabic.format_singleton(-0.125, false).unwrap(),
474 "ID 012: −١٫٢٥e−١"
475 );
476 }
477}