Skip to main content

ostrya_gvariant/
value.rs

1use crate::Type;
2
3/// A dynamically-typed GVariant value.
4///
5/// The representation is canonical with respect to a [`Type`]:
6///
7/// - byte arrays (`ay`) are `Bytes`, never `Array` of `Byte`;
8/// - dict entries are two-element `Tuple`s;
9/// - a `Variant` carries the child's type, since the serialized form embeds
10///   the child's signature.
11/// - a double is held as its IEEE-754 bit pattern, so a value compares by the
12///   bytes it serializes to.
13/// - an object path (`o`) and a signature (`g`) are `Str`, and a handle (`h`)
14///   is `I32`; the [`Type`] states which of the pair a value carries.
15#[derive(Debug, Clone, PartialEq, Eq)]
16pub enum Value {
17    /// `b`.
18    Bool(bool),
19    /// `y`.
20    Byte(u8),
21    /// `n`.
22    I16(i16),
23    /// `q`.
24    U16(u16),
25    /// `i`, and the folded `h`.
26    I32(i32),
27    /// `u`.
28    U32(u32),
29    /// `x`.
30    I64(i64),
31    /// `t`.
32    U64(u64),
33    /// The IEEE-754 bit pattern of a `d` value. Build one with
34    /// [`Value::double`].
35    Double(u64),
36    /// `s`, and the folded `o` and `g`.
37    Str(String),
38    /// `ay`, held as its bytes rather than as an array of [`Value::Byte`].
39    Bytes(Vec<u8>),
40    /// `m<T>`: the value it holds, or `None` for `nothing`.
41    Maybe(Option<Box<Value>>),
42    /// `a<T>`: the elements, in order.
43    Array(Vec<Value>),
44    /// `(...)`, and the folded dict entry, which is a two-element tuple.
45    Tuple(Vec<Value>),
46    /// `v`: the child's type and the child.
47    Variant(Box<(Type, Value)>),
48}
49
50impl Value {
51    /// Wrap `value` of type `ty` as a variant.
52    pub fn variant(ty: Type, value: Value) -> Value {
53        Value::Variant(Box::new((ty, value)))
54    }
55
56    /// A `d` value from a double.
57    pub fn double(value: f64) -> Value {
58        Value::Double(value.to_bits())
59    }
60
61    pub(crate) fn kind(&self) -> &'static str {
62        match self {
63            Value::Bool(_) => "bool",
64            Value::Byte(_) => "byte",
65            Value::I16(_) => "i16",
66            Value::U16(_) => "u16",
67            Value::I32(_) => "i32",
68            Value::U32(_) => "u32",
69            Value::I64(_) => "i64",
70            Value::U64(_) => "u64",
71            Value::Double(_) => "double",
72            Value::Str(_) => "string",
73            Value::Bytes(_) => "byte array",
74            Value::Maybe(_) => "maybe",
75            Value::Array(_) => "array",
76            Value::Tuple(_) => "tuple",
77            Value::Variant(_) => "variant",
78        }
79    }
80
81    /// The `b` this value holds, or `None` for any other type.
82    pub fn as_bool(&self) -> Option<bool> {
83        match self {
84            Value::Bool(b) => Some(*b),
85            _ => None,
86        }
87    }
88
89    /// The `y` this value holds, or `None` for any other type.
90    pub fn as_byte(&self) -> Option<u8> {
91        match self {
92            Value::Byte(b) => Some(*b),
93            _ => None,
94        }
95    }
96
97    /// The `u` this value holds, or `None` for any other type.
98    pub fn as_u32(&self) -> Option<u32> {
99        match self {
100            Value::U32(x) => Some(*x),
101            _ => None,
102        }
103    }
104
105    /// The `t` this value holds, or `None` for any other type.
106    pub fn as_u64(&self) -> Option<u64> {
107        match self {
108            Value::U64(x) => Some(*x),
109            _ => None,
110        }
111    }
112
113    /// The string this value holds, or `None` for any other type.
114    pub fn as_str(&self) -> Option<&str> {
115        match self {
116            Value::Str(s) => Some(s),
117            _ => None,
118        }
119    }
120
121    /// The byte array this value holds, or `None` for any other type.
122    pub fn as_bytes(&self) -> Option<&[u8]> {
123        match self {
124            Value::Bytes(b) => Some(b),
125            _ => None,
126        }
127    }
128
129    /// The array elements this value holds, or `None` for any other type.
130    pub fn as_array(&self) -> Option<&[Value]> {
131        match self {
132            Value::Array(items) => Some(items),
133            _ => None,
134        }
135    }
136
137    /// The strings an array holds, or `None` for any other type. One element
138    /// that is not a string yields `None` for the whole array. The empty
139    /// array yields the empty list.
140    pub fn as_strv(&self) -> Option<Vec<&str>> {
141        self.as_array()?.iter().map(Value::as_str).collect()
142    }
143
144    /// The tuple members this value holds, or `None` for any other type.
145    pub fn as_tuple(&self) -> Option<&[Value]> {
146        match self {
147            Value::Tuple(items) => Some(items),
148            _ => None,
149        }
150    }
151
152    /// The child type and child value a variant holds, or `None` for any other type.
153    pub fn as_variant(&self) -> Option<(&Type, &Value)> {
154        match self {
155            Value::Variant(inner) => Some((&inner.0, &inner.1)),
156            _ => None,
157        }
158    }
159
160    /// The same value with every multi-byte scalar byte-swapped, recursively,
161    /// through arrays, tuples, dict entries, and the child of a variant.
162    ///
163    /// This is GVariant's own byte-order conversion. The on-disk format places
164    /// its numeric fields in the variant already big-endian while the framing
165    /// stays little-endian, so a value parsed from those bytes holds each
166    /// numeric field byte-reversed, and one swap of the whole tree recovers the
167    /// numbers the fields state. Booleans, bytes, and strings are unchanged.
168    pub fn byteswapped(&self) -> Value {
169        match self {
170            Value::I16(x) => Value::I16(x.swap_bytes()),
171            Value::U16(x) => Value::U16(x.swap_bytes()),
172            Value::I32(x) => Value::I32(x.swap_bytes()),
173            Value::U32(x) => Value::U32(x.swap_bytes()),
174            Value::I64(x) => Value::I64(x.swap_bytes()),
175            Value::U64(x) => Value::U64(x.swap_bytes()),
176            Value::Double(bits) => Value::Double(bits.swap_bytes()),
177            Value::Maybe(inner) => Value::Maybe(inner.as_ref().map(|v| Box::new(v.byteswapped()))),
178            Value::Array(items) => Value::Array(items.iter().map(Value::byteswapped).collect()),
179            Value::Tuple(items) => Value::Tuple(items.iter().map(Value::byteswapped).collect()),
180            Value::Variant(inner) => {
181                let (ty, child) = &**inner;
182                Value::variant(ty.clone(), child.byteswapped())
183            }
184            Value::Bool(_) | Value::Byte(_) | Value::Str(_) | Value::Bytes(_) => self.clone(),
185        }
186    }
187
188    /// Look up a key in a dictionary value (`a{s?}`): an array of two-element
189    /// tuples whose first member is the key string. Returns the value member of
190    /// the first entry whose key matches. Entries that are not `{s?}`-shaped are
191    /// skipped; a non-array `self` yields `None`.
192    pub fn dict_get(&self, key: &str) -> Option<&Value> {
193        for entry in self.as_array()? {
194            let Some(fields) = entry.as_tuple() else {
195                continue;
196            };
197            if let [k, v] = fields
198                && k.as_str() == Some(key)
199            {
200                return Some(v);
201            }
202        }
203        None
204    }
205}
206
207impl From<bool> for Value {
208    fn from(v: bool) -> Value {
209        Value::Bool(v)
210    }
211}
212
213impl From<u8> for Value {
214    fn from(v: u8) -> Value {
215        Value::Byte(v)
216    }
217}
218
219impl From<u32> for Value {
220    fn from(v: u32) -> Value {
221        Value::U32(v)
222    }
223}
224
225impl From<u64> for Value {
226    fn from(v: u64) -> Value {
227        Value::U64(v)
228    }
229}
230
231impl From<&str> for Value {
232    fn from(v: &str) -> Value {
233        Value::Str(v.to_owned())
234    }
235}
236
237impl From<String> for Value {
238    fn from(v: String) -> Value {
239        Value::Str(v)
240    }
241}
242
243impl From<Vec<u8>> for Value {
244    fn from(v: Vec<u8>) -> Value {
245        Value::Bytes(v)
246    }
247}
248
249impl From<&[u8]> for Value {
250    fn from(v: &[u8]) -> Value {
251        Value::Bytes(v.to_vec())
252    }
253}
254
255#[cfg(test)]
256mod tests {
257    use super::*;
258    use crate::{DictBuilder, from_bytes, to_bytes};
259
260    /// A key written as an `as` reads back as the same strings in the same
261    /// order, through the dict the builder produces.
262    #[test]
263    fn reads_back_an_inserted_strv() {
264        let mut builder = DictBuilder::new();
265        builder.insert_strv(
266            "ostree.ref-binding",
267            &["one".to_owned(), "two".to_owned(), "three".to_owned()],
268        );
269        let dict = builder.build();
270
271        let (_, value) = dict
272            .dict_get("ostree.ref-binding")
273            .unwrap()
274            .as_variant()
275            .unwrap();
276        assert_eq!(value.as_strv(), Some(vec!["one", "two", "three"]));
277    }
278
279    /// A serialized `a{sv}` carrying an `as` key hands the strings back after a
280    /// parse of its bytes.
281    #[test]
282    fn reads_back_a_parsed_strv() {
283        let mut builder = DictBuilder::new();
284        builder
285            .insert_str("version", "1")
286            .insert_strv("ostree.ref-binding", &["alpha".to_owned(), "".to_owned()]);
287        let dict = builder.build();
288
289        let ty = Type::parse("a{sv}").unwrap();
290        let bytes = to_bytes(&ty, &dict).unwrap();
291        let parsed = from_bytes(&ty, &bytes).unwrap();
292
293        let (_, value) = parsed
294            .dict_get("ostree.ref-binding")
295            .unwrap()
296            .as_variant()
297            .unwrap();
298        assert_eq!(value.as_strv(), Some(vec!["alpha", ""]));
299    }
300
301    /// The empty array yields the empty list, which is what a key written as an
302    /// empty `as` holds.
303    #[test]
304    fn reads_an_empty_array_as_an_empty_list() {
305        assert_eq!(Value::Array(Vec::new()).as_strv(), Some(Vec::new()));
306
307        let mut builder = DictBuilder::new();
308        builder.insert_strv("k", &[]);
309        let dict = builder.build();
310        let (_, value) = dict.dict_get("k").unwrap().as_variant().unwrap();
311        assert_eq!(value.as_strv(), Some(Vec::new()));
312    }
313
314    /// An `o` and a `g` are held as strings, so an `ao` and an `ag` hand their
315    /// strings back the way an `as` does.
316    #[test]
317    fn reads_a_folded_object_path_and_signature_array() {
318        let paths = Value::Array(vec![
319            Value::Str("/org/example/One".to_owned()),
320            Value::Str("/org/example/Two".to_owned()),
321        ]);
322        let ty = Type::parse("ao").unwrap();
323        let parsed = from_bytes(&ty, &to_bytes(&ty, &paths).unwrap()).unwrap();
324        assert_eq!(
325            parsed.as_strv(),
326            Some(vec!["/org/example/One", "/org/example/Two"])
327        );
328
329        let signatures = Value::Array(vec![Value::Str("a{sv}".to_owned())]);
330        let ty = Type::parse("ag").unwrap();
331        let parsed = from_bytes(&ty, &to_bytes(&ty, &signatures).unwrap()).unwrap();
332        assert_eq!(parsed.as_strv(), Some(vec!["a{sv}"]));
333    }
334
335    /// An array holding an element that is not a string yields `None` for the
336    /// whole array. A byte array, a nested array, and a dict entry are such
337    /// elements.
338    #[test]
339    fn refuses_an_array_with_a_non_string_element() {
340        let mixed = Value::Array(vec![Value::Str("one".to_owned()), Value::U32(2)]);
341        assert_eq!(mixed.as_strv(), None);
342        assert_eq!(Value::Array(vec![Value::Bytes(vec![0x41])]).as_strv(), None);
343        let nested = Value::Array(vec![Value::Array(vec![Value::Str("one".to_owned())])]);
344        assert_eq!(nested.as_strv(), None);
345        let entries = Value::Array(vec![Value::Tuple(vec![
346            Value::Str("k".to_owned()),
347            Value::Str("v".to_owned()),
348        ])]);
349        assert_eq!(entries.as_strv(), None);
350    }
351
352    /// Only an array yields the strings. The string, the byte array, the
353    /// tuple, the maybe, and the variant all yield `None`.
354    #[test]
355    fn refuses_every_other_type() {
356        assert_eq!(Value::Str("one".to_owned()).as_strv(), None);
357        assert_eq!(Value::Bytes(vec![0x41, 0x42]).as_strv(), None);
358        assert_eq!(
359            Value::Tuple(vec![Value::Str("one".to_owned())]).as_strv(),
360            None
361        );
362        assert_eq!(
363            Value::Maybe(Some(Box::new(Value::Array(vec![Value::Str(
364                "one".to_owned()
365            )]))))
366            .as_strv(),
367            None
368        );
369        assert_eq!(Value::Maybe(None).as_strv(), None);
370        assert_eq!(
371            Value::variant(Type::Array(Box::new(Type::Str)), Value::Array(Vec::new())).as_strv(),
372            None
373        );
374    }
375}