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 tuple members this value holds, or `None` for any other type.
138    pub fn as_tuple(&self) -> Option<&[Value]> {
139        match self {
140            Value::Tuple(items) => Some(items),
141            _ => None,
142        }
143    }
144
145    /// The child type and child value a variant holds, or `None` for any other type.
146    pub fn as_variant(&self) -> Option<(&Type, &Value)> {
147        match self {
148            Value::Variant(inner) => Some((&inner.0, &inner.1)),
149            _ => None,
150        }
151    }
152
153    /// The same value with every multi-byte scalar byte-swapped, recursively,
154    /// through arrays, tuples, dict entries, and the child of a variant.
155    ///
156    /// This is GVariant's own byte-order conversion. The on-disk format places
157    /// its numeric fields in the variant already big-endian while the framing
158    /// stays little-endian, so a value parsed from those bytes holds each
159    /// numeric field byte-reversed, and one swap of the whole tree recovers the
160    /// numbers the fields state. Booleans, bytes, and strings are unchanged.
161    pub fn byteswapped(&self) -> Value {
162        match self {
163            Value::I16(x) => Value::I16(x.swap_bytes()),
164            Value::U16(x) => Value::U16(x.swap_bytes()),
165            Value::I32(x) => Value::I32(x.swap_bytes()),
166            Value::U32(x) => Value::U32(x.swap_bytes()),
167            Value::I64(x) => Value::I64(x.swap_bytes()),
168            Value::U64(x) => Value::U64(x.swap_bytes()),
169            Value::Double(bits) => Value::Double(bits.swap_bytes()),
170            Value::Maybe(inner) => Value::Maybe(inner.as_ref().map(|v| Box::new(v.byteswapped()))),
171            Value::Array(items) => Value::Array(items.iter().map(Value::byteswapped).collect()),
172            Value::Tuple(items) => Value::Tuple(items.iter().map(Value::byteswapped).collect()),
173            Value::Variant(inner) => {
174                let (ty, child) = &**inner;
175                Value::variant(ty.clone(), child.byteswapped())
176            }
177            Value::Bool(_) | Value::Byte(_) | Value::Str(_) | Value::Bytes(_) => self.clone(),
178        }
179    }
180
181    /// Look up a key in a dictionary value (`a{s?}`): an array of two-element
182    /// tuples whose first member is the key string. Returns the value member of
183    /// the first entry whose key matches. Entries that are not `{s?}`-shaped are
184    /// skipped; a non-array `self` yields `None`.
185    pub fn dict_get(&self, key: &str) -> Option<&Value> {
186        for entry in self.as_array()? {
187            let Some(fields) = entry.as_tuple() else {
188                continue;
189            };
190            if let [k, v] = fields
191                && k.as_str() == Some(key)
192            {
193                return Some(v);
194            }
195        }
196        None
197    }
198}
199
200impl From<bool> for Value {
201    fn from(v: bool) -> Value {
202        Value::Bool(v)
203    }
204}
205
206impl From<u8> for Value {
207    fn from(v: u8) -> Value {
208        Value::Byte(v)
209    }
210}
211
212impl From<u32> for Value {
213    fn from(v: u32) -> Value {
214        Value::U32(v)
215    }
216}
217
218impl From<u64> for Value {
219    fn from(v: u64) -> Value {
220        Value::U64(v)
221    }
222}
223
224impl From<&str> for Value {
225    fn from(v: &str) -> Value {
226        Value::Str(v.to_owned())
227    }
228}
229
230impl From<String> for Value {
231    fn from(v: String) -> Value {
232        Value::Str(v)
233    }
234}
235
236impl From<Vec<u8>> for Value {
237    fn from(v: Vec<u8>) -> Value {
238        Value::Bytes(v)
239    }
240}
241
242impl From<&[u8]> for Value {
243    fn from(v: &[u8]) -> Value {
244        Value::Bytes(v.to_vec())
245    }
246}