use std::sync::Arc;
use crate::{Error, Result};
mod data;
pub(super) fn validate_token(value: &str, empty: bool) -> Result<()> {
if (!empty && value.is_empty())
|| value
.chars()
.any(|c| c.is_control() || crate::text::is_nonrendering_mandatory_break(c))
{
return Err(Error::Data(
"numeric token must have valid single-line content".into(),
));
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum NumericGroupRepeat {
Cycle,
Last,
Stop,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NumericGrouping {
separator: String,
sizes: Vec<usize>,
repeat: NumericGroupRepeat,
}
impl NumericGrouping {
pub fn new(
separator: impl Into<String>,
sizes: Vec<usize>,
repeat: NumericGroupRepeat,
) -> Result<Self> {
let separator = separator.into();
validate_token(&separator, false)?;
if sizes.is_empty() || sizes.contains(&0) {
return Err(Error::Data(
"numeric grouping requires positive sizes".into(),
));
}
Ok(Self {
separator,
sizes,
repeat,
})
}
pub fn separator(&self) -> &str {
&self.separator
}
pub fn sizes(&self) -> &[usize] {
&self.sizes
}
pub const fn repeat(&self) -> NumericGroupRepeat {
self.repeat
}
pub(super) fn size(&self, index: usize) -> Option<usize> {
self.sizes
.get(index)
.copied()
.or_else(|| match self.repeat {
NumericGroupRepeat::Cycle => Some(self.sizes[index % self.sizes.len()]),
NumericGroupRepeat::Last => self.sizes.last().copied(),
NumericGroupRepeat::Stop => None,
})
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NumericSymbols {
positive: String,
negative: String,
percent: String,
per_mille: String,
}
impl NumericSymbols {
pub fn new(
positive: impl Into<String>,
negative: impl Into<String>,
percent: impl Into<String>,
per_mille: impl Into<String>,
) -> Result<Self> {
let value = Self {
positive: positive.into(),
negative: negative.into(),
percent: percent.into(),
per_mille: per_mille.into(),
};
for token in [
&value.positive,
&value.negative,
&value.percent,
&value.per_mille,
] {
validate_token(token, false)?;
}
Ok(value)
}
pub fn positive(&self) -> &str {
&self.positive
}
pub fn negative(&self) -> &str {
&self.negative
}
pub fn percent(&self) -> &str {
&self.percent
}
pub fn per_mille(&self) -> &str {
&self.per_mille
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NumericCurrency {
prefix: String,
suffix: String,
}
impl NumericCurrency {
pub fn new(prefix: impl Into<String>, suffix: impl Into<String>) -> Result<Self> {
let value = Self {
prefix: prefix.into(),
suffix: suffix.into(),
};
validate_token(&value.prefix, true)?;
validate_token(&value.suffix, true)?;
Ok(value)
}
pub fn prefix(&self) -> &str {
&self.prefix
}
pub fn suffix(&self) -> &str {
&self.suffix
}
}
#[derive(Debug, PartialEq, Eq)]
struct LocaleData {
decimal: String,
digits: [String; 10],
grouping: Option<NumericGrouping>,
symbols: NumericSymbols,
currency: NumericCurrency,
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct NumericLocale(Arc<LocaleData>);
impl NumericLocale {
pub fn invariant() -> Self {
Self::custom(
".",
std::array::from_fn(|i| {
char::from(b'0' + u8::try_from(i).expect("ten digits")).to_string()
}),
Some(
NumericGrouping::new(",", vec![3], NumericGroupRepeat::Cycle)
.expect("invariant grouping"),
),
NumericSymbols::new("+", "-", "%", "‰").expect("invariant symbols"),
NumericCurrency::new("$", "").expect("invariant currency"),
)
.expect("invariant locale")
}
pub fn named(name: &str) -> Result<Self> {
data::named(name)
}
pub fn named_ids() -> &'static [&'static str] {
data::IDS
}
pub fn custom(
decimal: impl Into<String>,
digits: [String; 10],
grouping: Option<NumericGrouping>,
symbols: NumericSymbols,
currency: NumericCurrency,
) -> Result<Self> {
let decimal = decimal.into();
validate_token(&decimal, false)?;
for (index, digit) in digits.iter().enumerate() {
validate_token(digit, false)?;
if digits[..index].contains(digit) {
return Err(Error::Data("numeric digit tokens must be distinct".into()));
}
}
Ok(Self(Arc::new(LocaleData {
decimal,
digits,
grouping,
symbols,
currency,
})))
}
pub fn decimal(&self) -> &str {
&self.0.decimal
}
pub fn digits(&self) -> &[String; 10] {
&self.0.digits
}
pub fn grouping(&self) -> Option<&NumericGrouping> {
self.0.grouping.as_ref()
}
pub fn symbols(&self) -> &NumericSymbols {
&self.0.symbols
}
pub fn currency(&self) -> &NumericCurrency {
&self.0.currency
}
pub(super) fn observe(&self, round: &mut crate::layout::kernel::FeedbackRound) -> Result<()> {
round.observe_string(self.decimal())?;
for token in self.digits() {
round.observe_string(token)?;
}
round.observe_count(usize::from(self.grouping().is_some()))?;
if let Some(grouping) = self.grouping() {
round.observe_string(grouping.separator())?;
round.observe_count(grouping.sizes().len())?;
for size in grouping.sizes() {
round.observe_count(*size)?;
}
round.observe_count(grouping.repeat() as usize)?;
}
for token in [
self.symbols().positive(),
self.symbols().negative(),
self.symbols().percent(),
self.symbols().per_mille(),
self.currency().prefix(),
self.currency().suffix(),
] {
round.observe_string(token)?;
}
Ok(())
}
}