mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-30 18:27:00 +01:00
Compress browser locale provider data losslessly
This commit is contained in:
1 parent
b50522dc44
commit
b3575af024
7 files changed
+144
-9
No files matched your search
Generated
+2
@@ -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",
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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.
|
||||
@@ -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<dyn std::error::Error>> {
|
||||
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(())
|
||||
}
|
||||
@@ -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<BlobDataProvider, DataError> {
|
||||
#[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<BlobDataProvider, DataError> {
|
||||
#[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<BlobDataProvider, DataError> {
|
||||
#[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<BlobDataProvider, DataError> {
|
||||
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<Vec<u8>> {
|
||||
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());
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -84,7 +84,7 @@ struct Data(LocaleFallbackProvider<BlobDataProvider>);
|
||||
|
||||
impl Data {
|
||||
fn new() -> Result<Data, DataError> {
|
||||
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())))
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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<Option<LocaleFallbackProvider<BlobDataProvider>>> = 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<Option<LocaleFallbackProvider<BlobDataProvider>>> = 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()
|
||||
|
||||
Reference in new issue
Block a user