use std::collections::BTreeMap;
use serde::Deserialize;
use super::{Part, locale::Locale, number};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Unit {
Second,
Minute,
Hour,
Day,
Week,
Month,
Quarter,
Year,
}
impl Unit {
pub(crate) fn parse(text: &str) -> Option<Self> {
Some(match text.strip_suffix('s').unwrap_or(text) {
"second" => Unit::Second,
"minute" => Unit::Minute,
"hour" => Unit::Hour,
"day" => Unit::Day,
"week" => Unit::Week,
"month" => Unit::Month,
"quarter" => Unit::Quarter,
"year" => Unit::Year,
_ => return None,
})
}
pub(crate) fn name(self) -> &'static str {
match self {
Unit::Second => "second",
Unit::Minute => "minute",
Unit::Hour => "hour",
Unit::Day => "day",
Unit::Week => "week",
Unit::Month => "month",
Unit::Quarter => "quarter",
Unit::Year => "year",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Style {
Long,
Short,
Narrow,
}
impl Style {
pub(crate) fn name(self) -> &'static str {
match self {
Style::Long => "long",
Style::Short => "short",
Style::Narrow => "narrow",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Numeric {
Always,
Auto,
}
impl Numeric {
pub(crate) fn name(self) -> &'static str {
match self {
Numeric::Always => "always",
Numeric::Auto => "auto",
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct Format {
pub(crate) style: Style,
pub(crate) numeric: Numeric,
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct Relative {
pub(crate) long: Units,
pub(crate) short: Units,
pub(crate) narrow: Units,
}
impl Relative {
fn units(&self, style: Style) -> &Units {
match style {
Style::Long => &self.long,
Style::Short => &self.short,
Style::Narrow => &self.narrow,
}
}
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct Units {
pub(crate) second: UnitPatterns,
pub(crate) minute: UnitPatterns,
pub(crate) hour: UnitPatterns,
pub(crate) day: UnitPatterns,
pub(crate) week: UnitPatterns,
pub(crate) month: UnitPatterns,
pub(crate) quarter: UnitPatterns,
pub(crate) year: UnitPatterns,
}
impl Units {
fn get(&self, unit: Unit) -> &UnitPatterns {
match unit {
Unit::Second => &self.second,
Unit::Minute => &self.minute,
Unit::Hour => &self.hour,
Unit::Day => &self.day,
Unit::Week => &self.week,
Unit::Month => &self.month,
Unit::Quarter => &self.quarter,
Unit::Year => &self.year,
}
}
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct UnitPatterns {
pub(crate) past: Forms,
pub(crate) future: Forms,
#[serde(default)]
pub(crate) relative: BTreeMap<i32, String>,
}
#[derive(Clone, Debug, Deserialize)]
pub(crate) struct Forms {
#[serde(default)]
pub(crate) one: Option<String>,
#[serde(default)]
pub(crate) few: Option<String>,
#[serde(default)]
pub(crate) many: Option<String>,
pub(crate) other: String,
}
impl Forms {
fn get(&self, category: Category) -> &str {
match category {
Category::One => self.one.as_deref().unwrap_or(&self.other),
Category::Few => self.few.as_deref().unwrap_or(&self.other),
Category::Many => self.many.as_deref().unwrap_or(&self.other),
Category::Other => &self.other,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum Category {
One,
Few,
Many,
Other,
}
fn category(language: &str, value: f64) -> Category {
let value = value.abs();
if value.fract() != 0.0 {
return Category::Other;
}
let n = value as u64;
match language {
"ru" => {
let (ten, hundred) = (n % 10, n % 100);
if ten == 1 && hundred != 11 {
Category::One
} else if (2..=4).contains(&ten) && !(12..=14).contains(&hundred) {
Category::Few
} else {
Category::Many
}
}
"pl" => {
let (ten, hundred) = (n % 10, n % 100);
if n == 1 {
Category::One
} else if (2..=4).contains(&ten) && !(12..=14).contains(&hundred) {
Category::Few
} else {
Category::Many
}
}
"fr" | "hi" | "pt" => {
if n <= 1 {
Category::One
} else {
Category::Other
}
}
"id" | "ja" | "ko" | "th" | "vi" | "zh" => Category::Other,
_ => {
if n == 1 {
Category::One
} else {
Category::Other
}
}
}
}
pub(crate) fn format(value: f64, unit: Unit, format: &Format, locale: &Locale) -> Vec<Part> {
let patterns = locale.relative.units(format.style).get(unit);
if format.numeric == Numeric::Auto
&& value.fract() == 0.0
&& let Ok(offset) = i32::try_from(value as i64)
&& let Some(named) = patterns.relative.get(&offset)
{
return vec![Part {
kind: "literal",
value: named.clone(),
}];
}
let forms = if value.is_sign_negative() {
&patterns.past
} else {
&patterns.future
};
let language = locale.tag.as_str().split(['-', '_']).next().unwrap_or("en");
let pattern = forms.get(category(language, value));
let number = number::Value::from_f64(value.abs());
let number_format = number::Format {
style: number::Style::Decimal,
notation: number::Notation::Standard,
sign: number::SignDisplay::Auto,
grouping: number::Grouping::Auto,
min_integer: 1,
rounding: number::Rounding::Fraction { min: 0, max: 3 },
strip_if_integer: false,
};
let number_parts = number::format(
&number,
&number_format,
&locale.numbers,
locale.tag.as_str(),
);
let (before, after) = pattern.split_once("{0}").unwrap_or((pattern, ""));
let mut parts = Vec::with_capacity(number_parts.len() + 2);
if !before.is_empty() {
parts.push(Part {
kind: "literal",
value: before.to_owned(),
});
}
parts.extend(number_parts);
if !after.is_empty() {
parts.push(Part {
kind: "literal",
value: after.to_owned(),
});
}
parts
}
#[cfg(test)]
mod tests {
use super::*;
use crate::web::format::{join, locale};
fn text(locale_tag: &str, value: f64, unit: Unit, style: Style, numeric: Numeric) -> String {
let locale = locale::resolve(&[locale_tag.to_owned()], "en-US");
let f = Format { style, numeric };
join(&format(value, unit, &f, &locale))
}
#[test]
fn english_formats_past_and_future_for_every_unit() {
for (unit, past, future) in [
(Unit::Second, "3 seconds ago", "in 2 seconds"),
(Unit::Minute, "3 minutes ago", "in 2 minutes"),
(Unit::Hour, "3 hours ago", "in 2 hours"),
(Unit::Day, "3 days ago", "in 2 days"),
(Unit::Week, "3 weeks ago", "in 2 weeks"),
(Unit::Month, "3 months ago", "in 2 months"),
(Unit::Quarter, "3 quarters ago", "in 2 quarters"),
(Unit::Year, "3 years ago", "in 2 years"),
] {
assert_eq!(
text("en", -3.0, unit, Style::Long, Numeric::Always),
past,
"{unit:?}"
);
assert_eq!(
text("en", 2.0, unit, Style::Long, Numeric::Always),
future,
"{unit:?}"
);
}
}
#[test]
fn auto_uses_a_named_time_and_falls_back_to_the_count() {
for (value, unit, expected) in [
(-1.0, Unit::Day, "yesterday"),
(1.0, Unit::Day, "tomorrow"),
(0.0, Unit::Day, "today"),
(-0.0, Unit::Day, "today"),
(0.0, Unit::Second, "now"),
(0.0, Unit::Minute, "this minute"),
(-1.0, Unit::Minute, "1 minute ago"),
(2.0, Unit::Day, "in 2 days"),
] {
assert_eq!(
text("en", value, unit, Style::Long, Numeric::Auto),
expected,
"{value} {unit:?}"
);
}
}
#[test]
fn english_writes_every_style() {
for (style, past, future) in [
(Style::Long, "3 seconds ago", "in 2 days"),
(Style::Short, "3 sec. ago", "in 2 days"),
(Style::Narrow, "3s ago", "in 2d"),
] {
assert_eq!(text("en", -3.0, Unit::Second, style, Numeric::Always), past);
assert_eq!(text("en", 2.0, Unit::Day, style, Numeric::Always), future);
}
}
#[test]
fn other_languages_use_their_patterns_and_plurals() {
assert_eq!(
text("tr", -5.0, Unit::Minute, Style::Long, Numeric::Always),
"5 dakika önce"
);
assert_eq!(
text("de", -3.0, Unit::Day, Style::Long, Numeric::Always),
"vor 3 Tagen"
);
assert_eq!(
text("de", 2.0, Unit::Day, Style::Long, Numeric::Auto),
"übermorgen"
);
assert_eq!(
text("ru", -1.0, Unit::Minute, Style::Long, Numeric::Always),
"1 минуту назад"
);
assert_eq!(
text("ru", -2.0, Unit::Minute, Style::Long, Numeric::Always),
"2 минуты назад"
);
assert_eq!(
text("ru", -5.0, Unit::Minute, Style::Long, Numeric::Always),
"5 минут назад"
);
assert_eq!(
text("pl", -5.0, Unit::Minute, Style::Long, Numeric::Always),
"5 minut temu"
);
assert_eq!(
text("ja", -2.0, Unit::Week, Style::Long, Numeric::Always),
"2 週間前"
);
assert_eq!(
text("ja", 0.0, Unit::Day, Style::Long, Numeric::Auto),
"今日"
);
}
#[test]
fn parts_keep_the_pattern_and_the_number_in_order() {
let locale = locale::resolve(&["en".to_owned()], "en-US");
let always = Format {
style: Style::Long,
numeric: Numeric::Always,
};
let parts = format(-1000.0, Unit::Day, &always, &locale);
let parts = parts
.iter()
.map(|p| (p.kind, p.value.as_str()))
.collect::<Vec<_>>();
assert_eq!(
parts,
[
("integer", "1"),
("group", ","),
("integer", "000"),
("literal", " days ago"),
]
);
let locale = locale::resolve(&["en".to_owned()], "en-US");
let auto = Format {
style: Style::Long,
numeric: Numeric::Auto,
};
let parts = format(-1.0, Unit::Day, &auto, &locale);
assert_eq!(parts.len(), 1);
assert_eq!(parts[0].kind, "literal");
assert_eq!(parts[0].value, "yesterday");
}
#[test]
fn zero_and_negative_zero_keep_their_sign() {
assert_eq!(
text("en", -0.0, Unit::Day, Style::Long, Numeric::Always),
"0 days ago"
);
assert_eq!(
text("en", 0.0, Unit::Day, Style::Long, Numeric::Always),
"in 0 days"
);
}
#[test]
fn a_locale_without_data_formats_in_english() {
assert_eq!(
text("xx", 2.0, Unit::Day, Style::Long, Numeric::Always),
"in 2 days"
);
}
#[test]
fn every_language_has_every_pattern() {
for lang in nsh_i18n::LANGUAGES {
let locale = locale::resolve(&[(*lang).to_owned()], "en-US");
for style in [Style::Long, Style::Short, Style::Narrow] {
for unit in [
Unit::Second,
Unit::Minute,
Unit::Hour,
Unit::Day,
Unit::Week,
Unit::Month,
Unit::Quarter,
Unit::Year,
] {
let patterns = locale.relative.units(style).get(unit);
for pattern in [
&patterns.past.other,
&patterns.future.other,
patterns.past.one.as_deref().unwrap_or(""),
patterns.future.one.as_deref().unwrap_or(""),
patterns.past.few.as_deref().unwrap_or(""),
patterns.future.few.as_deref().unwrap_or(""),
patterns.past.many.as_deref().unwrap_or(""),
patterns.future.many.as_deref().unwrap_or(""),
] {
if !pattern.is_empty() {
assert!(
pattern.contains("{0}"),
"{lang} {style:?} {unit:?} has no number: {pattern}"
);
}
}
}
}
}
}
}