use core::fmt;
pub const BASE_LANG: &str = "en";
pub const DEFAULT_LANG: &str = BASE_LANG;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum TextArg<'a> {
Str(&'a str),
Int(i64),
}
impl fmt::Display for TextArg<'_> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
TextArg::Str(s) => f.write_str(s),
TextArg::Int(n) => write!(f, "{n}"),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Seg {
Lit(&'static str),
Var(&'static str),
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Catalog {
pub lang: &'static str,
pub entries: &'static [(&'static str, &'static [Seg])],
}
impl Catalog {
pub fn get(&self, key: &str) -> Option<&'static [Seg]> {
self.entries
.binary_search_by(|(k, _)| (*k).cmp(key))
.ok()
.map(|i| self.entries[i].1)
}
}
pub fn find(catalogs: &[Catalog], lang: &str, key: &str) -> Option<&'static [Seg]> {
let get = |l: &str| {
catalogs
.iter()
.find(|c| c.lang == l)
.and_then(|c| c.get(key))
};
get(lang).or_else(|| get(BASE_LANG))
}
pub fn write_segs(
out: &mut dyn fmt::Write,
segs: &[Seg],
var: &mut dyn FnMut(&str, &mut dyn fmt::Write) -> fmt::Result,
) -> fmt::Result {
for s in segs {
match s {
Seg::Lit(t) => out.write_str(t)?,
Seg::Var(n) => var(n, out)?,
}
}
Ok(())
}
pub trait Localized {
fn text_key(&self) -> &'static str;
fn text_args(&self, f: &mut dyn FnMut(&'static str, TextArg<'_>)) {
let _ = f;
}
fn catalogs(&self) -> &'static [Catalog] {
&[]
}
}
pub fn write_localized<E: Localized + ?Sized>(
out: &mut dyn fmt::Write,
e: &E,
lang: &str,
) -> fmt::Result {
let Some(segs) = find(e.catalogs(), lang, e.text_key()) else {
return out.write_str(e.text_key());
};
write_segs(out, segs, &mut |name, w| {
let mut r = Ok(());
e.text_args(&mut |n, v| {
if n == name && r.is_ok() {
r = write!(w, "{v}");
}
});
r
})
}
pub struct InLang<'a, E: ?Sized>(pub &'a E, pub &'a str);
impl<E: Localized + ?Sized> fmt::Display for InLang<'_, E> {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
write_localized(f, self.0, self.1)
}
}
pub(crate) mod table {
use super::{Catalog, Seg};
include!(concat!(env!("OUT_DIR"), "/text.rs"));
}
#[cfg(test)]
mod tests {
use super::*;
struct E(i64);
static CATS: &[Catalog] = &[
Catalog {
lang: "en",
entries: &[("k", &[Seg::Lit("n="), Seg::Var("n"), Seg::Lit("!")])],
},
Catalog {
lang: "ja",
entries: &[],
},
];
impl Localized for E {
fn text_key(&self) -> &'static str {
"k"
}
fn text_args(&self, f: &mut dyn FnMut(&'static str, TextArg<'_>)) {
f("n", TextArg::Int(self.0));
}
fn catalogs(&self) -> &'static [Catalog] {
CATS
}
}
struct Buf([u8; 32], usize);
impl fmt::Write for Buf {
fn write_str(&mut self, s: &str) -> fmt::Result {
let b = s.as_bytes();
let end = self.1 + b.len();
if end > self.0.len() {
return Err(fmt::Error);
}
self.0[self.1..end].copy_from_slice(b);
self.1 = end;
Ok(())
}
}
#[test]
fn falls_back_to_the_base_language() {
let mut b = Buf([0; 32], 0);
write_localized(&mut b, &E(-3), "ja").unwrap();
assert_eq!(core::str::from_utf8(&b.0[..b.1]).unwrap(), "n=-3!");
}
}