intl_memoizer_for_carbide/lib.rs
1//! This crate contains a memoizer for internationalization formatters. Often it is
2//! expensive (in terms of performance and memory) to constuct a formatter, but then
3//! relatively cheap to run the format operation.
4//!
5//! The [IntlMemoizer] is the main struct that creates a per-locale [IntlLangMemoizer].
6
7use std::cell::RefCell;
8use std::collections::hash_map::Entry;
9use std::collections::HashMap;
10use std::hash::Hash;
11use std::rc::{Rc, Weak};
12use icu::locid::Locale;
13
14pub mod concurrent;
15
16/// The trait that needs to be implemented for each intl formatter that needs to be
17/// memoized.
18pub trait Memoizable {
19 /// Type of the arguments that are used to construct the formatter.
20 type Args: 'static + Eq + Hash + Clone;
21
22 /// Type of any errors that can occur during the construction process.
23 type Error;
24
25 /// Construct a formatter. This maps the [`Self::Args`] type to the actual constructor
26 /// for an intl formatter.
27 fn construct(lang: Locale, args: Self::Args) -> Result<Self, Self::Error>
28 where
29 Self: std::marker::Sized;
30}
31
32/// The [`IntlLangMemoizer`] can memoize multiple constructed internationalization
33/// formatters, and their configuration for a single locale. For instance, given "en-US",
34/// a memorizer could retain 3 DateTimeFormat instances, and a PluralRules.
35///
36/// For memoizing with multiple locales, see [`IntlMemoizer`].
37///
38/// # Example
39///
40/// The code example does the following steps:
41///
42/// 1. Create a static counter
43/// 2. Create an `ExampleFormatter`
44/// 3. Implement [`Memoizable`] for `ExampleFormatter`.
45/// 4. Use `IntlLangMemoizer::with_try_get` to run `ExampleFormatter::format`
46/// 5. Demonstrate the memoization using the static counter
47///
48/// ```
49/// use intl_memoizer::{IntlLangMemoizer, Memoizable};
50/// use icu::locid::Locale;
51///
52/// // Create a static counter so that we can demonstrate the side effects of when
53/// // the memoizer re-constructs an API.
54///
55/// static mut INTL_EXAMPLE_CONSTRUCTS: u32 = 0;
56/// fn increment_constructs() {
57/// unsafe {
58/// INTL_EXAMPLE_CONSTRUCTS += 1;
59/// }
60/// }
61///
62/// fn get_constructs_count() -> u32 {
63/// unsafe { INTL_EXAMPLE_CONSTRUCTS }
64/// }
65///
66/// /// Create an example formatter, that doesn't really do anything useful. In a real
67/// /// implementation, this could be a PluralRules or DateTimeFormat struct.
68/// struct ExampleFormatter {
69/// lang: Locale,
70/// /// This is here to show how to initiate the API with an argument.
71/// prefix: String,
72/// }
73///
74/// impl ExampleFormatter {
75/// /// Perform an example format by printing information about the formatter
76/// /// configuration, and the arguments passed into the individual format operation.
77/// fn format(&self, example_string: &str) -> String {
78/// format!(
79/// "{} lang({}) string({})",
80/// self.prefix, self.lang, example_string
81/// )
82/// }
83/// }
84///
85/// /// Multiple classes of structs may be add1ed to the memoizer, with the restriction
86/// /// that they must implement the `Memoizable` trait.
87/// impl Memoizable for ExampleFormatter {
88/// /// The arguments will be passed into the constructor. Here a single `String`
89/// /// will be used as a prefix to the formatting operation.
90/// type Args = (String,);
91///
92/// /// If the construtor is fallible, than errors can be described here.
93/// type Error = ();
94///
95/// /// This function wires together the `Args` and `Error` type to construct
96/// /// the intl API. In our example, there is
97/// fn construct(lang: Locale, args: Self::Args) -> Result<Self, Self::Error> {
98/// // Keep track for example purposes that this was constructed.
99/// increment_constructs();
100///
101/// Ok(Self {
102/// lang,
103/// prefix: args.0,
104/// })
105/// }
106/// }
107///
108/// // The following demonstrates how these structs are actually used with the memoizer.
109///
110/// // Construct a new memoizer.
111/// let lang = "en-US".parse().expect("Failed to parse.");
112/// let memoizer = IntlLangMemoizer::new(lang);
113///
114/// // These arguments are passed into the constructor for `ExampleFormatter`.
115/// let construct_args = (String::from("prefix:"),);
116/// let message1 = "The format operation will run";
117/// let message2 = "ExampleFormatter will be re-used, when a second format is run";
118///
119/// // Run `IntlLangMemoizer::with_try_get`. The name of the method means "with" an
120/// // intl formatter, "try and get" the result. See the method documentation for
121/// // more details.
122///
123/// let result1 = memoizer
124/// .with_try_get::<ExampleFormatter, _, _>(construct_args.clone(), |intl_example| {
125/// intl_example.format(message1)
126/// });
127///
128/// // The memoized instance of `ExampleFormatter` will be re-used.
129/// let result2 = memoizer
130/// .with_try_get::<ExampleFormatter, _, _>(construct_args.clone(), |intl_example| {
131/// intl_example.format(message2)
132/// });
133///
134/// assert_eq!(
135/// result1.unwrap(),
136/// "prefix: lang(en-US) string(The format operation will run)"
137/// );
138/// assert_eq!(
139/// result2.unwrap(),
140/// "prefix: lang(en-US) string(ExampleFormatter will be re-used, when a second format is run)"
141/// );
142/// assert_eq!(
143/// get_constructs_count(),
144/// 1,
145/// "The constructor was only run once."
146/// );
147///
148/// let construct_args = (String::from("re-init:"),);
149///
150/// // Since the constructor args changed, `ExampleFormatter` will be re-constructed.
151/// let result1 = memoizer
152/// .with_try_get::<ExampleFormatter, _, _>(construct_args.clone(), |intl_example| {
153/// intl_example.format(message1)
154/// });
155///
156/// // The memoized instance of `ExampleFormatter` will be re-used.
157/// let result2 = memoizer
158/// .with_try_get::<ExampleFormatter, _, _>(construct_args.clone(), |intl_example| {
159/// intl_example.format(message2)
160/// });
161///
162/// assert_eq!(
163/// result1.unwrap(),
164/// "re-init: lang(en-US) string(The format operation will run)"
165/// );
166/// assert_eq!(
167/// result2.unwrap(),
168/// "re-init: lang(en-US) string(ExampleFormatter will be re-used, when a second format is run)"
169/// );
170/// assert_eq!(
171/// get_constructs_count(),
172/// 2,
173/// "The constructor was invalidated and ran again."
174/// );
175/// ```
176#[derive(Debug)]
177pub struct IntlLangMemoizer {
178 lang: Locale,
179 map: RefCell<type_map::TypeMap>,
180}
181
182impl IntlLangMemoizer {
183 /// Create a new [`IntlLangMemoizer`] that is unique to a specific
184 /// [`Locale`]
185 pub fn new(lang: Locale) -> Self {
186 Self {
187 lang,
188 map: RefCell::new(type_map::TypeMap::new()),
189 }
190 }
191
192 pub fn lang(&self) -> &Locale {
193 &self.lang
194 }
195
196 /// `with_try_get` means `with` an internationalization formatter, `try` and `get` a result.
197 /// The (potentially expensive) constructor for the formatter (such as PluralRules or
198 /// DateTimeFormat) will be memoized and only constructed once for a given
199 /// `construct_args`. After that the format operation can be run multiple times
200 /// inexpensively.
201 ///
202 /// The first generic argument `I` must be provided, but the `R` and `U` will be
203 /// deduced by the typing of the `callback` argument that is provided.
204 ///
205 /// I - The memoizable intl object, for instance a `PluralRules` instance. This
206 /// must implement the Memoizable trait.
207 ///
208 /// R - The return result from the callback `U`.
209 ///
210 /// U - The callback function. Takes an instance of `I` as the first parameter and
211 /// returns the R value.
212 pub fn with_try_get<I, R, U>(&self, construct_args: I::Args, callback: U) -> Result<R, I::Error>
213 where
214 Self: Sized,
215 I: Memoizable + 'static,
216 U: FnOnce(&I) -> R,
217 {
218 let mut map = self
219 .map
220 .try_borrow_mut()
221 .expect("Cannot use memoizer reentrantly");
222 let cache = map
223 .entry::<HashMap<I::Args, I>>()
224 .or_insert_with(HashMap::new);
225
226 let e = match cache.entry(construct_args.clone()) {
227 Entry::Occupied(entry) => entry.into_mut(),
228 Entry::Vacant(entry) => {
229 let val = I::construct(self.lang.clone(), construct_args)?;
230 entry.insert(val)
231 }
232 };
233 Ok(callback(e))
234 }
235}
236
237/// [`IntlMemoizer`] is designed to handle lazily-initialized references to
238/// internationalization formatters.
239///
240/// Constructing a new formatter is often expensive in terms of memory and performance,
241/// and the instance is often read-only during its lifetime. The format operations in
242/// comparison are relatively cheap.
243///
244/// Because of this relationship, it can be helpful to memoize the constructors, and
245/// re-use them across multiple format operations. This strategy is used where all
246/// instances of intl APIs such as `PluralRules`, `DateTimeFormat` etc. are memoized
247/// between all `FluentBundle` instances.
248///
249/// # Example
250///
251/// For a more complete example of the memoization, see the [`IntlLangMemoizer`] documentation.
252/// This example provides a higher-level overview.
253///
254/// ```
255/// # use intl_memoizer::{IntlMemoizer, IntlLangMemoizer, Memoizable};
256/// # use icu::locid::Locale;
257/// # use std::rc::Rc;
258/// #
259/// # struct ExampleFormatter {
260/// # lang: Locale,
261/// # prefix: String,
262/// # }
263/// #
264/// # impl ExampleFormatter {
265/// # fn format(&self, example_string: &str) -> String {
266/// # format!(
267/// # "{} lang({}) string({})",
268/// # self.prefix, self.lang, example_string
269/// # )
270/// # }
271/// # }
272/// #
273/// # impl Memoizable for ExampleFormatter {
274/// # type Args = (String,);
275/// # type Error = ();
276/// # fn construct(lang: Locale, args: Self::Args) -> Result<Self, Self::Error> {
277/// # Ok(Self {
278/// # lang,
279/// # prefix: args.0,
280/// # })
281/// # }
282/// # }
283/// #
284/// let mut memoizer = IntlMemoizer::default();
285///
286/// // The memoziation happens per-locale.
287/// let en_us = "en-US".parse().expect("Failed to parse.");
288/// let en_us_memoizer: Rc<IntlLangMemoizer> = memoizer.get_for_lang(en_us);
289///
290/// // These arguments are passed into the constructor for `ExampleFormatter`. The
291/// // construct_args will be used for determining the memoization, but the message
292/// // can be different and re-use the constructed instance.
293/// let construct_args = (String::from("prefix:"),);
294/// let message = "The format operation will run";
295///
296/// // Use the `ExampleFormater` from the `IntlLangMemoizer` example. It returns a
297/// // string that demonstrates the configuration of the formatter. This step will
298/// // construct a new formatter if needed, and run the format operation.
299/// //
300/// // See `IntlLangMemoizer` for more details on this step.
301/// let en_us_result = en_us_memoizer
302/// .with_try_get::<ExampleFormatter, _, _>(construct_args.clone(), |intl_example| {
303/// intl_example.format(message)
304/// });
305///
306/// // The example formatter constructs a string with diagnostic information about
307/// // the configuration.
308/// assert_eq!(
309/// en_us_result.unwrap(),
310/// "prefix: lang(en-US) string(The format operation will run)"
311/// );
312///
313/// // The process can be repeated for a new locale.
314///
315/// let de_de = "de-DE".parse().expect("Failed to parse.");
316/// let de_de_memoizer: Rc<IntlLangMemoizer> = memoizer.get_for_lang(de_de);
317///
318/// let de_de_result = de_de_memoizer
319/// .with_try_get::<ExampleFormatter, _, _>(construct_args.clone(), |intl_example| {
320/// intl_example.format(message)
321/// });
322///
323/// assert_eq!(
324/// de_de_result.unwrap(),
325/// "prefix: lang(de-DE) string(The format operation will run)"
326/// );
327/// ```
328#[derive(Default)]
329pub struct IntlMemoizer {
330 map: HashMap<Locale, Weak<IntlLangMemoizer>>,
331}
332
333impl IntlMemoizer {
334 /// Get a [`IntlLangMemoizer`] for a given language. If one does not exist for
335 /// a locale, it will be constructed and weakly retained. See [`IntlLangMemoizer`]
336 /// for more detailed documentation how to use it.
337 pub fn get_for_lang(&mut self, lang: Locale) -> Rc<IntlLangMemoizer> {
338 match self.map.entry(lang.clone()) {
339 Entry::Vacant(empty) => {
340 let entry = Rc::new(IntlLangMemoizer::new(lang));
341 empty.insert(Rc::downgrade(&entry));
342 entry
343 }
344 Entry::Occupied(mut entry) => {
345 if let Some(entry) = entry.get().upgrade() {
346 entry
347 } else {
348 let e = Rc::new(IntlLangMemoizer::new(lang));
349 entry.insert(Rc::downgrade(&e));
350 e
351 }
352 }
353 }
354 }
355}
356//
357// #[cfg(test)]
358// mod tests {
359// use super::*;
360// use fluent_langneg::{negotiate_languages, NegotiationStrategy};
361// use intl_pluralrules::{PluralCategory, PluralRuleType, PluralRules as IntlPluralRules};
362// use std::{sync::Arc, thread};
363//
364// struct PluralRules(pub IntlPluralRules);
365//
366// impl PluralRules {
367// pub fn new(
368// lang: Locale,
369// pr_type: PluralRuleType,
370// ) -> Result<Self, &'static str> {
371// // let default_lang: Locale = "en".parse().unwrap();
372// // let pr_lang = negotiate_languages(
373// // &[lang],
374// // &IntlPluralRules::get_locales(pr_type),
375// // Some(&default_lang),
376// // NegotiationStrategy::Lookup,
377// // )[0]
378// // .clone();
379// //
380// // Ok(Self(IntlPluralRules::create(pr_lang, pr_type)?))
381//
382// todo!()
383// }
384// }
385//
386// impl Memoizable for PluralRules {
387// type Args = (PluralRuleType,);
388// type Error = &'static str;
389// fn construct(lang: Locale, args: Self::Args) -> Result<Self, Self::Error> {
390// Self::new(lang, args.0)
391// }
392// }
393//
394// #[test]
395// fn test_single_thread() {
396// let lang: Locale = "en".parse().unwrap();
397//
398// let mut memoizer = IntlMemoizer::default();
399// {
400// let en_memoizer = memoizer.get_for_lang(lang.clone());
401//
402// let result = en_memoizer
403// .with_try_get::<PluralRules, _, _>((PluralRuleType::CARDINAL,), |cb| cb.0.select(5))
404// .unwrap();
405// assert_eq!(result, Ok(PluralCategory::OTHER));
406// }
407//
408// {
409// let en_memoizer = memoizer.get_for_lang(lang);
410//
411// let result = en_memoizer
412// .with_try_get::<PluralRules, _, _>((PluralRuleType::CARDINAL,), |cb| cb.0.select(5))
413// .unwrap();
414// assert_eq!(result, Ok(PluralCategory::OTHER));
415// }
416// }
417//
418// #[test]
419// fn test_concurrent() {
420// let lang: Locale = "en".parse().unwrap();
421// let memoizer = Arc::new(concurrent::IntlLangMemoizer::new(lang));
422// let mut threads = vec![];
423//
424// // Spawn four threads that all use the PluralRules.
425// for _ in 0..4 {
426// let memoizer = Arc::clone(&memoizer);
427// threads.push(thread::spawn(move || {
428// memoizer
429// .with_try_get::<PluralRules, _, _>((PluralRuleType::CARDINAL,), |cb| {
430// cb.0.select(5)
431// })
432// .expect("Failed to get a PluralRules result.")
433// }));
434// }
435//
436// for thread in threads.drain(..) {
437// let result = thread.join().expect("Failed to join thread.");
438// assert_eq!(result, Ok(PluralCategory::OTHER));
439// }
440// }
441// }