@@ -13,35 +13,44 @@ APIs such as `PluralRules`, DateTimeFormat` etc. between all `FluentBundle` inst
13
13
Usage
14
14
-----
15
15
16
+ The following is a high-level example of how this works, for running examples see
17
+ the [ docs] ( https://docs.rs/intl-memoizer/ )
18
+
16
19
``` rust
17
- use intl_memoizer :: {IntlMemoizer , Memoizable };
18
- use unic_langid :: langid;
20
+ /// Internationalization formatter should implement the Memoizable trait.
21
+ impl Memoizable for NumberFormat {
22
+ ...
23
+ }
19
24
20
- use intl_pluralrules :: {PluralRules , PluralRuleType , PluralCategory };
25
+ // The main memoizer has weak references to all of the per-language memoizers.
26
+ let mut memoizer = IntlMemoizer :: default ();
21
27
22
- impl Memoizable for PluralRules {
23
- type Args = (PluralRulesType ,);
24
- fn construct (lang : LanguageIdentifier , args : Self :: Args ) -> Self {
25
- Self :: new (lang , args . 0 )
26
- }
27
- }
28
+ // The formatter memoziation happens per-locale.
29
+ let lang = " en-US" . parse (). expect (" Failed to parse." );
30
+ let lang_memoizer : Rc <IntlLangMemoizer > = memoizer . get_for_lang (en_us );
28
31
29
- fn main () {
30
- let lang = langid! (" en-US" );
32
+ // Run the formatter
31
33
32
- // A single memoizer for all languages
33
- let mut memoizer = IntlMemoizer :: new ();
34
+ let options : NumberFormatOptions {
35
+ minimum_fraction_digits : 3 ,
36
+ maximum_fraction_digits : 5 ,
37
+ };
34
38
35
- // A RefCell for a particular language to be used in all `FluentBundle`
36
- // instances.
37
- let mut en_us_memoizer = memoizer . get_for_lang (lang . clone ());
39
+ // Format pi with the options. This will lazily construct the NumberFormat.
40
+ let pi = lang_memoizer
41
+ . with_try_get :: <NumberFormat , _ , _ >((options ,), | nf | nf . format (3.141592653 ))
42
+ . unwrap ()
38
43
39
- // Per-call borrow
40
- let mut en_us_memoizer_borrow = en_us_memoizer . borrow_mut ();
41
- let cb = en_us_memoizer_borrow . get :: <PluralRules >((PluralRulesType :: Cardinal ,));
42
- assert_eq! (cb . select (1 ), PluralCategory :: One );
43
- }
44
+ // The example formatter constructs a string with diagnostic information about
45
+ // the configuration.
46
+ assert_eq! (text , " 3.14159" );
47
+
48
+ // Running it again will use the previous formatter.
49
+ let two = lang_memoizer
50
+ . with_try_get :: <NumberFormat , _ , _ >((options ,), | nf | nf . format (2.0 ))
51
+ . unwrap ()
44
52
53
+ assert_eq! (text , " 2.000" );
45
54
```
46
55
47
56
Get Involved
0 commit comments