use crate::catalog::{Entry, Msg, Tree, content_tag, path_budget};
use crate::error::Error;
use crate::i18n::{I18n, LocaleData, Snapshot};
use crate::json::{Event, Reader, number_to_js_string, write_str};
use crate::lazy::Layer;
use std::sync::{Arc, OnceLock};
#[must_use]
pub fn encode(i18n: &I18n, locale: Option<&str>, page: Option<&str>, meta: bool) -> (u64, Vec<u8>) {
i18n.inner.read(|s| {
let code = locale.unwrap_or(&s.locale);
let mut out = head(s, code);
if meta {
write_meta(&mut out, s);
}
write_chunks(&mut out, s, code, page, true);
(s.public, out.into_bytes())
})
}
#[must_use]
pub fn encode_page(i18n: &I18n, page: &str) -> (u64, Vec<u8>) {
i18n.inner.read(|s| {
let mut out = head(s, &s.locale);
write_chunks(&mut out, s, &s.locale, Some(page), false);
(s.public, out.into_bytes())
})
}
const EMPTY: &str = "{\"data\":{}}";
#[must_use]
pub fn chunk(i18n: &I18n, locale: &str, page: Option<&str>) -> (u64, Arc<str>) {
i18n.inner.read(|s| {
let page = s.meta.page(page);
match s.data.get(locale).and_then(|d| tree(d, page)) {
Some(t) => {
let (json, tag) = t.payload();
(*tag, json.clone())
}
None => (content_tag(EMPTY.as_bytes()), Arc::from(EMPTY)),
}
})
}
#[must_use]
pub fn bundle(
i18n: &I18n,
locale: &str,
page: Option<&str>,
want: Option<u64>,
) -> (u64, Option<Vec<u8>>) {
i18n.inner.read(|s| {
let tag = bundle_tag(s, locale, page);
if want.is_some_and(|w| w != tag) {
return (tag, None);
}
let mut out = String::with_capacity(256);
out.push_str("{\"locale\":");
write_str(&mut out, locale);
write_chunks(&mut out, s, locale, page, true);
(tag, Some(out.into_bytes()))
})
}
#[must_use]
pub fn meta(i18n: &I18n, locale: Option<&str>, page: Option<&str>) -> Vec<u8> {
i18n.inner.read(|s| {
let code = locale.unwrap_or(&s.locale);
let mut out = head(s, code);
write_meta(&mut out, s);
out.push_str(",\"tags\":{");
let mut first = true;
for_chunks(s, code, page, true, |c, name, t| {
if !first {
out.push(',');
}
first = false;
out.push('"');
push_name(&mut out, c);
out.push('/');
push_name(&mut out, name);
out.push_str("\":");
push_tag(&mut out, t.payload().1);
});
out.push_str("},\"bundle\":");
push_tag(&mut out, bundle_tag(s, code, page));
out.push('}');
out.into_bytes()
})
}
pub fn apply(i18n: &I18n, bytes: &[u8]) -> Result<u64, Error> {
apply_with(i18n, bytes, Vec::new())
}
pub(crate) type Stored = (Arc<str>, Option<String>, Arc<Tree>);
pub(crate) fn apply_with(i18n: &I18n, bytes: &[u8], mut extra: Vec<Stored>) -> Result<u64, Error> {
let shape = |reason: &'static str| Error::Config {
path: "payload".to_owned(),
reason,
};
let mut r = Payload {
r: Reader::new(bytes),
budget: path_budget(bytes.len()),
};
if !matches!(r.next()?, Event::ObjectStart) {
return Err(Error::NotObject {
path: "payload".to_owned(),
});
}
let mut version = 0;
let mut locale = None;
let mut chunks = Vec::new();
while let Event::Key(key) = r.next()? {
match &*key {
"version" => match r.next()? {
Event::Num(n) => version = n.parse().map_err(|_| shape("version"))?,
_ => return Err(shape("version must be a number")),
},
"locale" => match r.next()? {
Event::Str(s) => locale = Some(s.into_owned()),
_ => return Err(shape("locale must be a string")),
},
"chunks" => {
if !matches!(r.next()?, Event::ArrayStart) {
return Err(shape("chunks must be an array"));
}
loop {
match r.next()? {
Event::ArrayEnd => break,
Event::ObjectStart => {
let (l, p, t) = r.chunk()?;
chunks.push((l, p, Arc::new(t)));
}
_ => return Err(shape("chunks[] must hold objects")),
}
}
}
_ => r.skip_value()?,
}
}
r.r.next().map_err(json_error)?;
if let Some(l) = &locale {
crate::i18n::chunk_names(l, None)?;
}
chunks.append(&mut extra);
i18n.replace_chunks(chunks, locale.as_deref())?;
Ok(version)
}
pub fn builder(meta: &[u8]) -> Result<crate::i18n::Builder, Error> {
let m = Meta::read(meta)?;
let text = std::str::from_utf8(meta).map_err(|_| Error::Config {
path: "payload".to_owned(),
reason: "meta is not UTF-8",
})?;
Ok(m.builder(text))
}
#[derive(Debug, Default)]
pub(crate) struct Meta {
pub(crate) version: u64,
pub(crate) locale: String,
pub(crate) fallback: Option<String>,
pub(crate) chains: Vec<(String, Vec<String>)>,
pub(crate) tags: Vec<(String, String)>,
pub(crate) time_zone: Option<String>,
}
impl Meta {
pub(crate) fn read(bytes: &[u8]) -> Result<Meta, Error> {
let shape = |reason: &'static str| Error::Config {
path: "payload".to_owned(),
reason,
};
let mut r = Payload {
r: Reader::new(bytes),
budget: 0,
};
if !matches!(r.next()?, Event::ObjectStart) {
return Err(Error::NotObject {
path: "payload".to_owned(),
});
}
let mut m = Meta::default();
let text_or_null = |r: &mut Payload<'_>, reason| match r.next()? {
Event::Str(s) => Ok(Some(s.into_owned())),
Event::Null => Ok(None),
_ => Err(shape(reason)),
};
while let Event::Key(key) = r.next()? {
match &*key {
"version" => match r.next()? {
Event::Num(n) => m.version = n.parse().map_err(|_| shape("version"))?,
_ => return Err(shape("version must be a number")),
},
"locale" => {
m.locale = text_or_null(&mut r, "locale must be a string")?
.ok_or(shape("locale must be a string"))?;
}
"fallbackLocale" => {
m.fallback = text_or_null(&mut r, "fallbackLocale must be a string")?;
}
"timeZone" => m.time_zone = text_or_null(&mut r, "timeZone must be a string")?,
"chains" => {
if !matches!(r.next()?, Event::ObjectStart) {
return Err(shape("chains must be an object"));
}
while let Event::Key(code) = r.next()? {
if !matches!(r.next()?, Event::ArrayStart) {
return Err(shape("chains{} must hold arrays"));
}
let mut chain = Vec::new();
loop {
match r.next()? {
Event::ArrayEnd => break,
Event::Str(c) => chain.push(c.into_owned()),
_ => return Err(shape("chains{}[] must hold strings")),
}
}
m.chains.push((code.into_owned(), chain));
}
}
"tags" => {
if !matches!(r.next()?, Event::ObjectStart) {
return Err(shape("tags must be an object"));
}
while let Event::Key(at) = r.next()? {
match r.next()? {
Event::Str(t) => m.tags.push((at.into_owned(), t.into_owned())),
_ => return Err(shape("tags{} must hold strings")),
}
}
}
_ => r.skip_value()?,
}
}
r.r.next().map_err(json_error)?;
Ok(m)
}
pub(crate) fn builder(&self, text: &str) -> crate::i18n::Builder {
let mut b = crate::i18n::Builder::default()
.config_json(text)
.locale(&self.locale);
for (code, chain) in &self.chains {
if let Some(next) = chain.get(1)
&& !(chain.len() == 2 && self.fallback.as_deref() == Some(next.as_str()))
{
b = b.fallback_for(code, next);
}
}
#[cfg(feature = "format")]
if let Some(zone) = &self.time_zone {
b = b.time_zone(zone);
}
b
}
}
#[derive(Debug, Default)]
pub(crate) struct Formats {
numbers: Vec<Box<str>>,
dates: Vec<Box<str>>,
json: OnceLock<(Box<str>, Box<str>)>,
}
impl Formats {
pub(crate) fn new(b: &crate::i18n::Builder, config: &crate::loader::Config) -> Formats {
#[cfg(feature = "format")]
let (numbers, dates) = (&b.formats[..], &b.datetime_formats[..]);
#[cfg(not(feature = "format"))]
let (numbers, dates): (&[String], &[String]) = {
let _ = b;
(&[], &[])
};
let texts = |first: Option<&str>, rest: &[String]| -> Vec<Box<str>> {
first
.into_iter()
.chain(rest.iter().map(String::as_str))
.map(Box::from)
.collect()
};
Formats {
numbers: texts(config.number_formats.as_deref(), numbers),
dates: texts(config.datetime_formats.as_deref(), dates),
json: OnceLock::new(),
}
}
fn json(&self) -> &(Box<str>, Box<str>) {
self.json.get_or_init(|| {
let merged = |texts: &[Box<str>]| {
let mut acc = Tree::default();
for text in texts {
if let Ok(t) = Tree::parse(text.as_bytes(), "formats") {
acc.merge_replacing(t, 2);
}
}
let mut out = String::new();
acc.write_json(&mut out);
out.into_boxed_str()
};
(merged(&self.numbers), merged(&self.dates))
})
}
}
fn tree<'a>(d: &'a LocaleData, page: Option<&str>) -> Option<&'a Tree> {
d.layer(page).and_then(Layer::chunk)
}
fn head(s: &Snapshot, code: &str) -> String {
let mut out = String::with_capacity(256);
out.push_str("{\"version\":");
crate::json::push_u64(&mut out, s.public);
out.push_str(",\"locale\":");
write_str(&mut out, code);
out
}
fn push_tag(out: &mut String, tag: u64) {
out.push('"');
for i in (0..16).rev() {
let d = ((tag >> (i * 4)) & 0xf) as u32;
out.push(char::from_digit(d, 16).unwrap_or('0'));
}
out.push('"');
}
fn push_name(out: &mut String, name: &str) {
let mut quoted = String::new();
write_str(&mut quoted, name);
out.push_str(quoted.get(1..quoted.len() - 1).unwrap_or(""));
}
fn write_meta(out: &mut String, s: &Snapshot) {
let meta = &s.meta;
out.push_str(",\"defaultLocale\":");
write_str(out, meta.check.reference.as_deref().unwrap_or(&s.locale));
out.push_str(",\"fallbackLocale\":");
match meta.fallback() {
Some(f) => write_str(out, f),
None => out.push_str("null"),
}
let infos = s.locale_infos();
out.push_str(",\"locales\":[");
for (i, l) in infos.iter().enumerate() {
if i > 0 {
out.push(',');
}
out.push_str("{\"code\":");
write_str(out, &l.code);
for (name, value) in [
("iso", &l.iso),
("dir", &l.dir),
("displayName", &l.display_name),
] {
if let Some(v) = value {
out.push_str(",\"");
out.push_str(name);
out.push_str("\":");
write_str(out, v);
}
}
out.push('}');
}
out.push_str("],\"chains\":{");
for (i, l) in infos.iter().enumerate() {
if i > 0 {
out.push(',');
}
write_str(out, &l.code);
out.push_str(":[");
for (j, c) in meta.chain_codes(&l.code).into_iter().enumerate() {
if j > 0 {
out.push(',');
}
write_str(out, c);
}
out.push(']');
}
let (numbers, dates) = meta.formats.json();
out.push_str("},\"numberFormats\":");
out.push_str(numbers);
out.push_str(",\"datetimeFormats\":");
out.push_str(dates);
out.push_str(",\"timeZone\":");
#[cfg(feature = "format")]
let zone = meta.zone_name();
#[cfg(not(feature = "format"))]
let zone: Option<&str> = None;
match zone {
Some(z) => write_str(out, z),
None => out.push_str("null"),
}
}
fn for_chunks<'s>(
s: &'s Snapshot,
code: &'s str,
page: Option<&'s str>,
roots: bool,
mut f: impl FnMut(&'s str, &'s str, &'s Tree),
) {
let resolved = s.meta.page(page);
let page = page
.map(|p| (resolved, if resolved.is_some() { p } else { "index" }))
.filter(|(at, _)| at.is_some() || !roots);
for c in s.meta.chain_codes(code) {
let Some(d) = s.data.get(c) else { continue };
let pairs = [roots.then_some((None, "index")), page];
for (at, name) in pairs.into_iter().flatten() {
if let Some(t) = tree(d, at) {
f(c, name, t);
}
}
}
}
fn bundle_tag(s: &Snapshot, code: &str, page: Option<&str>) -> u64 {
let mut parts = Vec::with_capacity(64);
for_chunks(s, code, page, true, |c, name, t| {
parts.extend_from_slice(c.as_bytes());
parts.push(0);
parts.extend_from_slice(name.as_bytes());
parts.push(0);
parts.extend_from_slice(&t.payload().1.to_le_bytes());
});
content_tag(&parts)
}
fn write_chunks(out: &mut String, s: &Snapshot, code: &str, page: Option<&str>, roots: bool) {
out.push_str(",\"chunks\":[");
let mut first = true;
for_chunks(s, code, page, roots, |c, name, t| {
if !first {
out.push(',');
}
first = false;
out.push_str("{\"locale\":");
write_str(out, c);
out.push_str(",\"page\":");
write_str(out, name);
out.push(',');
let json = &t.payload().0;
out.push_str(json.get(1..).unwrap_or("}"));
});
out.push_str("]}");
}
fn json_error(e: crate::json::JsonError) -> Error {
Error::Json {
path: "payload".to_owned(),
offset: e.offset,
kind: e.kind.as_str(),
}
}
struct Payload<'a> {
r: Reader<'a>,
budget: usize,
}
impl<'a> Payload<'a> {
fn next(&mut self) -> Result<Event<'a>, Error> {
match self.r.next() {
Ok(Some(e)) => Ok(e),
Ok(None) => Err(Error::Config {
path: "payload".to_owned(),
reason: "unexpected end",
}),
Err(e) => Err(json_error(e)),
}
}
fn skip_rest(&mut self) -> Result<(), Error> {
let mut depth = 1usize;
while depth > 0 {
match self.next()? {
Event::ObjectStart | Event::ArrayStart => depth += 1,
Event::ObjectEnd | Event::ArrayEnd => depth -= 1,
_ => {}
}
}
Ok(())
}
fn skip_value(&mut self) -> Result<(), Error> {
match self.next()? {
Event::ObjectStart | Event::ArrayStart => self.skip_rest(),
_ => Ok(()),
}
}
fn chunk(&mut self) -> Result<(Arc<str>, Option<String>, Tree), Error> {
let shape = |reason: &'static str| Error::Config {
path: "payload".to_owned(),
reason,
};
let (mut locale, mut page, mut data, mut linked) = (None, None, None, Vec::new());
while let Event::Key(key) = self.next()? {
match &*key {
"locale" => match self.next()? {
Event::Str(s) => locale = Some(s.into_owned()),
_ => return Err(shape("chunks[].locale must be a string")),
},
"page" => match self.next()? {
Event::Str(s) => page = Some(s.into_owned()),
_ => return Err(shape("chunks[].page must be a string")),
},
"data" => {
let path = match &locale {
Some(l) => crate::i18n::messages_path(l, page.as_deref())
.replacen("messages", "payload", 1),
None => "payload".to_owned(),
};
match self.next()? {
Event::ObjectStart => {
data = Some(Tree::read_object(&mut self.r, &path, &mut self.budget)?);
}
Event::ArrayStart => {
self.skip_rest()?;
return Err(Error::NotObject { path });
}
_ => return Err(Error::NotObject { path }),
}
}
"linked" => {
if !matches!(self.next()?, Event::ObjectStart) {
return Err(shape("chunks[].linked must be an object"));
}
self.linked(&mut linked)?;
}
_ => self.skip_value()?,
}
}
let (Some(locale), Some(mut data)) = (locale, data) else {
return Err(shape("chunks[] needs locale and data"));
};
let page = page.filter(|p| !p.is_empty() && p != "index");
crate::i18n::chunk_names(&locale, page.as_deref())?;
if !linked.is_empty() {
data.add_linked(linked);
}
Ok((Arc::from(locale), page, data))
}
fn linked(&mut self, out: &mut Vec<(Arc<str>, Entry)>) -> Result<(), Error> {
while let Event::Key(key) = self.next()? {
let entry = match self.next()? {
Event::Str(s) => Some(Entry::Msg(Msg::new(&s))),
Event::Num(n) => Some(Entry::Value(crate::intern::intern(&number_to_js_string(n)))),
Event::Bool(b) => Some(Entry::Value(if b { "true" } else { "false" })),
Event::ObjectStart | Event::ArrayStart => {
self.skip_rest()?;
Some(Entry::Node)
}
_ => None,
};
let Some(entry) = entry else { continue };
self.budget = self.budget.checked_sub(key.len()).ok_or(Error::Config {
path: "payload".to_owned(),
reason: "linked keys too long for the payload size",
})?;
if key.len() > 4096 {
return Err(Error::Config {
path: "payload".to_owned(),
reason: "linked key longer than 4096 bytes",
});
}
out.push((Arc::from(&*key), entry));
}
Ok(())
}
}