Skip to main content

ostrya_gvariant/
value.rs

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