1use std::borrow::Cow;
6use std::time::{SystemTime, UNIX_EPOCH};
7
8use fluent_bundle::types::{FluentNumberCurrencyDisplayStyle, FluentNumberOptions, FluentNumberStyle, FluentType};
9use fluent_bundle::{FluentArgs, FluentValue};
10
11pub trait PlatformLocale {
16 fn languages(&self) -> Vec<String>;
19
20 fn format_number(&self, value: f64, format: &NumberFormat) -> Option<String>;
23
24 fn format_date_time(&self, time: SystemTime, format: &DateTimeFormat) -> Option<String>;
27}
28
29#[derive(Clone, Debug, PartialEq)]
33pub struct NumberFormat {
34 pub style: NumberStyle,
35 pub grouping: bool,
37 pub minimum_integer_digits: Option<usize>,
38 pub minimum_fraction_digits: Option<usize>,
39 pub maximum_fraction_digits: Option<usize>,
40 pub minimum_significant_digits: Option<usize>,
42 pub maximum_significant_digits: Option<usize>,
43}
44
45impl Default for NumberFormat {
46 fn default() -> NumberFormat {
47 NumberFormat {
48 style: NumberStyle::Decimal,
49 grouping: true,
50 minimum_integer_digits: None,
51 minimum_fraction_digits: None,
52 maximum_fraction_digits: None,
53 minimum_significant_digits: None,
54 maximum_significant_digits: None,
55 }
56 }
57}
58
59#[derive(Clone, Debug, Default, PartialEq)]
60pub enum NumberStyle {
61 #[default]
62 Decimal,
63 Percent,
65 Currency { code: String, display: CurrencyDisplay },
67}
68
69#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
71pub enum CurrencyDisplay {
72 #[default]
74 Symbol,
75 Code,
77 Name,
79}
80
81impl NumberFormat {
82 pub fn fraction_digits(&self) -> (usize, usize) {
85 let (min, max) = match &self.style {
86 NumberStyle::Decimal => (0, 3),
87 NumberStyle::Percent => (0, 0),
88 NumberStyle::Currency { code, .. } => {
89 let digits = currency_digits(code);
90 (digits, digits)
91 }
92 };
93 let min = self.minimum_fraction_digits.unwrap_or(match self.maximum_fraction_digits {
95 Some(max) => min.min(max),
96 None => min,
97 });
98 let max = self.maximum_fraction_digits.unwrap_or(max).max(min);
99 (min, max)
100 }
101
102 pub(crate) fn from_fluent(options: &FluentNumberOptions) -> NumberFormat {
103 NumberFormat {
104 style: match options.style {
105 FluentNumberStyle::Decimal => NumberStyle::Decimal,
106 FluentNumberStyle::Percent => NumberStyle::Percent,
107 FluentNumberStyle::Currency => NumberStyle::Currency {
108 code: options.currency.clone().unwrap_or_default(),
109 display: match options.currency_display {
110 FluentNumberCurrencyDisplayStyle::Symbol => CurrencyDisplay::Symbol,
111 FluentNumberCurrencyDisplayStyle::Code => CurrencyDisplay::Code,
112 FluentNumberCurrencyDisplayStyle::Name => CurrencyDisplay::Name,
113 },
114 },
115 },
116 grouping: options.use_grouping,
117 minimum_integer_digits: options.minimum_integer_digits.map(|n| n.clamp(1, 21)),
120 minimum_fraction_digits: options.minimum_fraction_digits.map(|n| n.min(100)),
121 maximum_fraction_digits: options.maximum_fraction_digits.map(|n| n.min(100)),
122 minimum_significant_digits: options.minimum_significant_digits.map(|n| n.clamp(1, 21)),
123 maximum_significant_digits: options.maximum_significant_digits.map(|n| n.clamp(1, 21)),
124 }
125 }
126}
127
128#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
132pub struct DateTimeFormat {
133 pub date: Option<DateTimeStyle>,
134 pub time: Option<DateTimeStyle>,
135}
136
137impl DateTimeFormat {
138 pub fn resolved(self) -> (Option<DateTimeStyle>, Option<DateTimeStyle>) {
140 match (self.date, self.time) {
141 (None, None) => (Some(DateTimeStyle::Short), None),
142 styles => styles,
143 }
144 }
145
146 fn merge(&mut self, args: &FluentArgs) {
147 for (key, value) in args.iter() {
148 let FluentValue::String(style) = value else { continue };
149 let style = match style.as_ref() {
150 "short" => DateTimeStyle::Short,
151 "medium" => DateTimeStyle::Medium,
152 "long" => DateTimeStyle::Long,
153 "full" => DateTimeStyle::Full,
154 _ => continue,
155 };
156 match key {
157 "dateStyle" => self.date = Some(style),
158 "timeStyle" => self.time = Some(style),
159 _ => {}
160 }
161 }
162 }
163}
164
165#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
168pub enum DateTimeStyle {
169 Short,
170 Medium,
171 Long,
172 Full,
173}
174
175#[derive(Clone, Debug, PartialEq)]
178pub(crate) struct DateTimeArg {
179 pub time: SystemTime,
180 pub format: DateTimeFormat,
181}
182
183impl FluentType for DateTimeArg {
184 fn duplicate(&self) -> Box<dyn FluentType + Send> {
185 Box::new(self.clone())
186 }
187
188 fn as_string(&self, _: &intl_memoizer::IntlLangMemoizer) -> Cow<'static, str> {
189 format_date_time(self.time, &self.format).into()
190 }
191
192 fn as_string_threadsafe(&self, _: &intl_memoizer::concurrent::IntlLangMemoizer) -> Cow<'static, str> {
193 basic_date_time(self.time, &self.format).into()
194 }
195}
196
197#[allow(non_snake_case)]
199pub(crate) fn DATETIME<'a>(positional: &[FluentValue<'a>], named: &FluentArgs) -> FluentValue<'a> {
200 let Some(FluentValue::Custom(value)) = positional.first() else { return FluentValue::Error };
201 let Some(date) = value.as_any().downcast_ref::<DateTimeArg>() else { return FluentValue::Error };
202 let mut date = date.clone();
203 date.format = DateTimeFormat::default();
205 date.format.merge(named);
206 FluentValue::Custom(Box::new(date))
207}
208
209pub(crate) fn format_value(value: &FluentValue, _: &intl_memoizer::IntlLangMemoizer) -> Option<String> {
212 match value {
213 FluentValue::Number(n) => Some(format_number(n.value, &NumberFormat::from_fluent(&n.options))),
214 FluentValue::Custom(custom) => {
215 custom.as_any().downcast_ref::<DateTimeArg>().map(|d| format_date_time(d.time, &d.format))
216 }
217 _ => None,
218 }
219}
220
221pub fn format_number(value: f64, format: &NumberFormat) -> String {
224 super::platform_locale()
225 .and_then(|platform| platform.format_number(value, format))
226 .unwrap_or_else(|| basic_number(value, format))
227}
228
229pub fn format_date_time(time: SystemTime, format: &DateTimeFormat) -> String {
232 super::platform_locale()
233 .and_then(|platform| platform.format_date_time(time, format))
234 .unwrap_or_else(|| basic_date_time(time, format))
235}
236
237#[derive(Clone, Debug, PartialEq)]
240pub struct NumberSymbols {
241 pub decimal: String,
242 pub group: String,
243 pub grouping: Vec<usize>,
246 pub currency_before: bool,
249 pub currency_space: bool,
250 pub percent: String,
253 pub percent_before: bool,
254}
255
256impl NumberSymbols {
257 pub fn us_english() -> NumberSymbols {
259 NumberSymbols {
260 decimal: ".".into(),
261 group: ",".into(),
262 grouping: vec![3],
263 currency_before: true,
264 currency_space: false,
265 percent: "%".into(),
266 percent_before: false,
267 }
268 }
269}
270
271pub fn basic_number(value: f64, format: &NumberFormat) -> String {
274 format_number_with(value, format, &NumberSymbols::us_english())
275}
276
277pub fn format_number_with(value: f64, format: &NumberFormat, symbols: &NumberSymbols) -> String {
280 if !value.is_finite() {
281 return if value.is_nan() {
282 "NaN".into()
283 } else if value > 0.0 {
284 "∞".into()
285 } else {
286 "-∞".into()
287 };
288 }
289 let scaled = if format.style == NumberStyle::Percent { value * 100.0 } else { value };
290 let digits = digits(scaled.abs(), format);
291 let (int, frac) = match digits.split_once('.') {
292 Some((i, f)) => (i.to_string(), Some(f.to_string())),
293 None => (digits, None),
294 };
295 let int = format!("{int:0>width$}", width = format.minimum_integer_digits.unwrap_or(1));
296 let mut out = if format.grouping { group(&int, symbols) } else { int };
297 if let Some(frac) = frac {
298 out.push_str(&symbols.decimal);
299 out.push_str(&frac);
300 }
301 let negative = scaled < 0.0 && out.chars().any(|c| c.is_ascii_digit() && c != '0');
302 let sign = if negative { "-" } else { "" };
303 match &format.style {
304 NumberStyle::Decimal => format!("{sign}{out}"),
305 NumberStyle::Percent if symbols.percent_before => format!("{sign}{}{out}", symbols.percent),
306 NumberStyle::Percent => format!("{sign}{out}{}", symbols.percent),
307 NumberStyle::Currency { code, display } => {
308 let symbol = match (display, currency_symbol(code)) {
309 (CurrencyDisplay::Symbol, Some(symbol)) => symbol.to_owned(),
310 _ => code.clone(),
311 };
312 let space = if symbols.currency_space || symbol == *code { "\u{a0}" } else { "" };
314 if symbols.currency_before {
315 format!("{sign}{symbol}{space}{out}")
316 } else {
317 format!("{sign}{out}{space}{symbol}")
318 }
319 }
320 }
321}
322
323pub fn rounded(value: f64, format: &NumberFormat) -> (f64, usize) {
327 let scaled = if format.style == NumberStyle::Percent { value * 100.0 } else { value };
328 if !scaled.is_finite() {
329 return (scaled, 0);
330 }
331 let digits = digits(scaled.abs(), format);
332 let decimals = digits.split_once('.').map_or(0, |(_, fraction)| fraction.len());
333 (digits.parse::<f64>().unwrap_or(scaled.abs()).copysign(scaled), decimals)
334}
335
336fn digits(abs: f64, format: &NumberFormat) -> String {
338 match (format.minimum_significant_digits, format.maximum_significant_digits) {
339 (None, None) => {
340 let (min, max) = format.fraction_digits();
341 trim_fraction(round_to(abs, max as i32), min)
342 }
343 (min, max) => {
344 let max = max.unwrap_or(21).max(1);
345 let min = min.unwrap_or(1).min(max);
346 significant(abs, min, max)
347 }
348 }
349}
350
351fn round_to(abs: f64, decimals: i32) -> String {
356 let text = format!("{abs}");
357 let (int, fraction) = text.split_once('.').unwrap_or((&text, ""));
358 let mut digits: Vec<u8> = int.bytes().chain(fraction.bytes()).map(|b| b - b'0').collect();
359 let mut point = int.len() as i32;
360 let keep = point + decimals;
361 if keep < 0 {
362 digits.clear();
363 } else if (keep as usize) < digits.len() {
364 let up = digits[keep as usize] >= 5;
365 digits.truncate(keep as usize);
366 if up {
367 match digits.iter().rposition(|d| *d < 9) {
368 Some(i) => {
369 digits[i] += 1;
370 digits.truncate(i + 1);
371 }
372 None => {
373 digits.clear();
374 digits.push(1);
375 point += 1;
376 }
377 }
378 }
379 }
380 let digit =
381 |i: i32| if i >= 0 && (i as usize) < digits.len() { char::from(b'0' + digits[i as usize]) } else { '0' };
382 let int: String = (0..point).map(digit).collect();
383 let int = match int.trim_start_matches('0') {
384 "" => "0".to_owned(),
385 trimmed => trimmed.to_owned(),
386 };
387 if decimals <= 0 {
388 return int;
389 }
390 let fraction: String = (point..point + decimals).map(digit).collect();
391 format!("{int}.{fraction}")
392}
393
394fn trim_fraction(mut digits: String, min: usize) -> String {
396 if let Some(dot) = digits.find('.') {
397 let keep = dot + 1 + min;
398 while digits.len() > keep && digits.ends_with('0') {
399 digits.pop();
400 }
401 if digits.ends_with('.') {
402 digits.pop();
403 }
404 }
405 digits
406}
407
408fn significant(value: f64, min: usize, max: usize) -> String {
409 if value == 0.0 {
410 return trim_fraction(round_to(0.0, max as i32 - 1), min.saturating_sub(1));
411 }
412 let exponent = value.log10().floor() as i32;
413 let min_decimals = (min as i32 - 1 - exponent).max(0) as usize;
414 trim_fraction(round_to(value, max as i32 - 1 - exponent), min_decimals)
415}
416
417fn currency_digits(code: &str) -> usize {
419 match code {
420 "BIF" | "CLP" | "DJF" | "GNF" | "ISK" | "JPY" | "KMF" | "KRW" | "PYG" | "RWF" | "UGX" | "VND" | "VUV"
421 | "XAF" | "XOF" | "XPF" => 0,
422 "BHD" | "IQD" | "JOD" | "KWD" | "LYD" | "OMR" | "TND" => 3,
423 _ => 2,
424 }
425}
426
427fn group(int: &str, symbols: &NumberSymbols) -> String {
428 let Some(&last) = symbols.grouping.last().filter(|size| **size > 0) else { return int.to_owned() };
429 let mut cuts = Vec::new();
431 let mut at = 0;
432 for i in 0.. {
433 at += symbols.grouping.get(i).copied().unwrap_or(last);
434 if at >= int.len() {
435 break;
436 }
437 cuts.push(int.len() - at);
438 }
439 let mut out = String::with_capacity(int.len() + cuts.len() * symbols.group.len());
440 for (i, c) in int.chars().enumerate() {
441 if cuts.contains(&i) {
442 out.push_str(&symbols.group);
443 }
444 out.push(c);
445 }
446 out
447}
448
449fn currency_symbol(code: &str) -> Option<&'static str> {
450 Some(match code {
451 "USD" => "$",
452 "EUR" => "€",
453 "GBP" => "£",
454 "JPY" => "¥",
455 "BRL" => "R$",
456 "INR" => "₹",
457 _ => return None,
458 })
459}
460
461const MONTHS: [&str; 12] = [
462 "January",
463 "February",
464 "March",
465 "April",
466 "May",
467 "June",
468 "July",
469 "August",
470 "September",
471 "October",
472 "November",
473 "December",
474];
475const WEEKDAYS: [&str; 7] = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
476
477pub fn basic_date_time(time: SystemTime, format: &DateTimeFormat) -> String {
480 let seconds = match time.duration_since(UNIX_EPOCH) {
481 Ok(d) => d.as_secs() as i64,
482 Err(e) => -(e.duration().as_secs_f64().ceil() as i64),
483 };
484 let days = seconds.div_euclid(86_400);
485 let of_day = seconds.rem_euclid(86_400);
486 let (year, month, day) = civil_from_days(days);
487 let weekday = WEEKDAYS[(days + 4).rem_euclid(7) as usize];
488 let month_name = MONTHS[month as usize - 1];
489 let (date_style, time_style) = format.resolved();
490 let date = date_style.map(|style| match style {
491 DateTimeStyle::Short => format!("{month}/{day}/{:02}", year.rem_euclid(100)),
492 DateTimeStyle::Medium => format!("{} {day}, {year}", &month_name[..3]),
493 DateTimeStyle::Long => format!("{month_name} {day}, {year}"),
494 DateTimeStyle::Full => format!("{weekday}, {month_name} {day}, {year}"),
495 });
496 let time = time_style.map(|style| {
497 let (hour, minute, second) = (of_day / 3600, of_day / 60 % 60, of_day % 60);
498 let (hour12, half) = (if hour % 12 == 0 { 12 } else { hour % 12 }, if hour < 12 { "AM" } else { "PM" });
499 match style {
500 DateTimeStyle::Short => format!("{hour12}:{minute:02}\u{202f}{half}"),
501 DateTimeStyle::Medium => format!("{hour12}:{minute:02}:{second:02}\u{202f}{half}"),
502 DateTimeStyle::Long | DateTimeStyle::Full => {
503 format!("{hour12}:{minute:02}:{second:02}\u{202f}{half} UTC")
504 }
505 }
506 });
507 match (date, time) {
508 (Some(date), Some(time)) => format!("{date}, {time}"),
509 (Some(one), None) | (None, Some(one)) => one,
510 (None, None) => String::new(),
511 }
512}
513
514fn civil_from_days(days: i64) -> (i64, u32, u32) {
517 let z = days + 719_468;
518 let era = z.div_euclid(146_097);
519 let doe = z.rem_euclid(146_097);
520 let yoe = (doe - doe / 1460 + doe / 36_524 - doe / 146_096) / 365;
521 let doy = doe - (365 * yoe + yoe / 4 - yoe / 100);
522 let mp = (5 * doy + 2) / 153;
523 let day = (doy - (153 * mp + 2) / 5 + 1) as u32;
524 let month = if mp < 10 { mp + 3 } else { mp - 9 } as u32;
525 let year = yoe + era * 400 + i64::from(month <= 2);
526 (year, month, day)
527}