intl-memoizer-0.5.3/.cargo_vcs_info.json0000644000000001530000000000100136330ustar { "git": { "sha1": "f22da4ea48328b4c617b7666c482634c49fbe0a7" }, "path_in_vcs": "intl-memoizer" }intl-memoizer-0.5.3/Cargo.lock0000644000000065200000000000100116120ustar # This file is automatically @generated by Cargo. # It is not intended for manual editing. version = 3 [[package]] name = "displaydoc" version = "0.2.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "97369cbbc041bc366949bc74d34658d6cda5621039731c6310521892a3a20ae0" dependencies = [ "proc-macro2", "quote", "syn", ] [[package]] name = "fluent-langneg" version = "0.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c4ad0989667548f06ccd0e306ed56b61bd4d35458d54df5ec7587c0e8ed5e94" dependencies = [ "unic-langid", ] [[package]] name = "intl-memoizer" version = "0.5.3" dependencies = [ "fluent-langneg", "intl_pluralrules", "type-map", "unic-langid", ] [[package]] name = "intl_pluralrules" version = "7.0.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "078ea7b7c29a2b4df841a7f6ac8775ff6074020c6776d48491ce2268e068f972" dependencies = [ "unic-langid", ] [[package]] name = "proc-macro2" version = "1.0.95" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "02b3e5e68a3a1a02aad3ec490a98007cbc13c37cbe84a3cd7b8e406d76e7f778" dependencies = [ "unicode-ident", ] [[package]] name = "quote" version = "1.0.40" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1885c039570dc00dcb4ff087a89e185fd56bae234ddc7f056a945bf36467248d" dependencies = [ "proc-macro2", ] [[package]] name = "rustc-hash" version = "2.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" [[package]] name = "syn" version = "2.0.101" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ce2b7fc941b3a24138a0a7cf8e858bfc6a992e7978a068a5c760deb0ed43caf" dependencies = [ "proc-macro2", "quote", "unicode-ident", ] [[package]] name = "tinystr" version = "0.8.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d4f6d1145dcb577acf783d4e601bc1d76a13337bb54e6233add580b07344c8b" dependencies = [ "displaydoc", "zerovec", ] [[package]] name = "type-map" version = "0.5.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cb30dbbd9036155e74adad6812e9898d03ec374946234fbcebd5dfc7b9187b90" dependencies = [ "rustc-hash", ] [[package]] name = "unic-langid" version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a28ba52c9b05311f4f6e62d5d9d46f094bd6e84cb8df7b3ef952748d752a7d05" dependencies = [ "unic-langid-impl", ] [[package]] name = "unic-langid-impl" version = "0.9.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dce1bf08044d4b7a94028c93786f8566047edc11110595914de93362559bc658" dependencies = [ "tinystr", ] [[package]] name = "unicode-ident" version = "1.0.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5a5f39404a5da50712a4c1eecf25e90dd62b613502b7e925fd4e4d19b5c96512" [[package]] name = "zerofrom" version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "91ec111ce797d0e0784a1116d0ddcdbea84322cd79e5d5ad173daeba4f93ab55" [[package]] name = "zerovec" version = "0.11.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4a05eb080e015ba39cc9e23bbe5e7fb04d5fb040350f99f34e338d5fdd294428" dependencies = [ "zerofrom", ] intl-memoizer-0.5.3/Cargo.toml0000644000000033430000000000100116350ustar # THIS FILE IS AUTOMATICALLY GENERATED BY CARGO # # When uploading crates to the registry Cargo will automatically # "normalize" Cargo.toml files for maximal compatibility # with all versions of Cargo and also rewrite `path` dependencies # to registry (e.g., crates.io) dependencies. # # If you are reading this file be aware that the original Cargo.toml # will likely look very different (and much more reasonable). # See Cargo.toml.orig for the original contents. [package] edition = "2021" rust-version = "1.67.0" name = "intl-memoizer" version = "0.5.3" authors = [ "Caleb Maclennan ", "Bruce Mitchener ", "Staś Małolepszy ", ] build = false include = [ "src/**/*", "benches/*.rs", "Cargo.toml", "README.md", "LICENSE-APACHE", "LICENSE-MIT", ] autolib = false autobins = false autoexamples = false autotests = false autobenches = false description = """ A memoizer specifically tailored for storing lazy-initialized intl formatters for Project Fluent, a localization system designed to unleash the entire expressive power of natural language translations. """ homepage = "https://www.projectfluent.org" readme = "README.md" keywords = [ "localization", "l10n", "i18n", "intl", "internationalization", ] categories = [ "localization", "internationalization", ] license = "Apache-2.0 OR MIT" repository = "https://github.com/projectfluent/fluent-rs" [lib] name = "intl_memoizer" path = "src/lib.rs" [dependencies.type-map] version = "0.5" [dependencies.unic-langid] version = "0.9" [dev-dependencies.fluent-langneg] version = "0.13" [dev-dependencies.intl_pluralrules] version = "7.0" intl-memoizer-0.5.3/Cargo.toml.orig000064400000000000000000000014031046102023000153110ustar 00000000000000[package] name = "intl-memoizer" description = """ A memoizer specifically tailored for storing lazy-initialized intl formatters for Project Fluent, a localization system designed to unleash the entire expressive power of natural language translations. """ version = "0.5.3" edition.workspace = true rust-version.workspace = true homepage.workspace = true repository.workspace = true license.workspace = true authors.workspace = true categories.workspace = true keywords.workspace = true readme = "README.md" include = [ "src/**/*", "benches/*.rs", "Cargo.toml", "README.md", "LICENSE-APACHE", "LICENSE-MIT", ] [dependencies] unic-langid.workspace = true type-map = "0.5" [dev-dependencies] intl_pluralrules.workspace = true fluent-langneg.workspace = true intl-memoizer-0.5.3/LICENSE-APACHE000064400000000000000000000261111046102023000143510ustar 00000000000000 Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: (a) You must give any other recipients of the Work or Derivative Works a copy of this License; and (b) You must cause any modified files to carry prominent notices stating that You changed the files; and (c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and (d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work. To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2017 Mozilla Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. intl-memoizer-0.5.3/LICENSE-MIT000064400000000000000000000020271046102023000140610ustar 00000000000000Copyright 2017 Mozilla Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. intl-memoizer-0.5.3/README.md000064400000000000000000000061351046102023000137100ustar 00000000000000# IntlMemoizer [![crates.io](https://img.shields.io/crates/v/intl-memoizer.svg)](https://crates.io/crates/intl-memoizer) [![docs.rs](https://img.shields.io/docsrs/intl-memoizer)](https://docs.rs/intl-memoizer) [![Build](https://github.com/projectfluent/fluent-rs/actions/workflows/test.yaml/badge.svg)](https://github.com/projectfluent/fluent-rs/actions/workflows/test.yaml) [![Coverage Status](https://coveralls.io/repos/github/projectfluent/fluent-rs/badge.svg?branch=main)](https://coveralls.io/github/projectfluent/fluent-rs?branch=main) The `fluent-rs` workspace is a collection of Rust crates implementing [Project Fluent][], a localization system designed to unleash the entire expressive power of natural language translations. This crate is a memoizer specifically tailored for storing lazy-initialized intl formatters. [Project Fluent]: https://projectfluent.org Usage ----- The assumption is that allocating a new formatter instance is costly, and such instance is read-only during its life time, with constructor being expensive, and `format`/`select` calls being cheap. In result it pays off to use a singleton to manage memoization of all instances of intl APIs such as `PluralRules`, `DateTimeFormat` etc. between all `FluentBundle` instances. The following is a high-level example of how this works, for running examples see the [docs](https://docs.rs/intl-memoizer/) ```rust /// Internationalization formatter should implement the Memoizable trait. impl Memoizable for NumberFormat { ... } // The main memoizer has weak references to all of the per-language memoizers. let mut memoizer = IntlMemoizer::default(); // The formatter memoziation happens per-locale. let lang = "en-US".parse().expect("Failed to parse."); let lang_memoizer: Rc = memoizer.get_for_lang(en_us); // Run the formatter let options: NumberFormatOptions { minimum_fraction_digits: 3, maximum_fraction_digits: 5, }; // Format pi with the options. This will lazily construct the NumberFormat. let pi = lang_memoizer .with_try_get::((options,), |nf| nf.format(3.141592653)) .unwrap() // The example formatter constructs a string with diagnostic information about // the configuration. assert_eq!(text, "3.14159"); // Running it again will use the previous formatter. let two = lang_memoizer .with_try_get::((options,), |nf| nf.format(2.0)) .unwrap() assert_eq!(text, "2.000"); ``` Get Involved ------------ `fluent-rs` is open-source, licensed under both the Apache 2.0 and MIT licenses. We encourage everyone to take a look at our code and we'll listen to your feedback. Discuss ------- We'd love to hear your thoughts on Project Fluent! Whether you're a localizer looking for a better way to express yourself in your language, or a developer trying to make your app localizable and multilingual, or a hacker looking for a project to contribute to, please do get in touch on the mailing list and the IRC channel. - Discourse: https://discourse.mozilla.org/c/fluent - Matrix channel: #fluent:mozilla.org intl-memoizer-0.5.3/src/concurrent.rs000064400000000000000000000027411046102023000157470ustar 00000000000000//! Contains thread-safe variants. use super::*; use std::sync::Mutex; /// A thread-safe version of the [`intl_memoizer::IntlLangMemoizer`](super::IntlLangMemoizer). /// See the single-thread version for more documentation. #[derive(Debug)] pub struct IntlLangMemoizer { lang: LanguageIdentifier, map: Mutex, } impl IntlLangMemoizer { /// Create a new [`IntlLangMemoizer`] that is unique to a specific [`LanguageIdentifier`] pub fn new(lang: LanguageIdentifier) -> Self { Self { lang, map: Mutex::new(type_map::concurrent::TypeMap::new()), } } /// Lazily initialize and run a formatter. See /// [`intl_memoizer::IntlLangMemoizer::with_try_get`](crate::IntlLangMemoizer::with_try_get) /// for documentation. pub fn with_try_get(&self, args: I::Args, cb: U) -> Result where Self: Sized, I: Memoizable + Sync + Send + 'static, I::Args: Send + Sync + 'static, U: FnOnce(&I) -> R, { let mut map = self.map.lock().unwrap(); let cache = map .entry::>() .or_insert_with(HashMap::new); let e = match cache.entry(args.clone()) { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => { let val = I::construct(self.lang.clone(), args)?; entry.insert(val) } }; Ok(cb(e)) } } intl-memoizer-0.5.3/src/lib.rs000064400000000000000000000364631046102023000143430ustar 00000000000000//! This crate contains a memoizer for internationalization formatters. Often it is //! expensive (in terms of performance and memory) to construct a formatter, but then //! relatively cheap to run the format operation. //! //! The [`IntlMemoizer`] is the main struct that creates a per-locale [`IntlLangMemoizer`]. use std::cell::RefCell; use std::collections::hash_map::Entry; use std::collections::HashMap; use std::hash::Hash; use std::rc::{Rc, Weak}; use unic_langid::LanguageIdentifier; pub mod concurrent; /// The trait that needs to be implemented for each intl formatter that needs to be /// memoized. pub trait Memoizable { /// Type of the arguments that are used to construct the formatter. type Args: 'static + Eq + Hash + Clone; /// Type of any errors that can occur during the construction process. type Error; /// Construct a formatter. This maps the [`Self::Args`] type to the actual constructor /// for an intl formatter. fn construct(lang: LanguageIdentifier, args: Self::Args) -> Result where Self: std::marker::Sized; } /// The [`IntlLangMemoizer`] can memoize multiple constructed internationalization /// formatters, and their configuration for a single locale. For instance, given "en-US", /// a memorizer could retain 3 `DateTimeFormat` instances, and a `PluralRules`. /// /// For memoizing with multiple locales, see [`IntlMemoizer`]. /// /// # Example /// /// The code example does the following steps: /// /// 1. Create a static counter /// 2. Create an `ExampleFormatter` /// 3. Implement [`Memoizable`] for `ExampleFormatter`. /// 4. Use `IntlLangMemoizer::with_try_get` to run `ExampleFormatter::format` /// 5. Demonstrate the memoization using the static counter /// /// ``` /// use intl_memoizer::{IntlLangMemoizer, Memoizable}; /// use unic_langid::LanguageIdentifier; /// /// // Create a static counter so that we can demonstrate the side effects of when /// // the memoizer re-constructs an API. /// /// static mut INTL_EXAMPLE_CONSTRUCTS: u32 = 0; /// fn increment_constructs() { /// unsafe { /// INTL_EXAMPLE_CONSTRUCTS += 1; /// } /// } /// /// fn get_constructs_count() -> u32 { /// unsafe { INTL_EXAMPLE_CONSTRUCTS } /// } /// /// /// Create an example formatter, that doesn't really do anything useful. In a real /// /// implementation, this could be a PluralRules or DateTimeFormat struct. /// struct ExampleFormatter { /// lang: LanguageIdentifier, /// /// This is here to show how to initiate the API with an argument. /// prefix: String, /// } /// /// impl ExampleFormatter { /// /// Perform an example format by printing information about the formatter /// /// configuration, and the arguments passed into the individual format operation. /// fn format(&self, example_string: &str) -> String { /// format!( /// "{} lang({}) string({})", /// self.prefix, self.lang, example_string /// ) /// } /// } /// /// /// Multiple classes of structs may be add1ed to the memoizer, with the restriction /// /// that they must implement the `Memoizable` trait. /// impl Memoizable for ExampleFormatter { /// /// The arguments will be passed into the constructor. Here a single `String` /// /// will be used as a prefix to the formatting operation. /// type Args = (String,); /// /// /// If the constructor is fallible, than errors can be described here. /// type Error = (); /// /// /// This function wires together the `Args` and `Error` type to construct /// /// the intl API. In our example, there is /// fn construct(lang: LanguageIdentifier, args: Self::Args) -> Result { /// // Keep track for example purposes that this was constructed. /// increment_constructs(); /// /// Ok(Self { /// lang, /// prefix: args.0, /// }) /// } /// } /// /// // The following demonstrates how these structs are actually used with the memoizer. /// /// // Construct a new memoizer. /// let lang = "en-US".parse().expect("Failed to parse."); /// let memoizer = IntlLangMemoizer::new(lang); /// /// // These arguments are passed into the constructor for `ExampleFormatter`. /// let construct_args = (String::from("prefix:"),); /// let message1 = "The format operation will run"; /// let message2 = "ExampleFormatter will be re-used, when a second format is run"; /// /// // Run `IntlLangMemoizer::with_try_get`. The name of the method means "with" an /// // intl formatter, "try and get" the result. See the method documentation for /// // more details. /// /// let result1 = memoizer /// .with_try_get::(construct_args.clone(), |intl_example| { /// intl_example.format(message1) /// }); /// /// // The memoized instance of `ExampleFormatter` will be re-used. /// let result2 = memoizer /// .with_try_get::(construct_args.clone(), |intl_example| { /// intl_example.format(message2) /// }); /// /// assert_eq!( /// result1.unwrap(), /// "prefix: lang(en-US) string(The format operation will run)" /// ); /// assert_eq!( /// result2.unwrap(), /// "prefix: lang(en-US) string(ExampleFormatter will be re-used, when a second format is run)" /// ); /// assert_eq!( /// get_constructs_count(), /// 1, /// "The constructor was only run once." /// ); /// /// let construct_args = (String::from("re-init:"),); /// /// // Since the constructor args changed, `ExampleFormatter` will be re-constructed. /// let result1 = memoizer /// .with_try_get::(construct_args.clone(), |intl_example| { /// intl_example.format(message1) /// }); /// /// // The memoized instance of `ExampleFormatter` will be re-used. /// let result2 = memoizer /// .with_try_get::(construct_args.clone(), |intl_example| { /// intl_example.format(message2) /// }); /// /// assert_eq!( /// result1.unwrap(), /// "re-init: lang(en-US) string(The format operation will run)" /// ); /// assert_eq!( /// result2.unwrap(), /// "re-init: lang(en-US) string(ExampleFormatter will be re-used, when a second format is run)" /// ); /// assert_eq!( /// get_constructs_count(), /// 2, /// "The constructor was invalidated and ran again." /// ); /// ``` #[derive(Debug)] pub struct IntlLangMemoizer { lang: LanguageIdentifier, map: RefCell, } impl IntlLangMemoizer { /// Create a new [`IntlLangMemoizer`] that is unique to a specific /// [`LanguageIdentifier`] pub fn new(lang: LanguageIdentifier) -> Self { Self { lang, map: RefCell::new(type_map::TypeMap::new()), } } /// `with_try_get` means `with` an internationalization formatter, `try` and `get` a result. /// The (potentially expensive) constructor for the formatter (such as `PluralRules` or /// `DateTimeFormat`) will be memoized and only constructed once for a given /// `construct_args`. After that the format operation can be run multiple times /// inexpensively. /// /// The first generic argument `I` must be provided, but the `R` and `U` will be /// deduced by the typing of the `callback` argument that is provided. /// /// I - The memoizable intl object, for instance a `PluralRules` instance. This /// must implement the Memoizable trait. /// /// R - The return result from the callback `U`. /// /// U - The callback function. Takes an instance of `I` as the first parameter and /// returns the R value. pub fn with_try_get(&self, construct_args: I::Args, callback: U) -> Result where Self: Sized, I: Memoizable + 'static, U: FnOnce(&I) -> R, { let mut map = self .map .try_borrow_mut() .expect("Cannot use memoizer reentrantly"); let cache = map .entry::>() .or_insert_with(HashMap::new); let e = match cache.entry(construct_args.clone()) { Entry::Occupied(entry) => entry.into_mut(), Entry::Vacant(entry) => { let val = I::construct(self.lang.clone(), construct_args)?; entry.insert(val) } }; Ok(callback(e)) } } /// [`IntlMemoizer`] is designed to handle lazily-initialized references to /// internationalization formatters. /// /// Constructing a new formatter is often expensive in terms of memory and performance, /// and the instance is often read-only during its lifetime. The format operations in /// comparison are relatively cheap. /// /// Because of this relationship, it can be helpful to memoize the constructors, and /// re-use them across multiple format operations. This strategy is used where all /// instances of intl APIs such as `PluralRules`, `DateTimeFormat` etc. are memoized /// between all `FluentBundle` instances. /// /// # Example /// /// For a more complete example of the memoization, see the [`IntlLangMemoizer`] documentation. /// This example provides a higher-level overview. /// /// ``` /// # use intl_memoizer::{IntlMemoizer, IntlLangMemoizer, Memoizable}; /// # use unic_langid::LanguageIdentifier; /// # use std::rc::Rc; /// # /// # struct ExampleFormatter { /// # lang: LanguageIdentifier, /// # prefix: String, /// # } /// # /// # impl ExampleFormatter { /// # fn format(&self, example_string: &str) -> String { /// # format!( /// # "{} lang({}) string({})", /// # self.prefix, self.lang, example_string /// # ) /// # } /// # } /// # /// # impl Memoizable for ExampleFormatter { /// # type Args = (String,); /// # type Error = (); /// # fn construct(lang: LanguageIdentifier, args: Self::Args) -> Result { /// # Ok(Self { /// # lang, /// # prefix: args.0, /// # }) /// # } /// # } /// # /// let mut memoizer = IntlMemoizer::default(); /// /// // The memoziation happens per-locale. /// let en_us = "en-US".parse().expect("Failed to parse."); /// let en_us_memoizer: Rc = memoizer.get_for_lang(en_us); /// /// // These arguments are passed into the constructor for `ExampleFormatter`. The /// // construct_args will be used for determining the memoization, but the message /// // can be different and re-use the constructed instance. /// let construct_args = (String::from("prefix:"),); /// let message = "The format operation will run"; /// /// // Use the `ExampleFormatter` from the `IntlLangMemoizer` example. It returns a /// // string that demonstrates the configuration of the formatter. This step will /// // construct a new formatter if needed, and run the format operation. /// // /// // See `IntlLangMemoizer` for more details on this step. /// let en_us_result = en_us_memoizer /// .with_try_get::(construct_args.clone(), |intl_example| { /// intl_example.format(message) /// }); /// /// // The example formatter constructs a string with diagnostic information about /// // the configuration. /// assert_eq!( /// en_us_result.unwrap(), /// "prefix: lang(en-US) string(The format operation will run)" /// ); /// /// // The process can be repeated for a new locale. /// /// let de_de = "de-DE".parse().expect("Failed to parse."); /// let de_de_memoizer: Rc = memoizer.get_for_lang(de_de); /// /// let de_de_result = de_de_memoizer /// .with_try_get::(construct_args.clone(), |intl_example| { /// intl_example.format(message) /// }); /// /// assert_eq!( /// de_de_result.unwrap(), /// "prefix: lang(de-DE) string(The format operation will run)" /// ); /// ``` #[derive(Default)] pub struct IntlMemoizer { map: HashMap>, } impl IntlMemoizer { /// Get a [`IntlLangMemoizer`] for a given language. If one does not exist for /// a locale, it will be constructed and weakly retained. See [`IntlLangMemoizer`] /// for more detailed documentation how to use it. pub fn get_for_lang(&mut self, lang: LanguageIdentifier) -> Rc { match self.map.entry(lang.clone()) { Entry::Vacant(empty) => { let entry = Rc::new(IntlLangMemoizer::new(lang)); empty.insert(Rc::downgrade(&entry)); entry } Entry::Occupied(mut entry) => { if let Some(entry) = entry.get().upgrade() { entry } else { let e = Rc::new(IntlLangMemoizer::new(lang)); entry.insert(Rc::downgrade(&e)); e } } } } } #[cfg(test)] mod tests { use super::*; use fluent_langneg::{negotiate_languages, NegotiationStrategy}; use intl_pluralrules::{PluralCategory, PluralRuleType, PluralRules as IntlPluralRules}; use std::{sync::Arc, thread}; struct PluralRules(pub IntlPluralRules); impl PluralRules { pub fn new( lang: LanguageIdentifier, pr_type: PluralRuleType, ) -> Result { let default_lang: LanguageIdentifier = "en".parse().unwrap(); let pr_lang = negotiate_languages( &[lang], &IntlPluralRules::get_locales(pr_type), Some(&default_lang), NegotiationStrategy::Lookup, )[0] .clone(); Ok(Self(IntlPluralRules::create(pr_lang, pr_type)?)) } } impl Memoizable for PluralRules { type Args = (PluralRuleType,); type Error = &'static str; fn construct(lang: LanguageIdentifier, args: Self::Args) -> Result { Self::new(lang, args.0) } } #[test] fn test_single_thread() { let lang: LanguageIdentifier = "en".parse().unwrap(); let mut memoizer = IntlMemoizer::default(); { let en_memoizer = memoizer.get_for_lang(lang.clone()); let result = en_memoizer .with_try_get::((PluralRuleType::CARDINAL,), |cb| cb.0.select(5)) .unwrap(); assert_eq!(result, Ok(PluralCategory::OTHER)); } { let en_memoizer = memoizer.get_for_lang(lang); let result = en_memoizer .with_try_get::((PluralRuleType::CARDINAL,), |cb| cb.0.select(5)) .unwrap(); assert_eq!(result, Ok(PluralCategory::OTHER)); } } #[test] fn test_concurrent() { let lang: LanguageIdentifier = "en".parse().unwrap(); let memoizer = Arc::new(concurrent::IntlLangMemoizer::new(lang)); let mut threads = vec![]; // Spawn four threads that all use the PluralRules. for _ in 0..4 { let memoizer = Arc::clone(&memoizer); threads.push(thread::spawn(move || { memoizer .with_try_get::((PluralRuleType::CARDINAL,), |cb| { cb.0.select(5) }) .expect("Failed to get a PluralRules result.") })); } for thread in threads.drain(..) { let result = thread.join().expect("Failed to join thread."); assert_eq!(result, Ok(PluralCategory::OTHER)); } } }