use crate::args::{Args, Count};
use crate::catalog::{Entry, Msg, Tree, WithCount, interpolate_once};
use crate::change::{Change, Listeners};
use crate::check::{self, CheckReport};
use crate::error::Error;
use crate::hash::FastMap;
use crate::lazy::{Layer, LazyCtl};
use crate::loader::{self, Config};
use crate::plural::{self, Plural};
use crate::source::{self, Pair, Sources};
use std::cell::RefCell;
use std::fmt;
use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
use std::sync::{Arc, Mutex, RwLock};
type Missing = Box<dyn Fn(&str, &str, &str) + Send + Sync>;
#[derive(Debug, Default, Clone)]
pub(crate) struct LocaleData {
pub(crate) root: Option<Layer>,
pub(crate) pages: FastMap<Arc<str>, Layer>,
}
impl LocaleData {
fn get(&self, page: Option<&str>, key: &crate::key::Probe<'_>) -> Option<&Entry> {
if let Some(p) = page
&& let Some(e) = self
.pages
.get(p)
.and_then(Layer::chunk)
.and_then(|c| c.find(key))
{
return Some(e);
}
self.root
.as_ref()
.and_then(Layer::chunk)
.and_then(|c| c.find(key))
}
pub(crate) fn layer(&self, page: Option<&str>) -> Option<&Layer> {
match page {
None => self.root.as_ref(),
Some(p) => self.pages.get(p),
}
}
fn has(&self, page: Option<&str>, key: &str) -> bool {
let has = |l: Option<&Layer>| l.and_then(Layer::chunk).is_some_and(|c| c.has(key));
has(page.and_then(|p| self.pages.get(p))) || has(self.root.as_ref())
}
}
type Chain = Arc<[Arc<LocaleData>]>;
#[derive(Debug, Default)]
pub(crate) struct Meta {
fallback: Option<Arc<str>>,
links: FastMap<Arc<str>, Arc<str>>,
iso: FastMap<Arc<str>, Arc<str>>,
configured: Vec<loader::LocaleEntry>,
declared: Vec<Arc<str>>,
aliases: FastMap<Arc<str>, Arc<str>>,
#[cfg(feature = "format")]
pub(crate) numbers: crate::format::Formats,
#[cfg(feature = "format")]
dates: crate::format::DateFormats,
#[cfg(feature = "format")]
zone: Option<crate::format::Zone>,
#[cfg(feature = "format")]
zone_name: Option<Box<str>>,
#[cfg(feature = "format")]
system_zone: std::sync::OnceLock<crate::format::Zone>,
#[cfg(feature = "format")]
system_zone_name: std::sync::OnceLock<Box<str>>,
#[cfg(feature = "format")]
cold_numbers: [std::sync::OnceLock<(Box<str>, &'static crate::format::Loc)>; 8],
#[cfg(feature = "format")]
clock: Option<crate::format::api::Clock>,
pub(crate) check: check::Facts,
linked: Option<ResolveLinked>,
#[cfg(feature = "payload")]
pub(crate) formats: crate::payload::Formats,
}
impl Meta {
pub(crate) fn linked(&self) -> bool {
self.linked.is_some()
}
fn disabled(&self, code: &str) -> bool {
self.configured.iter().any(|l| l.disabled && l.code == code)
}
pub(crate) fn page<'a>(&'a self, page: Option<&'a str>) -> Option<&'a str> {
let p = page.filter(|p| !p.is_empty() && *p != "index")?;
let p = self.aliases.get(p).map_or(p, |t| &**t);
(p != "index").then_some(p)
}
fn chain(&self, data: &FastMap<Arc<str>, Arc<LocaleData>>, code: &str) -> Chain {
self.chain_codes(code)
.iter()
.filter_map(|c| data.get(*c).cloned())
.collect()
}
pub(crate) fn chain_codes<'a>(&'a self, code: &'a str) -> Vec<&'a str> {
let mut codes: Vec<&str> = Vec::new();
let mut next = Some(code);
while let Some(c) = next {
if codes.contains(&c) {
break;
}
codes.push(c);
next = self.links.get(c).map(|s| &**s);
}
if let Some(fb) = self.fallback.as_deref()
&& !codes.contains(&fb)
{
codes.push(fb);
}
codes
}
#[cfg(feature = "payload")]
pub(crate) fn fallback(&self) -> Option<&str> {
self.fallback.as_deref()
}
}
pub(crate) type DataMap = FastMap<Arc<str>, Arc<LocaleData>>;
pub(crate) struct Snapshot {
pub(crate) version: u64,
pub(crate) public: u64,
pub(crate) locale: Arc<str>,
pub(crate) data: Arc<DataMap>,
chains: Arc<FastMap<Arc<str>, Chain>>,
active: Chain,
own: Option<Arc<LocaleData>>,
fallback: Chain,
pub(crate) meta: Arc<Meta>,
pub(crate) plural: Option<&'static Plural>,
plurals: Arc<FastMap<Arc<str>, Option<&'static Plural>>>,
#[cfg(feature = "format")]
pub(crate) number: &'static crate::format::Loc,
#[cfg(feature = "format")]
numbers: Arc<FastMap<Arc<str>, &'static crate::format::Loc>>,
}
impl Meta {
fn plural(&self, code: &str) -> Option<&'static Plural> {
plural::for_tag(self.tag(code))
}
pub(crate) fn tag<'a>(&'a self, code: &'a str) -> &'a str {
self.iso.get(code).map_or(code, |t| &**t)
}
#[cfg(feature = "format")]
fn number(&self, code: &str) -> &'static crate::format::Loc {
crate::format::locale::resolve(self.tag(code))
}
#[cfg(feature = "format")]
fn cold_number(&self, code: &str) -> &'static crate::format::Loc {
for slot in &self.cold_numbers {
match slot.get() {
Some((c, loc)) if **c == *code => return loc,
Some(_) => {}
None => {
let loc = self.number(code);
let _ = slot.set((code.into(), loc));
return loc;
}
}
}
self.number(code)
}
#[cfg(feature = "format")]
pub(crate) fn named_number(
&self,
code: &str,
name: &str,
) -> Option<&crate::format::NumberOptions> {
let mut at = code;
while !at.is_empty() {
if let Some(o) = self.numbers.get(at).and_then(|m| m.get(name)) {
return Some(o);
}
at = at.get(..at.rfind('-').unwrap_or(0)).unwrap_or("");
}
None
}
#[cfg(feature = "format")]
pub(crate) fn named_date(&self, code: &str, name: &str) -> Option<&crate::format::DateOptions> {
let mut at = code;
while !at.is_empty() {
if let Some(o) = self.dates.get(at).and_then(|m| m.get(name)) {
return Some(o);
}
at = at.get(..at.rfind('-').unwrap_or(0)).unwrap_or("");
}
None
}
#[cfg(all(feature = "format", feature = "payload"))]
pub(crate) fn zone_name(&self) -> Option<&str> {
self.zone_name
.as_deref()
.or_else(|| self.system_zone_name.get().map(|n| &**n))
}
#[cfg(feature = "format")]
pub(crate) fn set_system_zone(&self, iana: &str) -> bool {
if self.zone.is_some() || iana.is_empty() {
return false;
}
let Some(zone) = crate::format::date::zone_named(iana) else {
return false;
};
if self.system_zone.set(zone).is_err() {
return false;
}
let _ = self.system_zone_name.set(Box::from(iana));
true
}
#[cfg(feature = "format")]
pub(crate) fn zone(&self) -> &crate::format::Zone {
match &self.zone {
Some(z) => z,
None => self.system_zone.get_or_init(crate::format::Zone::system),
}
}
#[cfg(feature = "format")]
pub(crate) fn now(&self) -> Option<i64> {
match &self.clock {
Some(c) => crate::format::Timestamp::from((c.0)()).millis(),
None => crate::format::api::system_now(),
}
}
}
impl Snapshot {
pub(crate) fn new(meta: Arc<Meta>, data: DataMap, locale: Arc<str>, version: u64) -> Snapshot {
let mut chains = FastMap::default();
let names = meta
.configured
.iter()
.map(|l| &*l.code)
.chain(data.keys().map(|k| &**k))
.chain(meta.declared.iter().map(|k| &**k))
.chain(std::iter::once(&*locale));
let mut plurals = FastMap::default();
#[cfg(feature = "format")]
let mut numbers = FastMap::default();
for code in names {
if !chains.contains_key(code) {
let code: Arc<str> = Arc::from(code);
let chain = meta.chain(&data, &code);
plurals.insert(code.clone(), meta.plural(&code));
#[cfg(feature = "format")]
numbers.insert(code.clone(), meta.number(&code));
chains.insert(code, chain);
}
}
let active = chains
.get(&*locale)
.cloned()
.unwrap_or_else(|| meta.chain(&data, &locale));
let fallback = meta
.fallback
.as_deref()
.and_then(|fb| data.get(fb).cloned())
.into_iter()
.collect();
Snapshot {
version,
public: version,
own: data.get(&*locale).cloned(),
plural: meta.plural(&locale),
#[cfg(feature = "format")]
number: meta.number(&locale),
#[cfg(feature = "format")]
numbers: Arc::new(numbers),
locale,
data: Arc::new(data),
chains: Arc::new(chains),
plurals: Arc::new(plurals),
active,
fallback,
meta,
}
}
pub(crate) fn plural_of(&self, code: &str) -> Option<&'static Plural> {
match self.plurals.get(code) {
Some(p) => *p,
None => self.meta.plural(code),
}
}
#[cfg(feature = "format")]
pub(crate) fn number_of(&self, code: &str) -> &'static crate::format::Loc {
match self.numbers.get(code) {
Some(n) => n,
None => self.meta.cold_number(code),
}
}
pub(crate) fn layers(&self, locale: Option<&str>) -> &[Arc<LocaleData>] {
match locale {
None => &self.active,
Some(code) => self.chains.get(code).unwrap_or(&self.fallback),
}
}
pub(crate) fn lookup(
&self,
locale: Option<&str>,
page: Option<&str>,
key: &str,
) -> Option<&Entry> {
let page = self.meta.page(page);
let key = crate::key::Probe::new(key);
self.layers(locale)
.iter()
.find_map(|layer| layer.get(page, &key))
}
fn has(&self, locale: Option<&str>, page: Option<&str>, key: &str) -> bool {
let own = match locale {
None => self.own.as_deref(),
Some(code) if self.chains.contains_key(code) => self.data.get(code).map(|d| &**d),
Some(_) => None,
};
own.is_some_and(|d| d.has(self.meta.page(page), key))
}
}
impl Snapshot {
pub(crate) fn locale_infos(&self) -> Vec<LocaleInfo> {
let s = self;
let meta = &s.meta;
let mut rest: Vec<&str> = s
.data
.keys()
.map(|k| &**k)
.chain(meta.declared.iter().map(|k| &**k))
.filter(|c| !meta.configured.iter().any(|l| l.code == *c))
.collect();
rest.sort_unstable();
rest.dedup();
let info = |code: &str, entry: Option<&loader::LocaleEntry>| LocaleInfo {
code: code.to_owned(),
iso: meta
.iso
.get(code)
.map(|s| String::from(&**s))
.or_else(|| entry.and_then(|e| e.iso.clone())),
dir: entry.and_then(|e| e.dir.clone()),
display_name: entry.and_then(|e| e.display_name.clone()),
};
meta.configured
.iter()
.filter(|l| !l.disabled)
.map(|l| info(&l.code, Some(l)))
.chain(rest.into_iter().map(|c| info(c, None)))
.collect()
}
}
struct Slot {
id: u64,
version: u64,
snap: Arc<Snapshot>,
alive: Arc<AtomicBool>,
}
struct Cache {
slots: [Option<Slot>; 4],
next: usize,
drops: u64,
}
thread_local! {
#[allow(
clippy::missing_const_for_thread_local,
reason = "already `const`: clippy misreads the expansion on targets without native TLS (Android)"
)]
static CACHE: RefCell<Cache> = const {
RefCell::new(Cache { slots: [const { None }; 4], next: 0, drops: 0 })
};
}
static NEXT_ID: AtomicU64 = AtomicU64::new(0);
static DROPS: AtomicU64 = AtomicU64::new(0);
pub(crate) struct Inner {
id: u64,
version: AtomicU64,
state: RwLock<Arc<Snapshot>>,
writer: Mutex<()>,
missing: Option<Missing>,
alive: Arc<AtomicBool>,
pub(crate) sources: Sources,
pub(crate) ctl: Arc<LazyCtl>,
pub(crate) remote: FastMap<Box<str>, Pair>,
pub(crate) listeners: Listeners,
}
impl Drop for Inner {
fn drop(&mut self) {
self.alive.store(false, Ordering::Relaxed);
DROPS.fetch_add(1, Ordering::Release);
}
}
impl Inner {
pub(crate) fn current(&self) -> Arc<Snapshot> {
self.load()
}
fn load(&self) -> Arc<Snapshot> {
match self.state.read() {
Ok(g) => g.clone(),
Err(poisoned) => poisoned.into_inner().clone(),
}
}
pub(crate) fn read<R>(&self, mut f: impl FnMut(&Snapshot) -> R) -> R {
let version = self.version.load(Ordering::Acquire);
let drops = DROPS.load(Ordering::Relaxed);
let hit = CACHE.try_with(|cell| {
let cache = cell.try_borrow().ok()?;
if cache.drops != drops {
return None;
}
let slot = cache
.slots
.iter()
.flatten()
.find(|s| s.id == self.id && s.version == version)?;
Some(f(&slot.snap))
});
if let Ok(Some(r)) = hit {
return r;
}
let (snap, gone) = self.refresh();
let r = f(&snap);
drop(gone);
r
}
#[inline(never)]
fn refresh(&self) -> (Arc<Snapshot>, [Option<Slot>; 4]) {
let drops = DROPS.load(Ordering::Acquire);
let snap = self.load();
let mut gone: [Option<Slot>; 4] = [const { None }; 4];
let _ = CACHE.try_with(|cell| {
let Ok(mut cache) = cell.try_borrow_mut() else {
return;
};
let cache = &mut *cache;
if cache.drops != drops {
for (slot, out) in cache.slots.iter_mut().zip(&mut gone) {
if slot
.as_ref()
.is_some_and(|s| !s.alive.load(Ordering::Relaxed))
{
*out = slot.take();
}
}
cache.drops = drops;
}
let slots = &mut cache.slots;
let at = slots
.iter()
.position(|s| s.as_ref().is_some_and(|s| s.id == self.id))
.or_else(|| slots.iter().position(Option::is_none))
.unwrap_or_else(|| {
let at = cache.next;
cache.next = (at + 1) % slots.len();
at
});
let new = Slot {
id: self.id,
version: snap.version,
snap: snap.clone(),
alive: self.alive.clone(),
};
if let Some(old) = slots[at].replace(new) {
gone[at] = Some(old);
}
});
(snap, gone)
}
pub(crate) fn write(
&self,
f: impl FnOnce(&Snapshot) -> Result<Option<Snapshot>, Error>,
) -> Result<Option<Change>, Error> {
let _writer = match self.writer.lock() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
let current = self.load();
let Some(mut next) = f(¤t)? else {
return Ok(None);
};
next.version = current.version + 1;
next.public = current.public + 1;
let change = Change {
locale: next.locale.clone(),
version: next.public,
};
self.publish(next);
self.listeners.push(change.clone());
drop(_writer);
self.listeners.drain();
Ok(Some(change))
}
fn publish(&self, next: Snapshot) -> u64 {
let version = next.version;
let mut state = match self.state.write() {
Ok(g) => g,
Err(poisoned) => poisoned.into_inner(),
};
*state = Arc::new(next);
self.version.store(version, Ordering::Release);
version
}
pub(crate) fn try_evict(&self) {
let Some(limit) = self.ctl.limit else {
return;
};
let _writer = match self.writer.try_lock() {
Ok(g) => g,
Err(std::sync::TryLockError::Poisoned(p)) => p.into_inner(),
Err(std::sync::TryLockError::WouldBlock) => return,
};
let current = self.load();
if let Some(data) = crate::evict::plan(¤t.data, limit, &self.ctl) {
let mut next = Snapshot::new(
current.meta.clone(),
data,
current.locale.clone(),
current.version + 1,
);
next.public = current.public;
self.publish(next);
}
}
}
enum Found {
Text(String),
Node,
Miss(Option<Arc<str>>),
}
#[derive(Clone)]
pub struct I18n {
pub(crate) inner: Arc<Inner>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct LocaleInfo {
pub code: String,
pub iso: Option<String>,
pub dir: Option<String>,
pub display_name: Option<String>,
}
impl fmt::Debug for I18n {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
let snap = self.inner.load();
f.debug_struct("I18n")
.field("locale", &snap.locale)
.field("version", &snap.public)
.field("loads", &self.inner.ctl.loads.load(Ordering::Relaxed))
.finish_non_exhaustive()
}
}
pub(crate) fn chunk_names(locale: &str, page: Option<&str>) -> Result<(), Error> {
if locale.is_empty() || locale == "__proto__" {
return Err(Error::UnknownLocale(locale.to_owned()));
}
match page {
Some("__proto__") => Err(Error::UnknownPage("__proto__".to_owned())),
_ => Ok(()),
}
}
pub(crate) fn messages_path(locale: &str, page: Option<&str>) -> String {
let page = page.filter(|p| !p.is_empty()).unwrap_or("index");
let mut path = String::with_capacity(10 + locale.len() + page.len());
path.push_str("messages:");
path.push_str(locale);
path.push('/');
path.push_str(page);
path
}
impl I18n {
#[must_use]
pub fn builder() -> Builder {
Builder::default()
}
fn translate<'k>(&self, locale: Option<&str>, page: Option<&str>, key: &'k str) -> &'k str {
if key.is_empty() {
return key;
}
let report = self.inner.missing.is_some() || crate::trace::MISSES;
let found = self.inner.read(|s| match s.lookup(locale, page, key) {
Some(e) => Ok(e.text()),
None => Err((report && locale.is_none()).then(|| s.locale.clone())),
});
match found {
Ok(text) => text.unwrap_or(key),
Err(active) => {
self.report(locale.or(active.as_deref()), page, key);
key
}
}
}
fn resolve(
&self,
locale: Option<&str>,
page: Option<&str>,
key: &str,
args: Option<&Args<'_>>,
) -> String {
if key.is_empty() {
return String::new();
}
let report = self.inner.missing.is_some() || crate::trace::MISSES;
let found = self.inner.read(|s| match s.lookup(locale, page, key) {
Some(Entry::Msg(Msg::Text(t))) => Found::Text(match args {
Some(a) => t.interpolate(a),
None => String::from(t.raw),
}),
Some(Entry::Msg(Msg::Plural(p))) => Found::Text(match args {
Some(a) => p.text.interpolate(a),
None => String::from(p.text.raw),
}),
Some(Entry::Value(v)) => Found::Text(String::from(&**v)),
Some(Entry::Node) => Found::Node,
None => Found::Miss((report && locale.is_none()).then(|| s.locale.clone())),
});
match found {
Found::Text(s) => s,
Found::Node => key.to_owned(),
Found::Miss(active) => {
self.report(locale.or(active.as_deref()), page, key);
match args.and_then(|a| a.default_text().map(|d| (a, d))) {
Some((a, d)) => interpolate_once(d, a),
None => key.to_owned(),
}
}
}
}
#[cold]
pub(crate) fn report(&self, locale: Option<&str>, page: Option<&str>, key: &str) {
let code = locale.unwrap_or("");
let page = page.filter(|p| !p.is_empty()).unwrap_or("index");
if let Some(missing) = &self.inner.missing {
missing(code, key, page);
}
crate::trace::missing(code, page, key);
}
fn resolve_count(
&self,
locale: Option<&str>,
page: Option<&str>,
key: &str,
count: Count,
args: Option<&Args<'_>>,
) -> String {
let report = self.inner.missing.is_some() || crate::trace::MISSES;
let params = WithCount { args, count };
let found = self.inner.read(|s| {
let plural = match locale {
None => s.plural,
Some(code) => s.plural_of(code),
};
match s.lookup(locale, page, key) {
Some(Entry::Msg(Msg::Text(t))) => Found::Text(t.single_form(¶ms)),
Some(Entry::Msg(Msg::Plural(p))) => Found::Text(p.pick(count, plural, ¶ms)),
Some(Entry::Value(v)) if !matches!(&**v, "true" | "false") => {
Found::Text(String::from(&**v))
}
Some(_) => Found::Node,
None => Found::Miss((report && locale.is_none()).then(|| s.locale.clone())),
}
});
match found {
Found::Text(s) => s,
Found::Node => count_fallback(key, ¶ms),
Found::Miss(active) => {
self.report(locale.or(active.as_deref()), page, key);
count_fallback(key, ¶ms)
}
}
}
fn peek(&self, locale: Option<&str>, page: Option<&str>, key: &str) -> Option<&'static str> {
self.inner
.read(|s| s.lookup(locale, page, key).and_then(Entry::text))
}
fn has_in(&self, locale: Option<&str>, page: Option<&str>, key: &str) -> bool {
self.inner.read(|s| s.has(locale, page, key))
}
#[must_use]
pub fn t<'k>(&self, key: &'k str) -> &'k str {
self.translate(None, None, key)
}
#[must_use]
pub fn t_with(&self, key: &str, args: &Args<'_>) -> String {
self.resolve(None, None, key, Some(args))
}
#[must_use]
pub fn tc(&self, key: &str, count: impl Into<Count>) -> String {
self.resolve_count(None, None, key, count.into(), None)
}
#[must_use]
pub fn tc_with(&self, key: &str, count: impl Into<Count>, args: &Args<'_>) -> String {
self.resolve_count(None, None, key, count.into(), Some(args))
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&'static str> {
self.peek(None, None, key)
}
#[must_use]
pub fn has(&self, key: &str) -> bool {
self.has_in(None, None, key)
}
#[must_use]
pub fn page(&self, name: &str) -> View {
View {
i18n: self.clone(),
locale: None,
page: Some(Arc::from(name)),
}
}
#[must_use]
pub fn with_locale(&self, code: &str) -> View {
View {
i18n: self.clone(),
locale: Some(Arc::from(code)),
page: None,
}
}
pub fn set_locale(&self, code: &str) -> Result<(), Error> {
self.inner.write(|s| {
if s.meta.disabled(code) {
return Err(Error::DisabledLocale(code.to_owned()));
}
let Some((locale, active)) = s.chains.get_key_value(code) else {
return Err(Error::UnknownLocale(code.to_owned()));
};
if &*s.locale == code {
return Ok(None);
}
Ok(Some(Snapshot {
version: s.version + 1,
public: s.public + 1,
locale: locale.clone(),
data: s.data.clone(),
chains: s.chains.clone(),
active: active.clone(),
own: s.data.get(code).cloned(),
fallback: s.fallback.clone(),
plural: s.plural_of(code),
plurals: s.plurals.clone(),
#[cfg(feature = "format")]
number: s.number_of(code),
#[cfg(feature = "format")]
numbers: s.numbers.clone(),
meta: s.meta.clone(),
}))
})?;
Ok(())
}
#[must_use]
pub fn locale(&self) -> Arc<str> {
self.inner.read(|s| s.locale.clone())
}
#[must_use]
pub fn locales(&self) -> Vec<LocaleInfo> {
self.inner.read(Snapshot::locale_infos)
}
#[must_use]
pub fn pages(&self) -> Vec<String> {
self.inner.read(|s| {
let mut pages: Vec<String> = s
.data
.values()
.flat_map(|d| d.pages.keys())
.chain(s.meta.aliases.keys())
.map(|p| String::from(&**p))
.collect();
pages.sort_unstable();
pages.dedup();
pages
})
}
#[must_use]
pub fn has_locale(&self, code: &str) -> bool {
self.inner.read(|s| {
let meta = &s.meta;
match meta.configured.iter().find(|l| l.code == code) {
Some(l) => !l.disabled,
None => s.data.contains_key(code) || meta.declared.iter().any(|d| &**d == code),
}
})
}
#[must_use]
pub fn has_page(&self, name: &str) -> bool {
self.inner.read(|s| {
s.meta.aliases.contains_key(name) || s.data.values().any(|d| d.pages.contains_key(name))
})
}
pub fn add_messages(&self, locale: &str, page: Option<&str>, json: &str) -> Result<(), Error> {
chunk_names(locale, page)?;
let tree = Tree::parse(json.as_bytes(), &messages_path(locale, page))?;
self.inner.write(|s| {
let mut data = DataMap::clone(&s.data);
let mut slot = data
.get(locale)
.map(|d| LocaleData::clone(d))
.unwrap_or_default();
merge_into(&mut slot, s.meta.page(page), tree);
data.insert(Arc::from(locale), Arc::new(slot));
Ok(Some(Snapshot::new(
s.meta.clone(),
data,
s.locale.clone(),
s.version + 1,
)))
})?;
Ok(())
}
pub fn reload(&self) -> Result<(), Error> {
let timer = crate::trace::Timer::start();
let inner = &*self.inner;
let mut broken = Vec::new();
inner.write(|s| {
let mut data = source::load(&inner.sources, &s.meta, &inner.ctl)?;
if let Some(resolve) = s.meta.linked {
broken = resolve(&mut data, &s.meta);
check::lock(&s.meta.check.broken).clone_from(&broken);
}
let data = data.into_iter().map(|(k, v)| (k, Arc::new(v))).collect();
Ok(Some(Snapshot::new(
s.meta.clone(),
data,
s.locale.clone(),
s.version + 1,
)))
})?;
timer.done("reload", "", 0);
report_broken(inner.missing.as_ref(), &broken);
Ok(())
}
#[must_use]
pub fn version(&self) -> u64 {
self.inner.read(|s| s.public)
}
}
#[cfg(feature = "payload")]
impl I18n {
#[cfg(all(feature = "tauri-guest", target_arch = "wasm32", target_os = "unknown"))]
pub(crate) fn ready_chunk(&self, locale: &str, page: Option<&str>) -> Option<Arc<Tree>> {
self.inner
.read(|s| match s.data.get(locale)?.layer(s.meta.page(page))? {
Layer::Ready(c) => Some(c.clone()),
Layer::Lazy(_) => None,
})
}
pub(crate) fn replace_chunks(
&self,
chunks: Vec<(Arc<str>, Option<String>, Arc<Tree>)>,
locale: Option<&str>,
) -> Result<(), Error> {
self.inner.write(|s| {
let mut data = DataMap::clone(&s.data);
let mut slots: Vec<(Arc<str>, LocaleData)> = Vec::new();
for (code, page, tree) in &chunks {
let at = match slots.iter().position(|(c, _)| c == code) {
Some(at) => at,
None => {
let slot = data.get(code).map(|d| LocaleData::clone(d));
slots.push((code.clone(), slot.unwrap_or_default()));
slots.len() - 1
}
};
put(
&mut slots[at].1,
s.meta.page(page.as_deref()),
Layer::Ready(tree.clone()),
);
}
for (code, slot) in slots {
data.insert(code, Arc::new(slot));
}
let active = match locale {
Some(l) if !s.meta.disabled(l) => Arc::from(l),
_ => s.locale.clone(),
};
Ok(Some(Snapshot::new(
s.meta.clone(),
data,
active,
s.version + 1,
)))
})?;
Ok(())
}
}
fn count_fallback(key: &str, params: &WithCount<'_, '_>) -> String {
match params.args.and_then(Args::default_raw) {
Some("") => String::new(),
Some(d) => interpolate_once(d, params),
None => key.to_owned(),
}
}
fn merge_into(slot: &mut LocaleData, page: Option<&str>, tree: Tree) {
let layer = slot.layer(page);
let chunk = match layer {
Some(Layer::Lazy(cell)) => match if cell.remote {
cell.loaded()
} else {
cell.get()
} {
Some(loaded) => Some(loaded),
None => {
let waiting = Layer::Lazy(Arc::new(cell.with_over(tree)));
put(slot, page, waiting);
return;
}
},
Some(Layer::Ready(c)) => Some(&**c),
None => None,
};
let mut merged = chunk.cloned().unwrap_or_default();
merged.merge(tree);
put(slot, page, Layer::Ready(Arc::new(merged)));
}
fn put(slot: &mut LocaleData, page: Option<&str>, chunk: Layer) {
match page {
None => slot.root = Some(chunk),
Some(p) => {
slot.pages.insert(Arc::from(p), chunk);
}
}
}
#[derive(Clone)]
pub struct View {
pub(crate) i18n: I18n,
pub(crate) locale: Option<Arc<str>>,
pub(crate) page: Option<Arc<str>>,
}
impl fmt::Debug for View {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("View")
.field("locale", &self.locale)
.field("page", &self.page)
.finish_non_exhaustive()
}
}
impl View {
fn parts(&self) -> (Option<&str>, Option<&str>) {
(self.locale.as_deref(), self.page.as_deref())
}
#[must_use]
pub fn t<'k>(&self, key: &'k str) -> &'k str {
let (l, p) = self.parts();
self.i18n.translate(l, p, key)
}
#[must_use]
pub fn t_with(&self, key: &str, args: &Args<'_>) -> String {
let (l, p) = self.parts();
self.i18n.resolve(l, p, key, Some(args))
}
#[must_use]
pub fn tc(&self, key: &str, count: impl Into<Count>) -> String {
let (l, p) = self.parts();
self.i18n.resolve_count(l, p, key, count.into(), None)
}
#[must_use]
pub fn tc_with(&self, key: &str, count: impl Into<Count>, args: &Args<'_>) -> String {
let (l, p) = self.parts();
self.i18n.resolve_count(l, p, key, count.into(), Some(args))
}
#[must_use]
pub fn get(&self, key: &str) -> Option<&'static str> {
let (l, p) = self.parts();
self.i18n.peek(l, p, key)
}
#[must_use]
pub fn has(&self, key: &str) -> bool {
let (l, p) = self.parts();
self.i18n.has_in(l, p, key)
}
#[must_use]
pub fn page(&self, name: &str) -> View {
View {
page: Some(Arc::from(name)),
..self.clone()
}
}
#[must_use]
pub fn with_locale(&self, code: &str) -> View {
View {
locale: Some(Arc::from(code)),
..self.clone()
}
}
#[must_use]
pub fn locale(&self) -> Arc<str> {
match &self.locale {
Some(l) => l.clone(),
None => self.i18n.locale(),
}
}
}
enum ConfigSource {
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
Path(std::path::PathBuf),
Json(String),
}
#[derive(Default)]
pub struct Builder {
locale: Option<String>,
fallback: Option<String>,
links: Vec<(String, String)>,
iso: Vec<(String, String)>,
sources: Sources,
aliases: Vec<(String, String)>,
config: Option<ConfigSource>,
missing: Option<Missing>,
linked: Option<ResolveLinked>,
#[cfg(feature = "format")]
pub(crate) formats: Vec<String>,
#[cfg(feature = "format")]
pub(crate) datetime_formats: Vec<String>,
#[cfg(feature = "format")]
time_zone: Option<String>,
#[cfg(feature = "format")]
clock: Option<crate::format::api::Clock>,
#[cfg(feature = "format")]
dates: Option<SetupDates>,
}
#[cfg(feature = "format")]
type SetupDates =
fn(&Builder, &Config, &mut Meta, &mut crate::format::options::Numbering) -> Result<(), Error>;
#[cfg(feature = "format")]
fn setup_dates(
b: &Builder,
config: &Config,
meta: &mut Meta,
numbering: &mut crate::format::options::Numbering,
) -> Result<(), Error> {
if let Some(json) = &config.datetime_formats {
let path = b.config_path();
crate::format::parse_date_formats(json, &path, &mut meta.dates, numbering)?;
}
for json in &b.datetime_formats {
crate::format::parse_date_formats(json, "datetime_formats", &mut meta.dates, numbering)?;
}
if let Some(name) = b.time_zone.as_ref().filter(|n| !n.is_empty()) {
let zone = crate::format::date::zone_named(name)
.ok_or_else(|| Error::UnknownTimeZone(name.clone()))?;
meta.zone = Some(zone);
meta.zone_name = Some(Box::from(name.as_str()));
}
Ok(())
}
impl fmt::Debug for Builder {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.debug_struct("Builder")
.field("locale", &self.locale)
.field("fallback", &self.fallback)
.field("files", &self.sources.files.len())
.finish_non_exhaustive()
}
}
impl Builder {
#[must_use]
pub fn locale(mut self, code: &str) -> Self {
self.locale = Some(code.to_owned());
self
}
#[cfg(feature = "format")]
#[must_use]
pub fn formats(mut self, number_formats: &str) -> Self {
self.formats.push(number_formats.to_owned());
self
}
#[cfg(feature = "format")]
#[must_use]
pub fn datetime_formats(mut self, datetime_formats: &str) -> Self {
self.datetime_formats.push(datetime_formats.to_owned());
self.with_dates()
}
#[allow(unused_mut, reason = "mutates with `format` only")]
fn with_dates(mut self) -> Self {
#[cfg(feature = "format")]
{
self.dates = Some(setup_dates);
}
self
}
#[cfg(feature = "format")]
#[must_use]
pub fn time_zone(mut self, iana: &str) -> Self {
self.time_zone = Some(iana.to_owned());
self.with_dates()
}
#[cfg(feature = "format")]
#[must_use]
pub fn clock(mut self, now: impl Fn() -> i64 + Send + Sync + 'static) -> Self {
self.clock = Some(crate::format::api::Clock(Arc::new(now)));
self
}
#[must_use]
pub fn fallback(mut self, code: &str) -> Self {
self.fallback = Some(code.to_owned());
self
}
#[must_use]
pub fn fallback_for(mut self, locale: &str, fallback: &str) -> Self {
self.links.push((locale.to_owned(), fallback.to_owned()));
self
}
#[must_use]
pub fn iso(mut self, code: &str, tag: &str) -> Self {
self.iso.push((code.to_owned(), tag.to_owned()));
self
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
#[must_use]
pub fn dir(mut self, path: impl AsRef<std::path::Path>) -> Self {
self.sources.dirs.push(path.as_ref().to_path_buf());
self
}
#[must_use]
pub fn files<I, P, B>(mut self, files: I) -> Self
where
I: IntoIterator<Item = (P, B)>,
P: AsRef<str>,
B: AsRef<[u8]>,
{
self.sources.files.extend(embedded(files));
self
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
#[must_use]
pub fn lazy_dir(mut self, path: impl AsRef<std::path::Path>) -> Self {
self.sources.lazy_dirs.push(path.as_ref().to_path_buf());
self.sources.lazy = Some(source::LAZY);
self
}
#[must_use]
pub fn lazy_files<I, P, B>(mut self, files: I) -> Self
where
I: IntoIterator<Item = (P, B)>,
P: AsRef<str>,
B: AsRef<[u8]>,
{
self.sources.lazy_files.extend(embedded(files));
self.sources.lazy = Some(source::LAZY);
self
}
#[must_use]
pub fn remote<I>(mut self, manifest: I) -> Self
where
I: IntoIterator,
I::Item: AsRef<str>,
{
self.sources
.remote
.extend(manifest.into_iter().map(|p| source::normalize(p.as_ref())));
self.sources.lazy = Some(source::LAZY);
self
}
#[must_use]
pub fn extend<I, P, B>(mut self, files: I) -> Self
where
I: IntoIterator<Item = (P, B)>,
P: AsRef<str>,
B: AsRef<[u8]>,
{
self.sources.extend.push(embedded(files).collect());
self
}
#[must_use]
pub fn evict_pages(mut self, n: usize) -> Self {
self.sources.evict = Some(n.max(1));
self
}
#[must_use]
pub fn pin_page(mut self, name: &str) -> Self {
self.sources.pins.push(name.to_owned());
self
}
#[must_use]
pub fn messages(mut self, locale: &str, page: Option<&str>, json: &str) -> Self {
self.sources
.messages
.push((locale.to_owned(), page.map(str::to_owned), json.to_owned()));
self
}
#[must_use]
pub fn pages(mut self, enabled: bool) -> Self {
self.sources.no_pages = !enabled;
self
}
#[must_use]
pub fn page_alias(mut self, from: &str, to: &str) -> Self {
self.aliases.push((from.to_owned(), to.to_owned()));
self
}
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
#[must_use]
pub fn config(mut self, path: impl AsRef<std::path::Path>) -> Self {
self.config = Some(ConfigSource::Path(path.as_ref().to_path_buf()));
self.with_dates()
}
#[must_use]
pub fn config_json(mut self, json: &str) -> Self {
self.config = Some(ConfigSource::Json(json.to_owned()));
self.with_dates()
}
#[must_use]
pub fn missing(mut self, handler: impl Fn(&str, &str, &str) + Send + Sync + 'static) -> Self {
self.missing = Some(Box::new(handler));
self
}
#[must_use]
pub fn linked_messages(mut self, enabled: bool) -> Self {
self.linked = enabled.then_some(resolve_linked as ResolveLinked);
self
}
#[cfg(feature = "format")]
fn config_path(&self) -> String {
match &self.config {
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
Some(ConfigSource::Path(path)) => path.to_string_lossy().into_owned(),
_ => "i18n.json".to_owned(),
}
}
fn read_config(&self) -> Result<Config, Error> {
match &self.config {
None => Ok(Config::default()),
#[cfg(not(all(target_arch = "wasm32", target_os = "unknown")))]
Some(ConfigSource::Path(path)) => {
let shown = path.to_string_lossy();
let bytes = std::fs::read(path).map_err(|source| Error::Io {
path: shown.clone().into_owned(),
source,
})?;
Config::parse(&bytes, &shown)
}
Some(ConfigSource::Json(json)) => Config::parse(json.as_bytes(), "i18n.json"),
}
}
#[cfg(feature = "global")]
pub fn install(self) -> Result<&'static I18n, Error> {
crate::scope::install(self.build()?)?;
crate::scope::global().ok_or(Error::NotInstalled)
}
pub fn build(mut self) -> Result<I18n, Error> {
let config = self.read_config()?;
let mut meta = Meta {
fallback: self
.fallback
.as_deref()
.or(config.fallback_locale.as_deref())
.map(Arc::from),
..Meta::default()
};
#[cfg(feature = "format")]
let mut numbering = Vec::new();
#[cfg(feature = "format")]
{
if let Some(json) = &config.number_formats {
let path = self.config_path();
crate::format::parse_formats(json, &path, &mut meta.numbers, &mut numbering)?;
}
for json in &self.formats {
crate::format::parse_formats(json, "formats", &mut meta.numbers, &mut numbering)?;
}
if let Some(setup) = self.dates {
setup(&self, &config, &mut meta, &mut numbering)?;
}
meta.clock = self.clock.take();
}
for l in &config.locales {
if let Some(fb) = &l.fallback {
meta.links.insert(Arc::from(&*l.code), Arc::from(&**fb));
}
if let Some(iso) = &l.iso {
meta.iso.insert(Arc::from(&*l.code), Arc::from(&**iso));
}
}
for (l, fb) in &self.links {
meta.links.insert(Arc::from(&**l), Arc::from(&**fb));
}
for (code, tag) in &self.iso {
meta.iso.insert(Arc::from(&**code), Arc::from(&**tag));
}
#[cfg(feature = "format")]
crate::format::options::check_numbering(&numbering, |code| meta.number(code))?;
#[cfg(feature = "payload")]
{
meta.formats = crate::payload::Formats::new(&self, &config);
}
meta.configured = config.locales;
let locale: Arc<str> = Arc::from(
self.locale
.as_deref()
.or(config.default_locale.as_deref())
.unwrap_or("en"),
);
let mut declared = Vec::new();
let mut declare = |code: &str| {
if !declared.iter().any(|d: &Arc<str>| &**d == code) {
declared.push(Arc::from(code));
}
};
for code in [self.locale.as_deref(), config.default_locale.as_deref()]
.into_iter()
.flatten()
{
declare(code);
}
declare(&locale);
for (code, fallback) in &meta.links {
declare(code);
declare(fallback);
}
for code in meta.fallback.iter().chain(meta.iso.keys()) {
declare(code);
}
meta.declared = declared;
if meta.disabled(&locale) {
return Err(Error::DisabledLocale(String::from(&*locale)));
}
for (from, to) in &self.aliases {
meta.aliases.insert(Arc::from(&**from), Arc::from(&**to));
}
let ctl = Arc::new(LazyCtl::new(self.sources.evict));
self.sources.parse_files()?;
let mut data = source::load(&self.sources, &meta, &ctl)?;
if !self.sources.no_pages {
for to in meta.aliases.values() {
let defined = &**to == "index" || data.values().any(|d| d.pages.contains_key(to));
if !defined {
return Err(Error::UnknownPage(String::from(&**to)));
}
}
}
meta.check.reference = Some(
config
.default_locale
.as_deref()
.map_or_else(|| locale.clone(), Arc::from),
);
meta.linked = self.linked;
if let Some(resolve) = self.linked {
let broken = resolve(&mut data, &meta);
report_broken(self.missing.as_ref(), &broken);
*check::lock(&meta.check.broken) = broken;
}
let data = data.into_iter().map(|(k, v)| (k, Arc::new(v))).collect();
let snapshot = Snapshot::new(Arc::new(meta), data, locale, 0);
let inner = Arc::new(Inner {
id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
version: AtomicU64::new(0),
state: RwLock::new(Arc::new(snapshot)),
writer: Mutex::new(()),
missing: self.missing,
alive: Arc::new(AtomicBool::new(true)),
remote: source::remote_index(&self.sources),
sources: self.sources,
ctl: ctl.clone(),
listeners: Listeners::default(),
});
let _ = ctl.owner.set(Arc::downgrade(&inner));
Ok(I18n { inner })
}
}
type ResolveLinked = fn(&mut FastMap<Arc<str>, LocaleData>, &Meta) -> Vec<crate::linked::Broken>;
fn report_broken(missing: Option<&Missing>, broken: &[crate::linked::Broken]) {
let Some(missing) = missing else { return };
let mut last = None;
for b in broken {
let at = (&b.locale, &b.page, &b.key);
if last != Some(at) {
missing(&b.locale, &b.key, b.page.as_deref().unwrap_or("index"));
last = Some(at);
}
}
}
fn resolve_linked(
data: &mut FastMap<Arc<str>, LocaleData>,
meta: &Meta,
) -> Vec<crate::linked::Broken> {
let mut chunks = crate::linked::Chunks::new();
for (code, d) in data.iter_mut() {
if let Some(Layer::Ready(c)) = d.root.take_if(|l| matches!(l, Layer::Ready(_))) {
chunks.push(((code.clone(), None), c));
}
let ready: Vec<Arc<str>> = d
.pages
.iter()
.filter(|(_, l)| matches!(l, Layer::Ready(_)))
.map(|(p, _)| p.clone())
.collect();
for p in ready {
if let Some(Layer::Ready(c)) = d.pages.remove(&p) {
chunks.push(((code.clone(), Some(p)), c));
}
}
}
chunks.sort_unstable_by(|a, b| a.0.cmp(&b.0));
let setup = crate::linked::Setup {
links: &meta.links,
fallback: meta.fallback.as_deref(),
iso: &meta.iso,
};
let mut broken = crate::linked::resolve(&mut chunks, &setup);
for ((code, page), chunk) in chunks {
let d = data.entry(code).or_default();
match page {
None if matches!(d.root, Some(Layer::Lazy(_))) => {}
None => d.root = Some(Layer::Ready(chunk)),
Some(p) if matches!(d.pages.get(&p), Some(Layer::Lazy(_))) => {}
Some(p) => {
d.pages.insert(p, Layer::Ready(chunk));
}
}
}
crate::linked::lazy_contexts(data, &setup);
crate::linked::mark_lazy(&mut broken, data, &setup);
broken
}
impl I18n {
#[must_use]
pub fn check(&self) -> CheckReport {
self.inner.read(|s| {
let meta = &s.meta;
let chunks = s
.data
.iter()
.filter(|(code, _)| !meta.disabled(code))
.flat_map(|(code, d)| {
let root = d
.root
.iter()
.filter_map(move |l| Some((code, None, l.chunk()?)));
let pages = d.pages.iter();
root.chain(pages.filter_map(move |(p, l)| Some((code, Some(p), l.chunk()?))))
});
check::run(chunks, &meta.check, |code| s.plural_of(code))
})
}
}
fn embedded<I, P, B>(files: I) -> impl Iterator<Item = (String, source::Bytes)>
where
I: IntoIterator<Item = (P, B)>,
P: AsRef<str>,
B: AsRef<[u8]>,
{
files
.into_iter()
.map(|(p, b)| (source::normalize(p.as_ref()), Arc::from(b.as_ref())))
}