mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 05:14:24 +00:00
refactor(i18n): satisfy Clippy pedantic lints
This commit is contained in:
@@ -30,6 +30,7 @@ impl Collator {
|
||||
/// Sorting for `locale`, a language code such as `sv`, `pt-br` or `zh-hant` (any case, `-`
|
||||
/// or `_`, glibc forms such as `sv_SE.UTF-8` and `sr_RS@latin`). A BCP 47 collation type
|
||||
/// picks another order where there is one: `zh-hant-u-co-pinyin`, `zh-hans-u-co-stroke`.
|
||||
#[must_use]
|
||||
pub fn new(locale: &str) -> Collator {
|
||||
let mut prefs: CollatorPreferences = Locale::try_from_str(&bcp47(locale)).unwrap_or(Locale::UNKNOWN).into();
|
||||
prefs.numeric_ordering = Some(CollationNumericOrdering::True);
|
||||
@@ -46,6 +47,7 @@ impl Collator {
|
||||
/// the collation counts as equal (`Layer 2` and `Layer 02`) is in code point order, so a sort
|
||||
/// doesn't depend on the input order. Without collation data (never with the embedded data)
|
||||
/// this is code point order.
|
||||
#[must_use]
|
||||
pub fn compare(&self, a: &str, b: &str) -> Ordering {
|
||||
match &self.0 {
|
||||
Some(c) => c.as_borrowed().compare(a, b).then_with(|| a.cmp(b)),
|
||||
|
||||
+11
-3
@@ -15,7 +15,7 @@
|
||||
//! `IRMAK` and `ırmak`. Plain `str::to_lowercase` follows no locale and turns `İ` into `i` plus a
|
||||
//! combining dot, which nothing typed would match.
|
||||
//!
|
||||
//! The Turkish i handling and sigma folding come from PdfCraft's `fold_case` (snipeTR,
|
||||
//! The Turkish i handling and sigma folding come from `PdfCraft`'s `fold_case` (snipeTR,
|
||||
//! nevicia2010-hub).
|
||||
|
||||
use std::ops::Range;
|
||||
@@ -34,6 +34,7 @@ pub struct Folder {
|
||||
impl Folder {
|
||||
/// Case- and accent-insensitive folding for `locale`, a language code such as `tr`, `pt-br`
|
||||
/// or `zh-hant` (any case, `-` or `_`).
|
||||
#[must_use]
|
||||
pub fn new(locale: &str) -> Folder {
|
||||
let language = locale.split(['-', '_', '.', '@']).next().unwrap_or_default();
|
||||
Folder { turkic: language.eq_ignore_ascii_case("tr") || language.eq_ignore_ascii_case("az"), accents: false }
|
||||
@@ -41,11 +42,13 @@ impl Folder {
|
||||
|
||||
/// Accents count: `é` no longer matches `e`, and a match can't end on a letter whose accent it
|
||||
/// leaves out.
|
||||
#[must_use]
|
||||
pub fn keep_accents(self) -> Folder {
|
||||
Folder { accents: true, ..self }
|
||||
}
|
||||
|
||||
/// `s` folded, with the map back to `s`.
|
||||
#[must_use]
|
||||
pub fn fold(&self, s: &str) -> Folded {
|
||||
let nfkd = DecomposingNormalizerBorrowed::new_nfkd();
|
||||
let extend = CodePointSetData::new::<GraphemeExtend>();
|
||||
@@ -75,17 +78,19 @@ impl Folder {
|
||||
}
|
||||
|
||||
/// `s` folded, without the map: a key to compare or store.
|
||||
#[must_use]
|
||||
pub fn key(&self, s: &str) -> String {
|
||||
self.fold(s).text
|
||||
}
|
||||
|
||||
/// Whether `haystack` contains `needle`, both folded.
|
||||
#[must_use]
|
||||
pub fn contains(&self, haystack: &str, needle: &str) -> bool {
|
||||
self.fold(haystack).find(&self.fold(needle)).is_some()
|
||||
}
|
||||
|
||||
/// One cluster, already in NFKD.
|
||||
fn fold_cluster(&self, cluster: &str, out: &mut String) {
|
||||
fn fold_cluster(self, cluster: &str, out: &mut String) {
|
||||
let mut chars = cluster.chars().peekable();
|
||||
while let Some(c) = chars.next() {
|
||||
match c {
|
||||
@@ -219,6 +224,7 @@ pub struct Folded {
|
||||
|
||||
impl Folded {
|
||||
/// The folded text.
|
||||
#[must_use]
|
||||
pub fn as_str(&self) -> &str {
|
||||
&self.text
|
||||
}
|
||||
@@ -226,6 +232,7 @@ impl Folded {
|
||||
/// The source byte range that folded bytes `range` came from, widened to whole source
|
||||
/// characters with their accents: `ss` in the folding of `Straße` maps back to `ß`, `e` in
|
||||
/// that of `é` to the whole `é`. An empty range maps to an empty one.
|
||||
#[must_use]
|
||||
pub fn source_range(&self, range: Range<usize>) -> Range<usize> {
|
||||
// The last cluster starting at or before `at` is the one holding it: clusters that fold to
|
||||
// nothing share their offset with the next one.
|
||||
@@ -241,6 +248,7 @@ impl Folded {
|
||||
|
||||
/// The first match of `needle` (folded the same way), as a byte range of the source text.
|
||||
/// An empty needle matches at the start.
|
||||
#[must_use]
|
||||
pub fn find(&self, needle: &Folded) -> Option<Range<usize>> {
|
||||
self.matches(needle).next()
|
||||
}
|
||||
@@ -363,10 +371,10 @@ mod tests {
|
||||
|
||||
#[test]
|
||||
fn matches_map_back_to_the_source() {
|
||||
let f = Folder::new("en");
|
||||
fn find<'a>(f: Folder, haystack: &'a str, needle: &str) -> Option<&'a str> {
|
||||
f.fold(haystack).find(&f.fold(needle)).map(|r| &haystack[r])
|
||||
}
|
||||
let f = Folder::new("en");
|
||||
let find = |haystack, needle| find(f, haystack, needle);
|
||||
assert_eq!(find("Große Straße", "strasse"), Some("Straße"));
|
||||
assert_eq!(find("Große Straße", "SS"), Some("ß"));
|
||||
|
||||
@@ -4,7 +4,7 @@
|
||||
use std::fmt;
|
||||
|
||||
use fixed_decimal::{Decimal, Sign};
|
||||
use icu_decimal::{DecimalFormatter, parts};
|
||||
use icu_decimal::{DecimalFormatter, options::DecimalFormatterOptions, parts};
|
||||
use icu_locale_core::Locale;
|
||||
use icu_locale_core::extensions::unicode::{key, value};
|
||||
use writeable::{Part, PartsWrite, Writeable};
|
||||
@@ -46,7 +46,8 @@ impl Format {
|
||||
if digits == Digits::Latin {
|
||||
locale.extensions.unicode.keywords.set(key!("nu"), value!("latn"));
|
||||
}
|
||||
let decimal = data::provider().and_then(|p| DecimalFormatter::try_new_with_buffer_provider(p, (&locale).into(), Default::default()).ok());
|
||||
let decimal = data::provider()
|
||||
.and_then(|p| DecimalFormatter::try_new_with_buffer_provider(p, (&locale).into(), DecimalFormatterOptions::default()).ok());
|
||||
let mut format = Format { decimal, group: None, point: None, percent: ("", "%"), marks: Marks::default() };
|
||||
// The locale's own separators and digits, read from a number that shows them all.
|
||||
let probe = format.parts(&Decimal::try_from_str("-1234567.5").unwrap_or_default());
|
||||
@@ -81,6 +82,7 @@ impl Format {
|
||||
}
|
||||
|
||||
/// The format for a locale tag (`de-CH`, `ar-EG`), with the locale's own digits.
|
||||
#[must_use]
|
||||
pub fn from_tag(tag: &str) -> Format {
|
||||
Format::new(&Region::from_tag(tag), Digits::Locale)
|
||||
}
|
||||
@@ -92,6 +94,7 @@ impl Format {
|
||||
|
||||
/// `value` rounded to `decimals` digits after the decimal separator; infinities and NaN are
|
||||
/// `∞`, `-∞` and `NaN`.
|
||||
#[must_use]
|
||||
pub fn number(&self, value: f64, decimals: usize) -> String {
|
||||
match to_decimal(value, decimals) {
|
||||
Some(d) => self.write(&d),
|
||||
@@ -101,6 +104,7 @@ impl Format {
|
||||
|
||||
/// [`Self::number`] without grouping separators, for values such as pixel sizes and years:
|
||||
/// `1920`, `١٩٢٠`, `1234,5`.
|
||||
#[must_use]
|
||||
pub fn number_ungrouped(&self, value: f64, decimals: usize) -> String {
|
||||
match to_decimal(value, decimals) {
|
||||
Some(d) => {
|
||||
@@ -113,6 +117,7 @@ impl Format {
|
||||
|
||||
/// `ratio` as a percentage with `decimals` digits after the decimal separator: `0.5` is
|
||||
/// `50%`, `50 %` (French, German), `%50` (Turkish), `٥٠٪` (Egyptian Arabic).
|
||||
#[must_use]
|
||||
pub fn percent(&self, ratio: f64, decimals: usize) -> String {
|
||||
let Some(d) = to_decimal(ratio * 100.0, decimals) else {
|
||||
return format!("{}{}{}", self.percent.0, non_finite(ratio), self.percent.1);
|
||||
@@ -212,7 +217,7 @@ impl PartsWrite for Sink<'_> {
|
||||
_ => return result,
|
||||
};
|
||||
if slot.is_empty() {
|
||||
*slot = written.to_owned();
|
||||
written.clone_into(slot);
|
||||
}
|
||||
}
|
||||
result
|
||||
@@ -370,7 +375,7 @@ mod tests {
|
||||
for (tag, want) in
|
||||
[("en", "50%"), ("de", "50\u{a0}%"), ("fr", "12,5\u{a0}%"), ("tr", "%50"), ("ar-EG", "٥٠٪\u{61c}"), ("fa", "۵۰٪"), ("hi", "50%")]
|
||||
{
|
||||
let decimals = if tag == "fr" { 1 } else { 0 };
|
||||
let decimals = usize::from(tag == "fr");
|
||||
let ratio = if tag == "fr" { 0.125 } else { 0.5 };
|
||||
assert_eq!(Format::from_tag(tag).percent(ratio, decimals), want, "{tag}");
|
||||
}
|
||||
|
||||
+12
-5
@@ -113,7 +113,9 @@ impl Locale {
|
||||
rows.entry(e.context).or_default().insert(e.source, e.translation);
|
||||
}
|
||||
}
|
||||
problems.iter().for_each(|p| log::warn!("translation catalog: {p}; row skipped"));
|
||||
for p in &problems {
|
||||
log::warn!("translation catalog: {p}; row skipped");
|
||||
}
|
||||
Parsed { rows, problems }
|
||||
})
|
||||
}
|
||||
@@ -156,6 +158,7 @@ impl I18n {
|
||||
/// to left, say). Locales that can't be used are skipped and come back as problems for the app
|
||||
/// to log. A locale's bad rows are logged (`log::warn!`) when it is first looked up in, and
|
||||
/// [`I18n::check_all`] lists them all.
|
||||
#[must_use]
|
||||
pub fn new(embedded: &'static Embedded, offered: &[&str]) -> (I18n, Vec<String>) {
|
||||
let mut problems = Vec::new();
|
||||
let mut locales = vec![bare("en"), bare("pseudo")];
|
||||
@@ -417,6 +420,7 @@ impl I18n {
|
||||
/// value that already is one isolate keeps it; pass numbers, paths and codes through [`ltr`].
|
||||
/// Other text gets no marks, and a value's own isolate is taken off. Unknown placeholders stay as written,
|
||||
/// and inserted values are never read as templates, so a file name containing `{n}` stays intact.
|
||||
#[must_use]
|
||||
pub fn fmt(template: &str, args: &[(&str, &str)]) -> String {
|
||||
fill(template, args, true)
|
||||
}
|
||||
@@ -424,6 +428,7 @@ pub fn fmt(template: &str, args: &[(&str, &str)]) -> String {
|
||||
/// [`fmt`] without isolates, for text that goes where the marks would get in the way: file
|
||||
/// names, logs, terminals, text compared or parsed later. Every isolate mark is taken off, in
|
||||
/// the template and in the values.
|
||||
#[must_use]
|
||||
pub fn fmt_plain(template: &str, args: &[(&str, &str)]) -> String {
|
||||
strip_isolates(&fill(template, args, false))
|
||||
}
|
||||
@@ -444,6 +449,7 @@ const ALM: char = '\u{061C}';
|
||||
/// `value` as a first-strong isolate (FSI…PDI): it takes the direction of its first strong
|
||||
/// letter and can't reorder the text around it. What [`fmt`] does to each value in text with a
|
||||
/// right-to-left letter.
|
||||
#[must_use]
|
||||
pub fn isolate(value: &str) -> String {
|
||||
wrap(FSI, value)
|
||||
}
|
||||
@@ -452,12 +458,14 @@ pub fn isolate(value: &str) -> String {
|
||||
/// codes, which read left to right in every language. In an RTL first-strong isolate, the
|
||||
/// segments of `/home/مستخدم/file.txt` would run right to left. [`fmt`] takes the isolate off
|
||||
/// again in text with no right-to-left letter.
|
||||
#[must_use]
|
||||
pub fn ltr(value: &str) -> String {
|
||||
wrap(LRI, value)
|
||||
}
|
||||
|
||||
/// `text` without isolate marks (LRI, RLI, FSI, PDI): a [`fmt`] or [`I18n::trn`] result made fit
|
||||
/// for a file name, a log or a comparison.
|
||||
#[must_use]
|
||||
pub fn strip_isolates(text: &str) -> String {
|
||||
text.chars().filter(|c| !matches!(*c, LRI | RLI | FSI | PDI)).collect()
|
||||
}
|
||||
@@ -483,14 +491,13 @@ fn wrap(initiator: char, value: &str) -> String {
|
||||
PDF if open.last() == Some(&false) => {
|
||||
open.pop();
|
||||
}
|
||||
PDF => continue,
|
||||
PDI if isolates > 0 => {
|
||||
while open.pop() == Some(false) {
|
||||
out.push(PDF);
|
||||
}
|
||||
isolates -= 1;
|
||||
}
|
||||
PDI => continue,
|
||||
PDF | PDI => continue,
|
||||
_ => {}
|
||||
}
|
||||
out.push(c);
|
||||
@@ -713,11 +720,11 @@ fn plural_rules(code: &str) -> Option<(PluralRules, Vec<PluralCategory>)> {
|
||||
categories.push(c);
|
||||
}
|
||||
}
|
||||
categories.sort_by_key(rank);
|
||||
categories.sort_by_key(|c| rank(*c));
|
||||
Some((rules, categories))
|
||||
}
|
||||
|
||||
fn rank(c: &PluralCategory) -> u8 {
|
||||
fn rank(c: PluralCategory) -> u8 {
|
||||
match c {
|
||||
PluralCategory::Zero => 0,
|
||||
PluralCategory::One => 1,
|
||||
|
||||
@@ -80,6 +80,12 @@ impl Format {
|
||||
///
|
||||
/// Percent signs, units and the space before a unit (`50 %`, `12 px`) are not read; strip them
|
||||
/// first. Anything else is an error rather than a guess.
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns `NumberError::Empty` for an empty input or one reduced to spaces and a sign,
|
||||
/// `Unexpected` for an invalid character, `MixedDigits` for mixed digit sets, `Separator`
|
||||
/// for misplaced marks, and `TooLarge` when the parsed value is not finite.
|
||||
pub fn parse(&self, text: &str) -> Result<f64, NumberError> {
|
||||
let marks = self.marks;
|
||||
let text: String = text.chars().filter(|c| !is_bidi_mark(*c)).collect();
|
||||
@@ -129,6 +135,11 @@ impl Format {
|
||||
/// The number in `text` as `locale` (a language tag, `de-CH`, `ar_EG.UTF-8`) writes it:
|
||||
/// [`Format::parse`] for [`Format::from_tag`]. Build the [`Format`] once to read many numbers. A
|
||||
/// locale CLDR doesn't know reads as CLDR's root does (`1,234.5`).
|
||||
///
|
||||
/// # Errors
|
||||
///
|
||||
/// Returns the same `NumberError` as [`Format::parse`] for invalid digits, characters, or
|
||||
/// separators, or when the value is not finite.
|
||||
pub fn parse_number(text: &str, locale: &str) -> Result<f64, NumberError> {
|
||||
Format::from_tag(locale).parse(text)
|
||||
}
|
||||
|
||||
@@ -73,6 +73,7 @@ impl Region {
|
||||
/// `nu` stays in the number and time locales (`ar-EG-u-nu-latn`). `C` and `POSIX` are the C
|
||||
/// locale: English, A4, metric, a `.` decimal and no grouping. An empty or unreadable tag is
|
||||
/// `en-US`; a bare `en` is the United States, any other bare language has no territory.
|
||||
#[must_use]
|
||||
pub fn from_tag(tag: &str) -> Region {
|
||||
match Tag::parse(tag) {
|
||||
Some(tag) => Region::from_parts(&tag),
|
||||
@@ -85,6 +86,7 @@ impl Region {
|
||||
|
||||
/// The region for an app's saved region setting: `""` or `auto` (any case) is
|
||||
/// [`Region::system`], anything else a locale tag for [`Region::from_tag`].
|
||||
#[must_use]
|
||||
pub fn from_setting(setting: &str) -> Region {
|
||||
let setting = setting.trim();
|
||||
if setting.is_empty() || setting.eq_ignore_ascii_case("auto") { Region::system() } else { Region::from_tag(setting) }
|
||||
@@ -99,6 +101,7 @@ impl Region {
|
||||
/// - Linux and the BSDs: `LC_ALL`, else each of `LC_NUMERIC`, `LC_TIME`, `LC_MEASUREMENT` and
|
||||
/// `LC_PAPER` on its own, else `LANG`.
|
||||
/// - The web and Android: the preferred language, the only locale they expose.
|
||||
#[must_use]
|
||||
pub fn system() -> Region {
|
||||
static SYSTEM: OnceLock<Region> = OnceLock::new();
|
||||
SYSTEM.get_or_init(read_system).clone()
|
||||
@@ -298,6 +301,7 @@ fn from_apple(identifier: &str, metric: bool, decimal: &str, grouping: &str, hou
|
||||
/// A grouping separator the system sets: none at all when empty (Windows' `sThousand` the user
|
||||
/// cleared), else one character.
|
||||
#[cfg(any(test, windows, target_vendor = "apple"))]
|
||||
#[expect(clippy::option_option, reason = "The public setting distinguishes following the locale, no grouping, and a custom separator")]
|
||||
fn grouping(s: &str) -> Option<Option<char>> {
|
||||
if s.is_empty() { Some(None) } else { single_char(s).map(Some) }
|
||||
}
|
||||
|
||||
@@ -39,6 +39,7 @@ pub enum Script {
|
||||
|
||||
impl Script {
|
||||
/// The ISO 15924 code, `Latn`.
|
||||
#[must_use]
|
||||
pub fn code(self) -> &'static str {
|
||||
match self {
|
||||
Script::Arab => "Arab",
|
||||
@@ -75,6 +76,7 @@ impl Script {
|
||||
}
|
||||
|
||||
/// Whether text in this script runs right to left.
|
||||
#[must_use]
|
||||
pub fn rtl(self) -> bool {
|
||||
matches!(self, Script::Arab | Script::Hebr | Script::Syrc | Script::Thaa)
|
||||
}
|
||||
@@ -112,8 +114,12 @@ pub enum Han {
|
||||
/// where it is the language's own script. A language not in the table is taken to be written in
|
||||
/// Latin.
|
||||
// ponytail: the languages a Craft app ships or could plausibly ship; add a row with the locale.
|
||||
#[must_use]
|
||||
pub fn scripts(tag: &str) -> &'static [Script] {
|
||||
use Script::*;
|
||||
use Script::{
|
||||
Arab, Armn, Beng, Cyrl, Deva, Ethi, Geor, Grek, Gujr, Guru, Hang, Hani, Hebr, Hira, Kana, Khmr, Knda, Laoo, Latn, Mlym, Mymr, Orya, Sinh,
|
||||
Syrc, Taml, Telu, Thaa, Thai, Tibt,
|
||||
};
|
||||
let tag = Subtags::parse(tag);
|
||||
if let Some(s) = tag.script.as_deref().and_then(subtag_scripts) {
|
||||
return s;
|
||||
@@ -154,6 +160,7 @@ pub fn scripts(tag: &str) -> &'static [Script] {
|
||||
}
|
||||
|
||||
/// The direction of a language tag's text: right to left when its main script is.
|
||||
#[must_use]
|
||||
pub fn direction(tag: &str) -> Direction {
|
||||
match scripts(tag).first() {
|
||||
Some(s) if s.rtl() => Direction::Rtl,
|
||||
@@ -165,6 +172,7 @@ pub fn direction(tag: &str) -> Direction {
|
||||
/// P3): the contents of isolates (LRI, RLI or FSI up to the matching PDI) are skipped, and the
|
||||
/// search stops at the first paragraph separator. `None` when the paragraph has no strong
|
||||
/// character; P3 then reads it as left to right, and an app may use the interface direction.
|
||||
#[must_use]
|
||||
pub fn base_direction(text: &str) -> Option<Direction> {
|
||||
match unicode_bidi::get_base_direction(text) {
|
||||
unicode_bidi::Direction::Ltr => Some(Direction::Ltr),
|
||||
@@ -175,9 +183,10 @@ pub fn base_direction(text: &str) -> Option<Direction> {
|
||||
|
||||
/// The forms a language tag's Han characters take: `zh-CN`, `zh-SG`, `zh-Hans` and plain `zh` →
|
||||
/// Simplified; `zh-TW`, `zh-Hant` and the other regions CLDR writes in Traditional characters
|
||||
/// (`zh-US`, `zh-AU`) → Traditional; `zh-HK`, `zh-MO`, `zh-Hant-HK` and `yue` → HongKong; `ja` →
|
||||
/// (`zh-US`, `zh-AU`) → Traditional; `zh-HK`, `zh-MO`, `zh-Hant-HK` and `yue` → `HongKong`; `ja` →
|
||||
/// Japanese; `ko` → Korean. `None` for a language not written with Han, which leaves the choice
|
||||
/// to the font stack.
|
||||
#[must_use]
|
||||
pub fn han(tag: &str) -> Option<Han> {
|
||||
let tag = Subtags::parse(tag);
|
||||
let hong_kong = matches!(tag.region.as_deref(), Some("hk" | "mo"));
|
||||
@@ -202,8 +211,14 @@ pub fn han(tag: &str) -> Option<Han> {
|
||||
// ponytail: mn-CN → Mong is left out until vertical Mongolian layout is supported.
|
||||
pub(crate) fn region_script(language: &str, region: &str) -> Option<&'static str> {
|
||||
Some(match (language, region) {
|
||||
("az", "iq" | "ir") | ("ha", "cm" | "sd") | ("kk", "af" | "cn" | "ir" | "mn") | ("ku", "iq" | "ir" | "lb") => "arab",
|
||||
("ky", "cn") | ("ms", "cc") | ("pa", "pk") | ("tg", "pk") | ("uz", "af") => "arab",
|
||||
("az", "iq" | "ir")
|
||||
| ("ha", "cm" | "sd")
|
||||
| ("kk", "af" | "cn" | "ir" | "mn")
|
||||
| ("ku", "iq" | "ir" | "lb")
|
||||
| ("ky", "cn")
|
||||
| ("ms", "cc")
|
||||
| ("pa" | "tg", "pk")
|
||||
| ("uz", "af") => "arab",
|
||||
("az", "ru") | ("ku", "am" | "az" | "ge" | "tm") | ("ug", "kz" | "mn") | ("uz", "cn") => "cyrl",
|
||||
("ky", "tr") | ("sr", "me" | "ro" | "tr") => "latn",
|
||||
("sd", "in") => "deva",
|
||||
@@ -216,7 +231,10 @@ pub(crate) fn region_script(language: &str, region: &str) -> Option<&'static str
|
||||
/// The scripts a script subtag stands for, including the CLDR unions (`jpan`, `kore`). `None` for
|
||||
/// one not in [`Script`], so the language's own scripts apply.
|
||||
fn subtag_scripts(subtag: &str) -> Option<&'static [Script]> {
|
||||
use Script::*;
|
||||
use Script::{
|
||||
Arab, Armn, Beng, Cyrl, Deva, Ethi, Geor, Grek, Gujr, Guru, Hang, Hani, Hebr, Hira, Kana, Khmr, Knda, Laoo, Latn, Mlym, Mong, Mymr, Orya,
|
||||
Sinh, Syrc, Taml, Telu, Thaa, Thai, Tibt,
|
||||
};
|
||||
Some(match subtag {
|
||||
"hans" | "hant" | "hani" => &[Hani],
|
||||
"jpan" => &[Hani, Hira, Kana],
|
||||
|
||||
@@ -33,6 +33,7 @@ impl SizeUnit {
|
||||
/// // `12 MB`, `3.4 MB`, `640 KB`: decimal steps, whole kilobytes, no decimals from 10 MB.
|
||||
/// let style = FileSize::DECIMAL.smallest(SizeUnit::Kilo).largest(SizeUnit::Mega).unit_decimals(SizeUnit::Kilo, 0).whole_from(10);
|
||||
/// ```
|
||||
#[must_use]
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
|
||||
pub struct FileSize {
|
||||
step: u64,
|
||||
@@ -104,6 +105,10 @@ impl FileSize {
|
||||
}
|
||||
|
||||
/// The unit `bytes` is written in, the number in it and its digits after the point.
|
||||
#[expect(
|
||||
clippy::cast_precision_loss,
|
||||
reason = "File sizes are displayed as rounded f64 values; exact u64 arithmetic is not required for presentation"
|
||||
)]
|
||||
fn parts(&self, bytes: u64) -> (SizeUnit, f64, usize) {
|
||||
let (smallest, largest) = (self.smallest.min(self.largest), self.largest);
|
||||
let mut unit = smallest;
|
||||
@@ -137,6 +142,7 @@ impl FileSize {
|
||||
}
|
||||
}
|
||||
|
||||
#[expect(clippy::cast_precision_loss, reason = "Unit scales are displayed as f64 values; exact u64 arithmetic is not required for presentation")]
|
||||
fn scale(&self, unit: SizeUnit) -> f64 {
|
||||
(self.step as f64).powi(unit as i32)
|
||||
}
|
||||
@@ -160,6 +166,7 @@ impl FileSize {
|
||||
impl I18n {
|
||||
/// `bytes` as a file size in `lang`, written the way `style` says (`1.5 MB`, `512 bytes`), the
|
||||
/// number as [`I18n::format`] writes it (`1,5 Mo`).
|
||||
#[must_use]
|
||||
pub fn file_size(&self, lang: Lang, bytes: u64, style: FileSize) -> String {
|
||||
let (unit, n, decimals) = style.parts(bytes);
|
||||
if unit == SizeUnit::Byte && !style.byte_symbol {
|
||||
@@ -171,6 +178,7 @@ impl I18n {
|
||||
/// `value` with `decimals` digits after the decimal separator in the unit template `unit`, an
|
||||
/// English catalog key with the number as `{n}` (`{n} px`, `{n} dB`), the number as
|
||||
/// [`I18n::format`] writes it. Percentages are [`crate::Format::percent`].
|
||||
#[must_use]
|
||||
pub fn measure(&self, lang: Lang, value: f64, decimals: usize, unit: &str) -> String {
|
||||
self.unit_text(lang, unit, &self.format().number(value, decimals))
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user