glib/
variant_dict.rs

1// Take a look at the license at the top of the repository in the LICENSE file.
2
3use std::borrow::Cow;
4
5use crate::{ffi, translate::*, variant::*, variant_type::*};
6
7wrapper! {
8    // rustdoc-stripper-ignore-next
9    /// `VariantDict` is a mutable key/value store where the keys are always
10    /// strings and the values are [`Variant`s](variant/struct.Variant.html).
11    ///
12    /// Variant dictionaries can easily be converted to/from `Variant`s of the
13    /// appropriate type.  In `glib` terms, this is a variant of the form `"a{sv}"`.
14    ///
15    /// # Panics
16    ///
17    /// Note, pretty much all methods on this struct will panic if the
18    /// [`end_unsafe()`](#method.end_unsafe) method was called on the instance.
19    #[doc(alias = "GVariantDict")]
20    pub struct VariantDict(Shared<ffi::GVariantDict>);
21
22    match fn {
23        ref => |ptr| ffi::g_variant_dict_ref(ptr),
24        unref => |ptr| ffi::g_variant_dict_unref(ptr),
25        type_ => || ffi::g_variant_dict_get_type(),
26    }
27}
28
29impl VariantDict {
30    // rustdoc-stripper-ignore-next
31    /// Create a new `VariantDict` optionally populating it with the given `Variant`
32    ///
33    /// Since `Variant`s are immutable, this does not couple the `VariantDict` with
34    /// the input `Variant`, instead the contents are copied into the `VariantDict`.
35    ///
36    /// # Panics
37    ///
38    /// This function will panic if the given `Variant` is not of the correct type.
39    #[doc(alias = "g_variant_dict_new")]
40    pub fn new(from_asv: Option<&Variant>) -> Self {
41        if let Some(var) = from_asv {
42            assert_eq!(var.type_(), VariantDict::static_variant_type());
43        }
44        unsafe { from_glib_full(ffi::g_variant_dict_new(from_asv.to_glib_none().0)) }
45    }
46
47    // rustdoc-stripper-ignore-next
48    /// Check if this `VariantDict` contains the given key.
49    ///
50    /// Look up whether or not the given key is present, returning `true` if it
51    /// is present in `self`.
52    #[doc(alias = "g_variant_dict_contains")]
53    pub fn contains(&self, key: &str) -> bool {
54        unsafe {
55            from_glib(ffi::g_variant_dict_contains(
56                self.to_glib_none().0,
57                key.to_glib_none().0,
58            ))
59        }
60    }
61
62    // rustdoc-stripper-ignore-next
63    /// Look up a typed value from this `VariantDict`.
64    ///
65    /// The given `key` is looked up in `self`.
66    ///
67    /// This will return `None` if the `key` is not present in the dictionary,
68    /// and an error if the key is present but with the wrong type.
69    #[doc(alias = "g_variant_dict_lookup")]
70    pub fn lookup<T: FromVariant>(&self, key: &str) -> Result<Option<T>, VariantTypeMismatchError> {
71        self.lookup_value(key, None)
72            .map(|v| Variant::try_get(&v))
73            .transpose()
74    }
75
76    // rustdoc-stripper-ignore-next
77    /// Look up and return a value from this `VariantDict`.
78    ///
79    /// The given `key` is looked up in `self`.  If `expected_type` is not
80    /// `None` then it will be matched against the type of any found value.
81    ///
82    /// This will return `None` if the `key` is not present in the dictionary
83    /// or if it is present but the type of the value does not match a given
84    /// `expected_type`.  Otherwise, `Some(value)` will be returned where
85    /// the `value` is an instance of [`Variant`](variant/struct.Variant.html).
86    #[doc(alias = "g_variant_dict_lookup_value")]
87    pub fn lookup_value(&self, key: &str, expected_type: Option<&VariantTy>) -> Option<Variant> {
88        unsafe {
89            from_glib_full(ffi::g_variant_dict_lookup_value(
90                self.to_glib_none().0,
91                key.to_glib_none().0,
92                expected_type.to_glib_none().0,
93            ))
94        }
95    }
96
97    // rustdoc-stripper-ignore-next
98    /// Insert a variant into the dictionary.
99    ///
100    /// The given `key`/`value` pair is inserted into `self`.  If a value
101    /// was previously associated with `key` then it is overwritten.
102    ///
103    /// For convenience, you may use the [`insert()`](#method.insert) if
104    /// you have a value which implements [`ToVariant`](variant/trait.ToVariant.html).
105    #[doc(alias = "g_variant_dict_insert_value")]
106    pub fn insert_value(&self, key: &str, value: &Variant) {
107        unsafe {
108            ffi::g_variant_dict_insert_value(
109                self.to_glib_none().0,
110                key.to_glib_none().0,
111                value.to_glib_none().0,
112            )
113        }
114    }
115
116    // rustdoc-stripper-ignore-next
117    /// Insert a value into the dictionary
118    ///
119    /// The given `key`/`value` pair is inserted into `self`.  If a value
120    /// was previously associated with `key` then it is overwritten.
121    ///
122    /// This is a convenience method which automatically calls
123    /// [`to_variant()`](variant/trait.ToVariant.html#method.to_variant) for you
124    /// on the given value.
125    ///
126    /// If, on the other hand, you have a [`Variant`](variant/struct.Variant.html)
127    /// instance already, you should use the [`insert_value()`](#method.insert_value)
128    /// method instead.
129    #[doc(alias = "g_variant_dict_insert_value")]
130    pub fn insert(&self, key: &str, value: impl Into<Variant>) {
131        unsafe {
132            ffi::g_variant_dict_insert_value(
133                self.to_glib_none().0,
134                key.to_glib_none().0,
135                value.into().to_glib_none().0,
136            )
137        }
138    }
139
140    // rustdoc-stripper-ignore-next
141    /// Remove the given `key` from the dictionary.
142    ///
143    /// This removes the given `key` from the dictionary, releasing the reference
144    /// on the associated value if one is present.
145    ///
146    /// If a `key`/`value` pair was removed from the dictionary, `true` is
147    /// returned.  If `key` was not present then `false` is returned instead.
148    #[doc(alias = "g_variant_dict_remove")]
149    pub fn remove(&self, key: &str) -> bool {
150        unsafe {
151            from_glib(ffi::g_variant_dict_remove(
152                self.to_glib_none().0,
153                key.to_glib_none().0,
154            ))
155        }
156    }
157
158    // rustdoc-stripper-ignore-next
159    /// Convert this dictionary to a [`Variant`](variant/struct.Variant.html)
160    ///
161    /// This method converts `self` into an instance of [`Variant`](variant/struct.Variant.html)
162    /// but in doing so renders it very unsafe to use.
163    ///
164    /// # Safety
165    ///
166    /// After calling this, the underlying `GVariantDict` is in a state where
167    /// the only valid operations to perform as reference ones.  As such
168    /// any attempt to read/update the dictionary *will* fail and emit warnings
169    /// of such.
170    ///
171    /// You should only use this function if the extra cost of the safe function
172    /// is too much for your performance critical codepaths
173    pub unsafe fn end_unsafe(&self) -> Variant {
174        from_glib_none(ffi::g_variant_dict_end(self.to_glib_none().0))
175    }
176
177    // rustdoc-stripper-ignore-next
178    /// Convert this dictionary to a [`Variant`](variant/struct.Variant.html)
179    ///
180    /// This method converts `self` into an instance of [`Variant`](variant/struct.Variant.html)
181    /// and then reinitialises itself in order to be safe for further use.
182    ///
183    /// If you are certain that nothing other than disposing of references will
184    /// be done after ending the instance, you can call the
185    /// [`end_unsafe()`](#method.end_unsafe) method instead to avoid the unnecessary
186    /// reinitialisation of the dictionary.
187    pub fn end(&self) -> Variant {
188        unsafe {
189            let ret = self.end_unsafe();
190            // Reinitialise the dict so that we can continue safely
191            ffi::g_variant_dict_init(self.to_glib_none().0, None::<Variant>.to_glib_none().0);
192            ret
193        }
194    }
195}
196
197impl Default for VariantDict {
198    fn default() -> Self {
199        Self::new(None)
200    }
201}
202
203impl StaticVariantType for VariantDict {
204    fn static_variant_type() -> Cow<'static, VariantTy> {
205        Cow::Borrowed(VariantTy::VARDICT)
206    }
207}
208
209impl ToVariant for VariantDict {
210    fn to_variant(&self) -> Variant {
211        self.end()
212    }
213}
214
215impl From<VariantDict> for Variant {
216    // rustdoc-stripper-ignore-next
217    /// Consume a given `VariantDict` and call [`VariantDict::end`] on it.
218    ///
219    /// Note: While this method consumes the `VariantDict`, the underlying
220    /// object could still be accessed through other clones because of the
221    /// reference counted clone semantics.
222    #[inline]
223    fn from(d: VariantDict) -> Self {
224        d.end()
225    }
226}
227
228impl FromVariant for VariantDict {
229    fn from_variant(variant: &Variant) -> Option<Self> {
230        if variant.type_() == VariantDict::static_variant_type() {
231            Some(Self::new(Some(variant)))
232        } else {
233            None
234        }
235    }
236}
237
238impl From<Variant> for VariantDict {
239    fn from(other: Variant) -> Self {
240        Self::new(Some(&other))
241    }
242}
243
244#[cfg(test)]
245mod test {
246    use super::*;
247
248    #[test]
249    fn create_destroy() {
250        let _dict = VariantDict::new(None);
251    }
252
253    #[test]
254    fn create_roundtrip() {
255        let dict = VariantDict::default();
256        let var: Variant = dict.to_variant();
257        let _dict2: VariantDict = var.into();
258    }
259
260    #[test]
261    fn into_variant_roundtrip() {
262        let dict1 = VariantDict::default();
263        let dict2 = dict1.clone();
264        dict1.insert_value("one", &(1u8.to_variant()));
265
266        assert_eq!(dict1.lookup::<u8>("one").unwrap(), Some(1u8));
267        assert_eq!(dict2.lookup::<u8>("one").unwrap(), Some(1u8));
268
269        // Convert it into `Variant`
270        let dict: Variant = dict1.into();
271
272        // While we can still access the `VariantDict` via `dict2`,
273        // it should be empty now
274        assert_eq!(dict2.lookup::<u8>("one").unwrap(), None);
275
276        // Convert it back
277        let dict3: VariantDict = dict.into();
278
279        assert_eq!(dict3.lookup::<u8>("one").unwrap(), Some(1u8));
280    }
281
282    #[test]
283    fn create_populate_destroy() {
284        let dict = VariantDict::default();
285        dict.insert_value("one", &(1u8.to_variant()));
286        assert_eq!(dict.lookup_value("one", None), Some(1u8.to_variant()));
287    }
288
289    #[test]
290    fn create_populate_roundtrip() {
291        let dict = VariantDict::default();
292        dict.insert_value("one", &(1u8.to_variant()));
293        let var: Variant = dict.to_variant();
294        let dict = VariantDict::from_variant(&var).expect("Not a dict?");
295        assert_eq!(dict.lookup_value("one", None), Some(1u8.to_variant()));
296    }
297
298    #[test]
299    fn lookup() -> Result<(), Box<dyn std::error::Error>> {
300        let dict = VariantDict::default();
301        dict.insert_value("one", &(1u8.to_variant()));
302        assert_eq!(dict.lookup::<u8>("one")?.unwrap(), 1u8);
303        assert_eq!(
304            dict.lookup::<String>("one").err().unwrap().actual,
305            u8::static_variant_type()
306        );
307        assert!(dict.lookup::<u8>("two")?.is_none());
308        Ok(())
309    }
310
311    #[test]
312    fn create_populate_remove() {
313        let dict = VariantDict::default();
314        let empty_var = dict.to_variant();
315        dict.insert("one", 1u64);
316        assert!(dict.remove("one"));
317        assert!(!dict.remove("one"));
318        let var2 = dict.to_variant();
319        assert_eq!(empty_var, var2);
320    }
321}