| 1 |
// This file is part of ICU4X. For terms of use, please see the file |
| 2 |
// called LICENSE at the top level of the ICU4X source tree |
| 3 |
// (online at: https://github.com/unicode-org/icu4x/blob/main/LICENSE ). |
| 4 |
|
| 5 |
use fixed_decimal::{CompactDecimal, Decimal, UnsignedDecimal}; |
| 6 |
|
| 7 |
const LIMIT_18_DIGITS: u64 = 1_000_000_000_000_000_000; |
| 8 |
|
| 9 |
/// A full plural operands representation of a number. See [CLDR Plural Rules](https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules) for complete operands description. |
| 10 |
/// |
| 11 |
/// Plural operands in compliance with [CLDR Plural Rules](https://unicode.org/reports/tr35/tr35-numbers.html#Language_Plural_Rules). |
| 12 |
/// |
| 13 |
/// See [full operands description](https://unicode.org/reports/tr35/tr35-numbers.html#Operands). |
| 14 |
/// |
| 15 |
/// # Data Types |
| 16 |
/// |
| 17 |
/// The following types can be converted to [`PluralOperands`]: |
| 18 |
/// |
| 19 |
/// - Integers, signed and unsigned |
| 20 |
/// - Strings representing an arbitrary-precision decimal |
| 21 |
/// - [`Decimal`] |
| 22 |
/// |
| 23 |
/// This crate does not support selection from a floating-point number, because floats are not |
| 24 |
/// capable of carrying trailing zeros, which are required for proper plural rule selection. For |
| 25 |
/// example, in English, "1 star" has a different plural form than "1.0 stars", but this |
| 26 |
/// distinction cannot be represented using a float. Clients should use [`Decimal`] instead. |
| 27 |
/// |
| 28 |
/// # Examples |
| 29 |
/// |
| 30 |
/// From int |
| 31 |
/// |
| 32 |
/// ``` |
| 33 |
/// use icu::plurals::PluralOperands; |
| 34 |
/// use icu::plurals::RawPluralOperands; |
| 35 |
/// |
| 36 |
/// assert_eq!( |
| 37 |
/// PluralOperands::from(RawPluralOperands { |
| 38 |
/// i: 2, |
| 39 |
/// v: 0, |
| 40 |
/// w: 0, |
| 41 |
/// f: 0, |
| 42 |
/// t: 0, |
| 43 |
/// c: 0, |
| 44 |
/// }), |
| 45 |
/// PluralOperands::from(2_usize) |
| 46 |
/// ); |
| 47 |
/// ``` |
| 48 |
/// |
| 49 |
/// From &str |
| 50 |
/// |
| 51 |
/// ``` |
| 52 |
/// use icu::plurals::PluralOperands; |
| 53 |
/// use icu::plurals::RawPluralOperands; |
| 54 |
/// |
| 55 |
/// assert_eq!( |
| 56 |
/// Ok(PluralOperands::from(RawPluralOperands { |
| 57 |
/// i: 123, |
| 58 |
/// v: 2, |
| 59 |
/// w: 2, |
| 60 |
/// f: 45, |
| 61 |
/// t: 45, |
| 62 |
/// c: 0, |
| 63 |
/// })), |
| 64 |
/// "123.45".parse() |
| 65 |
/// ); |
| 66 |
/// ``` |
| 67 |
/// |
| 68 |
/// From [`Decimal`] |
| 69 |
/// |
| 70 |
/// ``` |
| 71 |
/// use fixed_decimal::Decimal; |
| 72 |
/// use icu::plurals::PluralOperands; |
| 73 |
/// use icu::plurals::RawPluralOperands; |
| 74 |
/// |
| 75 |
/// assert_eq!( |
| 76 |
/// PluralOperands::from(RawPluralOperands { |
| 77 |
/// i: 123, |
| 78 |
/// v: 2, |
| 79 |
/// w: 2, |
| 80 |
/// f: 45, |
| 81 |
/// t: 45, |
| 82 |
/// c: 0, |
| 83 |
/// }), |
| 84 |
/// (&{ |
| 85 |
/// let mut decimal = Decimal::from(12345); |
| 86 |
/// decimal.multiply_pow10(-2); |
| 87 |
/// decimal |
| 88 |
/// }) |
| 89 |
/// .into() |
| 90 |
/// ); |
| 91 |
/// ``` |
| 92 |
#[derive(Debug, Clone, Copy, PartialEq, Default)] |
| 93 |
#[allow(clippy::exhaustive_structs)] // mostly stable, new operands may be added at the cadence of ICU's release cycle |
| 94 |
pub struct PluralOperands { |
| 95 |
/// Integer value of input |
| 96 |
pub(crate) i: u64, |
| 97 |
/// Number of visible fraction digits with trailing zeros |
| 98 |
pub(crate) v: usize, |
| 99 |
/// Number of visible fraction digits without trailing zeros |
| 100 |
pub(crate) w: usize, |
| 101 |
/// Visible fraction digits with trailing zeros |
| 102 |
pub(crate) f: u64, |
| 103 |
/// Visible fraction digits without trailing zeros |
| 104 |
pub(crate) t: u64, |
| 105 |
/// Exponent of the power of 10 used in compact decimal formatting |
| 106 |
pub(crate) c: usize, |
| 107 |
} |
| 108 |
|
| 109 |
#[derive(displaydoc::Display, Debug, PartialEq, Eq)] |
| 110 |
#[non_exhaustive] |
| 111 |
#[cfg(feature = "datagen")] |
| 112 |
pub enum OperandsError { |
| 113 |
/// Input to the Operands parsing was empty. |
| 114 |
#[displaydoc("Input to the Operands parsing was empty")] |
| 115 |
Empty, |
| 116 |
/// Input to the Operands parsing was invalid. |
| 117 |
#[displaydoc("Input to the Operands parsing was invalid")] |
| 118 |
Invalid, |
| 119 |
} |
| 120 |
|
| 121 |
#[cfg(feature = "datagen")] |
| 122 |
impl core::error::Error for OperandsError {} |
| 123 |
|
| 124 |
#[cfg(feature = "datagen")] |
| 125 |
impl From<core::num::ParseIntError> for OperandsError { |
| 126 |
fn from(_: core::num::ParseIntError) -> Self { |
| 127 |
Self::Invalid |
| 128 |
} |
| 129 |
} |
| 130 |
|
| 131 |
#[cfg(feature = "datagen")] |
| 132 |
impl core::str::FromStr for PluralOperands { |
| 133 |
type Err = OperandsError; |
| 134 |
|
| 135 |
fn from_str(input: &str) -> Result<Self, Self::Err> { |
| 136 |
fn get_exponent(input: &str) -> Result<(&str, usize), OperandsError> { |
| 137 |
if let Some((base, exponent)) = input.split_once('e') { |
| 138 |
Ok((base, exponent.parse()?)) |
| 139 |
} else { |
| 140 |
Ok((input, 0)) |
| 141 |
} |
| 142 |
} |
| 143 |
|
| 144 |
if input.is_empty() { |
| 145 |
return Err(OperandsError::Empty); |
| 146 |
} |
| 147 |
|
| 148 |
let abs_str = input.strip_prefix('-').unwrap_or(input); |
| 149 |
|
| 150 |
let ( |
| 151 |
integer_digits, |
| 152 |
num_fraction_digits0, |
| 153 |
num_fraction_digits, |
| 154 |
fraction_digits0, |
| 155 |
fraction_digits, |
| 156 |
exponent, |
| 157 |
) = if let Some((int_str, rest)) = abs_str.split_once('.') { |
| 158 |
let (dec_str, exponent) = get_exponent(rest)?; |
| 159 |
|
| 160 |
let integer_digits = u64::from_str(int_str)?; |
| 161 |
|
| 162 |
let dec_str_no_zeros = dec_str.trim_end_matches('0'); |
| 163 |
|
| 164 |
let num_fraction_digits0 = dec_str.len(); |
| 165 |
let num_fraction_digits = dec_str_no_zeros.len(); |
| 166 |
|
| 167 |
let fraction_digits0 = u64::from_str(dec_str)?; |
| 168 |
let fraction_digits = |
| 169 |
if num_fraction_digits == 0 || num_fraction_digits == num_fraction_digits0 { |
| 170 |
fraction_digits0 |
| 171 |
} else { |
| 172 |
u64::from_str(dec_str_no_zeros)? |
| 173 |
}; |
| 174 |
|
| 175 |
( |
| 176 |
integer_digits, |
| 177 |
num_fraction_digits0, |
| 178 |
num_fraction_digits, |
| 179 |
fraction_digits0, |
| 180 |
fraction_digits, |
| 181 |
exponent, |
| 182 |
) |
| 183 |
} else { |
| 184 |
let (abs_str, exponent) = get_exponent(abs_str)?; |
| 185 |
let integer_digits = u64::from_str(abs_str)?; |
| 186 |
(integer_digits, 0, 0, 0, 0, exponent) |
| 187 |
}; |
| 188 |
|
| 189 |
Ok(Self { |
| 190 |
i: integer_digits, |
| 191 |
v: num_fraction_digits0, |
| 192 |
w: num_fraction_digits, |
| 193 |
f: fraction_digits0, |
| 194 |
t: fraction_digits, |
| 195 |
c: exponent, |
| 196 |
}) |
| 197 |
} |
| 198 |
} |
| 199 |
|
| 200 |
macro_rules! impl_integer_type { |
| 201 |
($ty:ident) => { |
| 202 |
impl From<$ty> for PluralOperands { |
| 203 |
#[inline] |
| 204 |
#[allow(trivial_numeric_casts)] |
| 205 |
fn from(input: $ty) -> Self { |
| 206 |
Self { |
| 207 |
i: input as u64, |
| 208 |
v: 0, |
| 209 |
w: 0, |
| 210 |
f: 0, |
| 211 |
t: 0, |
| 212 |
c: 0, |
| 213 |
} |
| 214 |
} |
| 215 |
} |
| 216 |
}; |
| 217 |
($($ty:ident)+) => { |
| 218 |
$(impl_integer_type!($ty);)+ |
| 219 |
}; |
| 220 |
} |
| 221 |
|
| 222 |
macro_rules! impl_signed_integer_type { |
| 223 |
($ty:ident) => { |
| 224 |
impl From<$ty> for PluralOperands { |
| 225 |
#[inline] |
| 226 |
fn from(input: $ty) -> Self { |
| 227 |
input.unsigned_abs().into() |
| 228 |
} |
| 229 |
} |
| 230 |
}; |
| 231 |
($($ty:ident)+) => { |
| 232 |
$(impl_signed_integer_type!($ty);)+ |
| 233 |
}; |
| 234 |
} |
| 235 |
|
| 236 |
impl_integer_type!(u8 u16 u32 u64 usize); |
| 237 |
impl_signed_integer_type!(i8 i16 i32 i64 i128 isize); |
| 238 |
|
| 239 |
impl From<u128> for PluralOperands { |
| 240 |
#[inline] |
| 241 |
fn from(input: u128) -> Self { |
| 242 |
let i = if input < LIMIT_18_DIGITS as u128 { |
| 243 |
input as u64 |
| 244 |
} else { |
| 245 |
// Add LIMIT_18_DIGITS so that is_exactly_one and is_exactly_zero |
| 246 |
// do not return true for large magnitude numbers like 1e18+1. |
| 247 |
(input % LIMIT_18_DIGITS as u128) as u64 + LIMIT_18_DIGITS |
| 248 |
}; |
| 249 |
Self { |
| 250 |
i, |
| 251 |
v: 0, |
| 252 |
w: 0, |
| 253 |
f: 0, |
| 254 |
t: 0, |
| 255 |
c: 0, |
| 256 |
} |
| 257 |
} |
| 258 |
} |
| 259 |
|
| 260 |
impl PluralOperands { |
| 261 |
#[doc(hidden)] // todo: figure out whether to expose this |
| 262 |
/// Creates a [`PluralOperands`] from a significand and power of ten. |
| 263 |
pub fn from_significand_and_exponent(dec: &UnsignedDecimal, exp: u8) -> PluralOperands { |
| 264 |
let exp_i16 = i16::from(exp); |
| 265 |
|
| 266 |
let mag_range = dec.magnitude_range(); |
| 267 |
let upper_mag = (*mag_range.end()).saturating_add(exp_i16); |
| 268 |
let lower_mag = (*mag_range.start()).saturating_add(exp_i16); |
| 269 |
let mag_high = upper_mag.clamp(0, 17); |
| 270 |
let mag_low = lower_mag.clamp(-18, 0); |
| 271 |
|
| 272 |
let mut i: u64 = 0; |
| 273 |
for magnitude in (0..=mag_high).rev() { |
| 274 |
i *= 10; |
| 275 |
i += dec.digit_at(magnitude - exp_i16) as u64; |
| 276 |
} |
| 277 |
|
| 278 |
if upper_mag > 17 { |
| 279 |
i += LIMIT_18_DIGITS; |
| 280 |
} |
| 281 |
|
| 282 |
let mut f: u64 = 0; |
| 283 |
let mut t: u64 = 0; |
| 284 |
let mut w: usize = 0; |
| 285 |
for magnitude in (mag_low..=-1).rev() { |
| 286 |
let digit = dec.digit_at(magnitude - exp_i16) as u64; |
| 287 |
f *= 10; |
| 288 |
f += digit; |
| 289 |
if digit != 0 { |
| 290 |
t = f; |
| 291 |
w = (-magnitude) as usize; |
| 292 |
} |
| 293 |
} |
| 294 |
|
| 295 |
Self { |
| 296 |
i, |
| 297 |
v: (-mag_low) as usize, |
| 298 |
w, |
| 299 |
f, |
| 300 |
t, |
| 301 |
c: usize::from(exp), |
| 302 |
} |
| 303 |
} |
| 304 |
|
| 305 |
/// Whether these [`PluralOperands`] are exactly the number 0, which might be a special case. |
| 306 |
pub(crate) fn is_exactly_zero(self) -> bool { |
| 307 |
self == Self { |
| 308 |
i: 0, |
| 309 |
v: 0, |
| 310 |
w: 0, |
| 311 |
f: 0, |
| 312 |
t: 0, |
| 313 |
c: 0, |
| 314 |
} |
| 315 |
} |
| 316 |
|
| 317 |
/// Whether these [`PluralOperands`] are exactly the number 1, which might be a special case. |
| 318 |
pub(crate) fn is_exactly_one(self) -> bool { |
| 319 |
self == Self { |
| 320 |
i: 1, |
| 321 |
v: 0, |
| 322 |
w: 0, |
| 323 |
f: 0, |
| 324 |
t: 0, |
| 325 |
c: 0, |
| 326 |
} |
| 327 |
} |
| 328 |
} |
| 329 |
|
| 330 |
impl From<&Decimal> for PluralOperands { |
| 331 |
/// Converts a [`fixed_decimal::Decimal`] to [`PluralOperands`]. Retains at most 18 |
| 332 |
/// digits each from the integer and fraction parts. |
| 333 |
fn from(dec: &Decimal) -> Self { |
| 334 |
(&dec.absolute).into() |
| 335 |
} |
| 336 |
} |
| 337 |
|
| 338 |
impl From<&UnsignedDecimal> for PluralOperands { |
| 339 |
fn from(value: &UnsignedDecimal) -> Self { |
| 340 |
Self::from_significand_and_exponent(value, 0) |
| 341 |
} |
| 342 |
} |
| 343 |
|
| 344 |
impl From<&CompactDecimal> for PluralOperands { |
| 345 |
/// Converts a [`fixed_decimal::CompactDecimal`] to [`PluralOperands`]. Retains at most 18 |
| 346 |
/// digits each from the integer and fraction parts. |
| 347 |
/// |
| 348 |
/// # Examples |
| 349 |
/// |
| 350 |
/// ``` |
| 351 |
/// use fixed_decimal::CompactDecimal; |
| 352 |
/// use fixed_decimal::Decimal; |
| 353 |
/// use icu::locale::locale; |
| 354 |
/// use icu::plurals::PluralCategory; |
| 355 |
/// use icu::plurals::PluralOperands; |
| 356 |
/// use icu::plurals::PluralRules; |
| 357 |
/// use icu::plurals::RawPluralOperands; |
| 358 |
/// |
| 359 |
/// let fixed_decimal = "1000000.20".parse::<Decimal>().unwrap(); |
| 360 |
/// let compact_decimal = "1.00000020c6".parse::<CompactDecimal>().unwrap(); |
| 361 |
/// |
| 362 |
/// assert_eq!( |
| 363 |
/// PluralOperands::from(RawPluralOperands { |
| 364 |
/// i: 1000000, |
| 365 |
/// v: 2, |
| 366 |
/// w: 1, |
| 367 |
/// f: 20, |
| 368 |
/// t: 2, |
| 369 |
/// c: 0, |
| 370 |
/// }), |
| 371 |
/// PluralOperands::from(&fixed_decimal) |
| 372 |
/// ); |
| 373 |
/// |
| 374 |
/// assert_eq!( |
| 375 |
/// PluralOperands::from(RawPluralOperands { |
| 376 |
/// i: 1000000, |
| 377 |
/// v: 2, |
| 378 |
/// w: 1, |
| 379 |
/// f: 20, |
| 380 |
/// t: 2, |
| 381 |
/// c: 6, |
| 382 |
/// }), |
| 383 |
/// PluralOperands::from(&compact_decimal) |
| 384 |
/// ); |
| 385 |
/// |
| 386 |
/// let rules = PluralRules::try_new_cardinal(locale!("fr").into()).unwrap(); |
| 387 |
/// assert_eq!(rules.category_for(&fixed_decimal), PluralCategory::Other); |
| 388 |
/// assert_eq!(rules.category_for(&compact_decimal), PluralCategory::Many); |
| 389 |
/// ``` |
| 390 |
fn from(compact: &CompactDecimal) -> Self { |
| 391 |
Self::from_significand_and_exponent(&compact.significand().absolute, compact.exponent()) |
| 392 |
} |
| 393 |
} |
| 394 |
|
| 395 |
#[cfg(test)] |
| 396 |
mod tests { |
| 397 |
use super::*; |
| 398 |
use core::str::FromStr; |
| 399 |
use fixed_decimal::Decimal; |
| 400 |
|
| 401 |
#[test] |
| 402 |
fn test_u128_overflow() { |
| 403 |
let limit_18 = LIMIT_18_DIGITS; |
| 404 |
|
| 405 |
// Small u128 |
| 406 |
let val_small: u128 = 123; |
| 407 |
let ops = PluralOperands::from(val_small); |
| 408 |
assert_eq!(ops.i, 123); |
| 409 |
assert_eq!(ops.v, 0); |
| 410 |
|
| 411 |
// u128::MAX should end in 5. |
| 412 |
let val_max = u128::MAX; |
| 413 |
let ops = PluralOperands::from(val_max); |
| 414 |
|
| 415 |
assert!(ops.i >= limit_18, "i should be offset by LIMIT_18_DIGITS"); |
| 416 |
assert_eq!(ops.i % 10, 5, "Mod 10 Check"); |
| 417 |
assert_eq!(ops.i % 100, 55, "Mod 100 Check"); |
| 418 |
|
| 419 |
// Just above limit |
| 420 |
let val_limit = limit_18 as u128; |
| 421 |
let ops = PluralOperands::from(val_limit); |
| 422 |
// limit % limit + limit = 0 + limit |
| 423 |
assert_eq!(ops.i, limit_18); |
| 424 |
|
| 425 |
let val_limit_plus_1 = val_limit + 1; |
| 426 |
let ops = PluralOperands::from(val_limit_plus_1); |
| 427 |
assert_eq!(ops.i, limit_18 + 1); |
| 428 |
} |
| 429 |
|
| 430 |
#[test] |
| 431 |
fn test_fixed_decimal_overflow() { |
| 432 |
let limit_18 = LIMIT_18_DIGITS; |
| 433 |
|
| 434 |
// Huge FixedDecimal |
| 435 |
let mut s = "1".to_string(); |
| 436 |
for _ in 0..29 { |
| 437 |
s.push('0'); |
| 438 |
} |
| 439 |
s.push('7'); |
| 440 |
|
| 441 |
let dec = Decimal::from_str(&s).unwrap(); |
| 442 |
let ops = PluralOperands::from(&dec); |
| 443 |
|
| 444 |
assert!(ops.i >= limit_18, "i should be offset"); |
| 445 |
assert_eq!(ops.i % 10, 7, "Mod 10 check"); |
| 446 |
assert_eq!(ops.i, limit_18 + 7); |
| 447 |
} |
| 448 |
|
| 449 |
#[test] |
| 450 |
fn test_i128_overflow() { |
| 451 |
let limit_18 = LIMIT_18_DIGITS; |
| 452 |
|
| 453 |
let val = i128::MIN; |
| 454 |
let ops = PluralOperands::from(val); |
| 455 |
|
| 456 |
assert!(ops.i >= limit_18); |
| 457 |
assert_eq!(ops.i % 10, 8); |
| 458 |
} |
| 459 |
|
| 460 |
#[test] |
| 461 |
fn test_compact_decimal_overflow() { |
| 462 |
use fixed_decimal::CompactDecimal; |
| 463 |
let limit_18 = LIMIT_18_DIGITS; |
| 464 |
|
| 465 |
let mut s = "9".repeat(i16::MAX as usize); |
| 466 |
s.push_str("c2"); |
| 467 |
|
| 468 |
let cd = CompactDecimal::from_str(&s).unwrap(); |
| 469 |
let ops = PluralOperands::from(&cd); |
| 470 |
|
| 471 |
assert!(ops.i >= limit_18, "i should be offset"); |
| 472 |
} |
| 473 |
} |