fractal/
i18n.rs

1use gettextrs::{gettext, ngettext};
2
3use crate::utils::freplace;
4
5/// Like `gettext`, but replaces named variables with the given dictionary.
6///
7/// The expected format to replace is `{name}`, where `name` is the first string
8/// in the dictionary entry tuple.
9pub fn gettext_f(msgid: &str, args: &[(&str, &str)]) -> String {
10    let s = gettext(msgid);
11    freplace(&s, args).into_owned()
12}
13
14/// Like `ngettext`, but replaces named variables with the given dictionary.
15///
16/// The expected format to replace is `{name}`, where `name` is the first string
17/// in the dictionary entry tuple.
18pub fn ngettext_f(msgid: &str, msgid_plural: &str, n: u32, args: &[(&str, &str)]) -> String {
19    let s = ngettext(msgid, msgid_plural, n);
20    freplace(&s, args).into_owned()
21}
22
23#[cfg(test)]
24mod tests {
25    use super::*;
26
27    #[test]
28    fn test_gettext_f() {
29        let out = gettext_f("{one} param", &[("one", "one")]);
30        assert_eq!(out, "one param");
31
32        let out = gettext_f("middle {one} param", &[("one", "one")]);
33        assert_eq!(out, "middle one param");
34
35        let out = gettext_f("end {one}", &[("one", "one")]);
36        assert_eq!(out, "end one");
37
38        let out = gettext_f("multiple {one} and {two}", &[("one", "1"), ("two", "two")]);
39        assert_eq!(out, "multiple 1 and two");
40
41        let out = gettext_f("multiple {two} and {one}", &[("one", "1"), ("two", "two")]);
42        assert_eq!(out, "multiple two and 1");
43
44        let out = gettext_f("multiple {one} and {one}", &[("one", "1"), ("two", "two")]);
45        assert_eq!(out, "multiple 1 and 1");
46
47        let out = ngettext_f(
48            "singular {one} and {two}",
49            "plural {one} and {two}",
50            1,
51            &[("one", "1"), ("two", "two")],
52        );
53        assert_eq!(out, "singular 1 and two");
54        let out = ngettext_f(
55            "singular {one} and {two}",
56            "plural {one} and {two}",
57            2,
58            &[("one", "1"), ("two", "two")],
59        );
60        assert_eq!(out, "plural 1 and two");
61    }
62}