1use core::fmt;
9
10pub const BASE_LANG: &str = "en";
12
13pub const DEFAULT_LANG: &str = BASE_LANG;
17
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
20pub enum TextArg<'a> {
21 Str(&'a str),
23 Int(i64),
25}
26
27impl fmt::Display for TextArg<'_> {
28 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
29 match self {
30 TextArg::Str(s) => f.write_str(s),
31 TextArg::Int(n) => write!(f, "{n}"),
32 }
33 }
34}
35
36#[derive(Debug, Clone, Copy, PartialEq, Eq)]
38pub enum Seg {
39 Lit(&'static str),
41 Var(&'static str),
43}
44
45#[derive(Debug, Clone, Copy, PartialEq, Eq)]
47pub struct Catalog {
48 pub lang: &'static str,
50 pub entries: &'static [(&'static str, &'static [Seg])],
52}
53
54impl Catalog {
55 pub fn get(&self, key: &str) -> Option<&'static [Seg]> {
57 self.entries
58 .binary_search_by(|(k, _)| (*k).cmp(key))
59 .ok()
60 .map(|i| self.entries[i].1)
61 }
62}
63
64pub fn find(catalogs: &[Catalog], lang: &str, key: &str) -> Option<&'static [Seg]> {
66 let get = |l: &str| {
67 catalogs
68 .iter()
69 .find(|c| c.lang == l)
70 .and_then(|c| c.get(key))
71 };
72 get(lang).or_else(|| get(BASE_LANG))
73}
74
75pub fn write_segs(
77 out: &mut dyn fmt::Write,
78 segs: &[Seg],
79 var: &mut dyn FnMut(&str, &mut dyn fmt::Write) -> fmt::Result,
80) -> fmt::Result {
81 for s in segs {
82 match s {
83 Seg::Lit(t) => out.write_str(t)?,
84 Seg::Var(n) => var(n, out)?,
85 }
86 }
87 Ok(())
88}
89
90pub trait Localized {
92 fn text_key(&self) -> &'static str;
94
95 fn text_args(&self, f: &mut dyn FnMut(&'static str, TextArg<'_>)) {
97 let _ = f;
98 }
99
100 fn catalogs(&self) -> &'static [Catalog] {
103 &[]
104 }
105}
106
107pub fn write_localized<E: Localized + ?Sized>(
109 out: &mut dyn fmt::Write,
110 e: &E,
111 lang: &str,
112) -> fmt::Result {
113 let Some(segs) = find(e.catalogs(), lang, e.text_key()) else {
114 return out.write_str(e.text_key());
115 };
116 write_segs(out, segs, &mut |name, w| {
117 let mut r = Ok(());
118 e.text_args(&mut |n, v| {
119 if n == name && r.is_ok() {
120 r = write!(w, "{v}");
121 }
122 });
123 r
124 })
125}
126
127pub struct InLang<'a, E: ?Sized>(pub &'a E, pub &'a str);
129
130impl<E: Localized + ?Sized> fmt::Display for InLang<'_, E> {
131 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
132 write_localized(f, self.0, self.1)
133 }
134}
135
136pub(crate) mod table {
138 use super::{Catalog, Seg};
139 include!(concat!(env!("OUT_DIR"), "/text.rs"));
140}
141
142#[cfg(test)]
143mod tests {
144 use super::*;
145
146 struct E(i64);
147 static CATS: &[Catalog] = &[
148 Catalog {
149 lang: "en",
150 entries: &[("k", &[Seg::Lit("n="), Seg::Var("n"), Seg::Lit("!")])],
151 },
152 Catalog {
153 lang: "ja",
154 entries: &[],
155 },
156 ];
157 impl Localized for E {
158 fn text_key(&self) -> &'static str {
159 "k"
160 }
161 fn text_args(&self, f: &mut dyn FnMut(&'static str, TextArg<'_>)) {
162 f("n", TextArg::Int(self.0));
163 }
164 fn catalogs(&self) -> &'static [Catalog] {
165 CATS
166 }
167 }
168
169 struct Buf([u8; 32], usize);
170 impl fmt::Write for Buf {
171 fn write_str(&mut self, s: &str) -> fmt::Result {
172 let b = s.as_bytes();
173 let end = self.1 + b.len();
174 if end > self.0.len() {
175 return Err(fmt::Error);
176 }
177 self.0[self.1..end].copy_from_slice(b);
178 self.1 = end;
179 Ok(())
180 }
181 }
182
183 #[test]
184 fn falls_back_to_the_base_language() {
185 let mut b = Buf([0; 32], 0);
186 write_localized(&mut b, &E(-3), "ja").unwrap();
187 assert_eq!(core::str::from_utf8(&b.0[..b.1]).unwrap(), "n=-3!");
188 }
189}