2 use std::iter::FromIterator;
4 use crate::types::FluentValue;
6 /// A map of arguments passed from the code to
7 /// the localization to be used for message
13 /// use fluent_bundle::{FluentArgs, FluentBundle, FluentResource};
15 /// let mut args = FluentArgs::new();
16 /// args.set("user", "John");
17 /// args.set("emailCount", 5);
19 /// let res = FluentResource::try_new(r#"
21 /// msg-key = Hello, { $user }. You have { $emailCount } messages.
24 /// .expect("Failed to parse FTL.");
26 /// let mut bundle = FluentBundle::default();
28 /// // For this example, we'll turn on BiDi support.
29 /// // Please, be careful when doing it, it's a risky move.
30 /// bundle.set_use_isolating(false);
32 /// bundle.add_resource(res)
33 /// .expect("Failed to add a resource.");
35 /// let mut err = vec![];
37 /// let msg = bundle.get_message("msg-key")
38 /// .expect("Failed to retrieve a message.");
39 /// let value = msg.value()
40 /// .expect("Failed to retrieve a value.");
43 /// bundle.format_pattern(value, Some(&args), &mut err),
44 /// "Hello, John. You have 5 messages."
47 #[derive(Debug, Default)]
48 pub struct FluentArgs<'args>(Vec<(Cow<'args, str>, FluentValue<'args>)>);
50 impl<'args> FluentArgs<'args> {
51 pub fn new() -> Self {
55 pub fn with_capacity(capacity: usize) -> Self {
56 Self(Vec::with_capacity(capacity))
59 pub fn get<K>(&self, key: K) -> Option<&FluentValue<'args>>
61 K: Into<Cow<'args, str>>,
64 if let Ok(idx) = self.0.binary_search_by_key(&&key, |(k, _)| k) {
71 pub fn set<K, V>(&mut self, key: K, value: V)
73 K: Into<Cow<'args, str>>,
74 V: Into<FluentValue<'args>>,
77 let idx = match self.0.binary_search_by_key(&&key, |(k, _)| k) {
81 self.0.insert(idx, (key, value.into()));
84 pub fn iter(&self) -> impl Iterator<Item = (&str, &FluentValue)> {
85 self.0.iter().map(|(k, v)| (k.as_ref(), v))
89 impl<'args, K, V> FromIterator<(K, V)> for FluentArgs<'args>
91 K: Into<Cow<'args, str>>,
92 V: Into<FluentValue<'args>>,
94 fn from_iter<I>(iter: I) -> Self
96 I: IntoIterator<Item = (K, V)>,
98 let iter = iter.into_iter();
99 let mut args = if let Some(size) = iter.size_hint().1 {
100 FluentArgs::with_capacity(size)
113 impl<'args> IntoIterator for FluentArgs<'args> {
114 type Item = (Cow<'args, str>, FluentValue<'args>);
115 type IntoIter = std::vec::IntoIter<Self::Item>;
117 fn into_iter(self) -> Self::IntoIter {