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