From b3575af024aee5668bc079300a5508a855306499 Mon Sep 17 00:00:00 2001 From: Codex Date: Sun, 29 Nov 2026 21:42:01 +0100 Subject: [PATCH] Compress browser locale provider data losslessly --- Cargo.lock | 2 + crates/i18n/Cargo.toml | 9 ++++- crates/i18n/README.md | 13 +++--- crates/i18n/build.rs | 39 ++++++++++++++++++ crates/i18n/src/blob.rs | 82 ++++++++++++++++++++++++++++++++++++++ crates/i18n/src/collate.rs | 2 +- crates/i18n/src/lib.rs | 6 ++- 7 files changed, 144 insertions(+), 9 deletions(-) create mode 100644 crates/i18n/build.rs create mode 100644 crates/i18n/src/blob.rs diff --git a/Cargo.lock b/Cargo.lock index d9a4bed7c5..0d687f1100 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3050,6 +3050,8 @@ version = "0.1.0" name = "craft-i18n" version = "0.1.0" dependencies = [ + "brotli 8.0.4", + "brotli-decompressor 5.0.3", "chrono", "fixed_decimal", "icu_calendar", diff --git a/crates/i18n/Cargo.toml b/crates/i18n/Cargo.toml index 4328b8fe75..337e6417aa 100644 --- a/crates/i18n/Cargo.toml +++ b/crates/i18n/Cargo.toml @@ -21,7 +21,7 @@ icu_datetime = { version = "~2.3", default-features = false, features = ["serde" icu_time = { version = "~2.3", default-features = false } icu_provider = { version = "~2.3", default-features = false, features = ["sync"] } icu_provider_adapters = { version = "~2.3", default-features = false } -icu_provider_blob = { version = "~2.3", default-features = false } +icu_provider_blob = { version = "~2.3", default-features = false, features = ["alloc"] } writeable = "0.6" log = "0.4" sys-locale = "0.3" @@ -34,10 +34,17 @@ icu_collator = { version = "~2.3.1", default-features = false, features = ["serd unicode-bidi = "0.3" [target.'cfg(target_arch = "wasm32")'.dependencies] +brotli-decompressor = "5" sys-locale = { version = "0.3", features = ["js"] } # The browser's `Date` supplies the local offset. chrono = { workspace = true, features = ["clock", "wasmbind"] } +[build-dependencies] +brotli = "8" + +[dev-dependencies] +brotli-decompressor = "5" + # The regional format (Region::system); safe registry reads, MIT OR Apache-2.0. [target.'cfg(windows)'.dependencies] windows-registry = "0.6" diff --git a/crates/i18n/README.md b/crates/i18n/README.md index 544f715505..33dba40156 100644 --- a/crates/i18n/README.md +++ b/crates/i18n/README.md @@ -123,11 +123,13 @@ The app keeps its `tl!` macro, its language setting (`"auto"` → `I18N.system_l (`1.234 Dateien`, `١٬٢٣٤ ملفًا`); for names written into documents or files (`Copy 1234`), use `trn_plain`, which writes `0`–`9` without grouping or isolate marks. - **CLDR data:** decimal symbols, digits and plural rules (`data/numbers.postcard`, about 10 KB), - percent patterns (`data/locales.rs`) and date data (`data/dates.postcard`, about 340 KB) cover + percent patterns (`data/locales.rs`) and date data (`data/dates.postcard`, about 430 KB) cover every CLDR locale; `data/generate.sh` rebuilds all three from CLDR 48.2.1. The ICU4X crates are - pinned to one minor version (`~2.3`), the one the data is generated for. The ICU4X code and the - number data add about 90 KB to a stripped release build and 80 KB to wasm; the date data is - extra. + pinned to one minor version (`~2.3`), the one the data is generated for. Native builds embed the + static provider blobs. Browser builds embed lossless Brotli copies and restore each provider + once on first use, preserving every locale and rule. The build writes packed copies only to + `OUT_DIR`; the checked-in source data and its generation commands are unchanged. Tests compare + every decoded byte with the source blobs and load the result as an owned ICU provider. - **Dates:** `DateFormat` (`I18n::dates`, `set_dates`, `reset_dates`, as `I18n::format` is for numbers) writes dates and times for the region's time locale and clock in the `Short`, `Medium`, `Long` and `Full` lengths, month and weekday names (`NameLength`), the first day of the week and @@ -165,4 +167,5 @@ The app keeps its `tl!` macro, its language setting (`"auto"` → `I18N.system_l - **Sorting** (`Collator`, feature `collate`): ICU4X collation for the locales craft-i18n ships, Persian and Hindi, with digits compared by value (`Layer 2` before `Layer 10`) and `-u-co-pinyin` / `-u-co-stroke` for Chinese. The data (754 KB) is regenerated by `data/generate-collation.sh`; - the feature adds about 1 MB to a release binary or wasm module (320 KB gzipped). + native builds embed it directly, while browser builds use the same lossless packing as the + number and date providers. diff --git a/crates/i18n/build.rs b/crates/i18n/build.rs new file mode 100644 index 0000000000..f2be878371 --- /dev/null +++ b/crates/i18n/build.rs @@ -0,0 +1,39 @@ +//! Pack the existing locale data losslessly for browser builds; native providers stay static. + +use std::io::Write as _; +use std::path::PathBuf; + +fn main() { + if let Err(error) = pack() { + println!("cargo::error=packing locale data: {error}"); + } +} + +fn pack() -> Result<(), Box> { + let out = PathBuf::from(std::env::var_os("OUT_DIR").ok_or("OUT_DIR is missing")?); + let mut declarations = String::new(); + for name in ["numbers", "dates", "collation"] { + let input = format!("data/{name}.postcard"); + println!("cargo::rerun-if-changed={input}"); + let bytes = std::fs::read(&input)?; + if bytes.is_empty() || bytes.len() > 2 * 1024 * 1024 { + return Err(format!("{input} is outside the browser locale-data size budget").into()); + } + let mut compressed = Vec::new(); + { + let mut encoder = brotli::CompressorWriter::new(&mut compressed, 4096, 11, 22); + encoder.write_all(&bytes)?; + } + std::fs::write(out.join(format!("{name}.br")), compressed)?; + if name == "collation" { + declarations.push_str("#[cfg(any(test, feature = \"collate\"))]\n"); + } + declarations.push_str(&format!( + "const {}: (&[u8], usize) = (include_bytes!(concat!(env!(\"OUT_DIR\"), \"/{name}.br\")), {});\n", + name.to_ascii_uppercase(), + bytes.len() + )); + } + std::fs::write(out.join("locale_blobs.rs"), declarations)?; + Ok(()) +} diff --git a/crates/i18n/src/blob.rs b/crates/i18n/src/blob.rs new file mode 100644 index 0000000000..6d644c6d8b --- /dev/null +++ b/crates/i18n/src/blob.rs @@ -0,0 +1,82 @@ +//! Preserve every locale byte while avoiding raw provider blobs in browser binaries. + +use icu_provider::DataError; +use icu_provider_blob::BlobDataProvider; + +#[cfg(any(test, target_arch = "wasm32"))] +include!(concat!(env!("OUT_DIR"), "/locale_blobs.rs")); + +pub(crate) fn numbers() -> Result { + #[cfg(target_arch = "wasm32")] + { + owned(NUMBERS) + } + #[cfg(not(target_arch = "wasm32"))] + BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/numbers.postcard")) +} + +pub(crate) fn dates() -> Result { + #[cfg(target_arch = "wasm32")] + { + owned(DATES) + } + #[cfg(not(target_arch = "wasm32"))] + BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/dates.postcard")) +} + +#[cfg(feature = "collate")] +pub(crate) fn collation() -> Result { + #[cfg(target_arch = "wasm32")] + { + owned(COLLATION) + } + #[cfg(not(target_arch = "wasm32"))] + BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/collation.postcard")) +} + +#[cfg(target_arch = "wasm32")] +fn owned((bytes, len): (&[u8], usize)) -> Result { + let bytes = unpack(bytes, len).ok_or_else(|| DataError::custom("Invalid compressed locale data"))?; + BlobDataProvider::try_new_from_blob(bytes.into_boxed_slice()) +} + +#[cfg(any(test, target_arch = "wasm32"))] +fn unpack(bytes: &[u8], len: usize) -> Option> { + use std::io::Read as _; + // Generated blobs are currently below 1 MiB. Bound allocation and decoding even for corrupt metadata. + if len == 0 || len > 2 * 1024 * 1024 { + return None; + } + let mut decoded = Vec::new(); + decoded.try_reserve_exact(len).ok()?; + brotli_decompressor::Decompressor::new(bytes, 4096).take(len as u64 + 1).read_to_end(&mut decoded).ok()?; + (decoded.len() == len).then_some(decoded) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn packed_catalogs_preserve_every_locale_byte_and_load_as_owned_providers() { + for (packed, original) in [ + (NUMBERS, include_bytes!("../data/numbers.postcard").as_slice()), + (DATES, include_bytes!("../data/dates.postcard").as_slice()), + (COLLATION, include_bytes!("../data/collation.postcard").as_slice()), + ] { + let decoded = unpack(packed.0, packed.1).unwrap(); + assert_eq!(decoded, original); + assert!(packed.0.len() < original.len()); + BlobDataProvider::try_new_from_blob(decoded.into_boxed_slice()).unwrap(); + } + } + + #[test] + fn corrupt_or_wrong_sized_catalogs_are_unavailable() { + assert!(unpack(b"not compressed locale data", NUMBERS.1).is_none()); + assert!(unpack(&NUMBERS.0[..NUMBERS.0.len() / 2], NUMBERS.1).is_none()); + for len in [0, NUMBERS.1 - 1, NUMBERS.1 + 1, usize::MAX] { + assert!(unpack(NUMBERS.0, len).is_none()); + } + } +} diff --git a/crates/i18n/src/collate.rs b/crates/i18n/src/collate.rs index 76d7893565..a5441d0195 100644 --- a/crates/i18n/src/collate.rs +++ b/crates/i18n/src/collate.rs @@ -84,7 +84,7 @@ struct Data(LocaleFallbackProvider); impl Data { fn new() -> Result { - let blob = BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/collation.postcard"))?; + let blob = crate::blob::collation()?; Ok(Data(LocaleFallbackProvider::new(blob, LocaleFallbacker::new().static_to_owned()))) } } diff --git a/crates/i18n/src/lib.rs b/crates/i18n/src/lib.rs index ea51b6d728..363083bbb7 100644 --- a/crates/i18n/src/lib.rs +++ b/crates/i18n/src/lib.rs @@ -38,6 +38,8 @@ pub use bidi::{file_name, isolate, ltr, path, strip_isolates}; pub use message::MessageMatch; use message::{KEPT_VALUE, MAX_MESSAGE_LEN, MESSAGE_DEPTH, Template, insert_template, sort_templates}; +mod blob; + /// The CLDR number, plural and date data for every CLDR locale, from `data/generate.sh`. mod data { use std::sync::OnceLock; @@ -53,7 +55,7 @@ mod data { static PROVIDER: OnceLock>> = OnceLock::new(); PROVIDER .get_or_init(|| { - let blob = BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/numbers.postcard")).ok()?; + let blob = crate::blob::numbers().ok()?; Some(LocaleFallbackProvider::new(blob, LocaleFallbacker::new().static_to_owned())) }) .as_ref() @@ -65,7 +67,7 @@ mod data { static PROVIDER: OnceLock>> = OnceLock::new(); PROVIDER .get_or_init(|| { - let blob = BlobDataProvider::try_new_from_static_blob(include_bytes!("../data/dates.postcard")).ok()?; + let blob = crate::blob::dates().ok()?; Some(LocaleFallbackProvider::new(blob, LocaleFallbacker::new().static_to_owned())) }) .as_ref()