Skip to main content

ostrya_gvariant/
ser.rs

1use crate::codec::{TupleWriter, write_array};
2use crate::de::MAX_VALUE_DEPTH;
3use crate::{Error, GvEncode, Result, Type, Value};
4
5/// Serialize `value` as type `ty` in GVariant normal form.
6///
7/// Framing offsets and multi-byte scalars are written little-endian, the
8/// normal-form byte order on the little-endian targets ostree supports.
9/// Fields the on-disk format defines as big-endian (uids, modes, timestamps)
10/// are value-level conversions done by the caller before serialization.
11pub fn to_bytes(ty: &Type, value: &Value) -> Result<Vec<u8>> {
12    let mut buf = Vec::new();
13    serialize(&mut buf, ty, value, 0)?;
14    Ok(buf)
15}
16
17/// Serialize one value at the current buffer position.
18///
19/// Alignment is computed on absolute buffer positions: the top-level value
20/// starts at 0 and every container is placed at a multiple of its own
21/// alignment, which is at least each member's alignment, so absolute and
22/// container-relative padding coincide.
23///
24/// `depth` counts container nesting as in the parser, sharing
25/// [`MAX_VALUE_DEPTH`], so a value the serializer accepts is one the parser
26/// accepts back.
27fn serialize(buf: &mut Vec<u8>, ty: &Type, value: &Value, depth: usize) -> Result<()> {
28    if depth > MAX_VALUE_DEPTH {
29        return Err(Error::DepthExceeded);
30    }
31    match (ty, value) {
32        // Scalar and string leaves share the encoding (and the interior-NUL
33        // check) with the typed encoders; the `Value` path only unwraps.
34        (Type::Bool, Value::Bool(b)) => b.encode(buf)?,
35        (Type::Byte, Value::Byte(b)) => b.encode(buf)?,
36        (Type::I16, Value::I16(x)) => buf.extend_from_slice(&x.to_le_bytes()),
37        (Type::U16, Value::U16(x)) => buf.extend_from_slice(&x.to_le_bytes()),
38        (Type::I32 | Type::Handle, Value::I32(x)) => buf.extend_from_slice(&x.to_le_bytes()),
39        (Type::U32, Value::U32(x)) => x.encode(buf)?,
40        (Type::I64, Value::I64(x)) => buf.extend_from_slice(&x.to_le_bytes()),
41        (Type::U64, Value::U64(x)) => x.encode(buf)?,
42        (Type::Double, Value::Double(bits)) => buf.extend_from_slice(&bits.to_le_bytes()),
43        (Type::Str | Type::ObjectPath | Type::Signature, Value::Str(s)) => {
44            s.as_str().encode(buf)?;
45        }
46        (Type::Maybe(elem), Value::Maybe(inner)) => {
47            // `Nothing` is the empty byte sequence. `Just` is the element's own
48            // bytes, followed by one zero byte when the element is
49            // variable-size, which is what tells the two apart.
50            if let Some(child) = inner {
51                serialize(buf, elem, child, depth + 1)?;
52                if elem.fixed_size().is_none() {
53                    buf.push(0);
54                }
55            }
56        }
57        (Type::Array(elem), Value::Bytes(b)) if **elem == Type::Byte => {
58            b.as_slice().encode(buf)?;
59        }
60        (Type::Array(elem), Value::Array(items)) if **elem != Type::Byte => {
61            serialize_array(buf, elem, items, depth)?;
62        }
63        (Type::Tuple(members), Value::Tuple(items)) => {
64            serialize_struct(buf, ty, members.iter(), items, depth)?;
65        }
66        (Type::DictEntry(key, val), Value::Tuple(items)) => {
67            serialize_struct(buf, ty, [&**key, &**val].into_iter(), items, depth)?;
68        }
69        (Type::Variant, Value::Variant(inner)) => {
70            let (child_ty, child) = &**inner;
71            // The buffer is 8-aligned here (variant alignment), which
72            // satisfies any child alignment.
73            serialize(buf, child_ty, child, depth + 1)?;
74            buf.push(0);
75            buf.extend_from_slice(child_ty.signature().as_bytes());
76        }
77        _ => {
78            return Err(Error::TypeMismatch {
79                expected: ty.signature(),
80                found: value.kind(),
81            });
82        }
83    }
84    Ok(())
85}
86
87fn serialize_array(buf: &mut Vec<u8>, elem: &Type, items: &[Value], depth: usize) -> Result<()> {
88    write_array(
89        buf,
90        elem.alignment(),
91        elem.fixed_size().is_some(),
92        items.len(),
93        |buf, i| serialize(buf, elem, &items[i], depth + 1),
94    )
95}
96
97/// Serialize a tuple or dict entry.
98fn serialize_struct<'t>(
99    buf: &mut Vec<u8>,
100    whole: &Type,
101    members: impl ExactSizeIterator<Item = &'t Type>,
102    items: &[Value],
103    depth: usize,
104) -> Result<()> {
105    let n = members.len();
106    if items.len() != n {
107        return Err(Error::TypeMismatch {
108            expected: whole.signature(),
109            found: "tuple of a different arity",
110        });
111    }
112    if n == 0 {
113        buf.push(0);
114        return Ok(());
115    }
116    let mut writer = TupleWriter::new(buf);
117    let last = n - 1;
118    for (i, (member_ty, item)) in members.zip(items).enumerate() {
119        writer.field_dyn(
120            member_ty.alignment(),
121            member_ty.fixed_size(),
122            i == last,
123            |buf| serialize(buf, member_ty, item, depth + 1),
124        )?;
125    }
126    writer.finish(whole.fixed_size());
127    Ok(())
128}
129
130/// The smallest offset size whose representable range covers the container's
131/// total size (data plus the framing offsets themselves). The parser derives
132/// the same size from the total, so both sides agree.
133///
134/// Public alongside [`write_offset`] so a caller that emits a container too
135/// large to buffer -- a static-delta part payload, whose two trailing byte
136/// arrays stream from disk -- can write the same framing this serializer does
137/// once it knows each member's length.
138pub fn choose_offset_size(data_len: usize, n_offsets: usize) -> usize {
139    for z in [1usize, 2, 4] {
140        if data_len + n_offsets * z <= offset_max(z) {
141            return z;
142        }
143    }
144    8
145}
146
147pub(crate) fn offset_max(z: usize) -> usize {
148    match z {
149        1 => 0xFF,
150        2 => 0xFFFF,
151        4 => 0xFFFF_FFFF,
152        _ => usize::MAX,
153    }
154}
155
156/// Append one framing offset of width `z` (as chosen by
157/// [`choose_offset_size`]). A container's offsets are written after its data,
158/// in reverse member order for a tuple and in member order for an array.
159pub fn write_offset(buf: &mut Vec<u8>, value: usize, z: usize) {
160    buf.extend_from_slice(&value.to_le_bytes()[..z]);
161}
162
163#[cfg(test)]
164mod tests {
165    use super::*;
166
167    fn ser(sig: &str, value: &Value) -> Vec<u8> {
168        to_bytes(&Type::parse(sig).unwrap(), value).unwrap()
169    }
170
171    #[test]
172    fn scalars() {
173        assert_eq!(ser("y", &Value::Byte(0xab)), [0xab]);
174        assert_eq!(ser("b", &Value::Bool(true)), [1]);
175        assert_eq!(ser("b", &Value::Bool(false)), [0]);
176        assert_eq!(ser("u", &Value::U32(0x0102_0304)), [4, 3, 2, 1]);
177        assert_eq!(
178            ser("t", &Value::U64(0x0102_0304_0506_0708)),
179            [8, 7, 6, 5, 4, 3, 2, 1]
180        );
181        assert_eq!(ser("s", &Value::Str("hi".into())), b"hi\0");
182    }
183
184    #[test]
185    fn dirmeta_layout() {
186        // (uuua(ayay)) with uid 0, gid 0, mode big-endian 0o40755, no xattrs:
187        // three fixed u32 members and an empty final array -- 12 bytes, no
188        // framing offsets. Matches the golden dirmeta fixture bytes.
189        let value = Value::Tuple(vec![
190            Value::U32(0),
191            Value::U32(0),
192            Value::U32(0o40755u32.swap_bytes()),
193            Value::Array(vec![]),
194        ]);
195        assert_eq!(
196            ser("(uuua(ayay))", &value),
197            [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0x41, 0xed]
198        );
199    }
200
201    #[test]
202    fn string_array_framing() {
203        let value = Value::Array(vec!["foo".into(), "bar".into()]);
204        assert_eq!(ser("as", &value), b"foo\0bar\0\x04\x08");
205    }
206
207    #[test]
208    fn empty_containers() {
209        assert_eq!(ser("as", &Value::Array(vec![])), Vec::<u8>::new());
210        assert_eq!(ser("ay", &Value::Bytes(vec![])), Vec::<u8>::new());
211        assert_eq!(ser("a{sv}", &Value::Array(vec![])), Vec::<u8>::new());
212        assert_eq!(ser("()", &Value::Tuple(vec![])), [0]);
213    }
214
215    #[test]
216    fn dict_with_one_entry() {
217        // {"version": <"1">}: key "version\0" fills bytes 0..8 (the variant
218        // member is 8-aligned), the variant is "1\0" + NUL + "s", the entry
219        // framing offset is the key's end (8), and the array framing offset
220        // is the entry's end (13).
221        let entry = Value::Tuple(vec![
222            "version".into(),
223            Value::variant(Type::Str, "1".into()),
224        ]);
225        assert_eq!(
226            ser("a{sv}", &Value::Array(vec![entry])),
227            b"version\x001\0\0s\x08\x0d"
228        );
229    }
230
231    #[test]
232    fn variable_tuple_with_fixed_final_member() {
233        // (su): the string end needs a framing offset, the trailing u32 does
234        // not; padding to the u32 alignment separates them.
235        let value = Value::Tuple(vec!["abc".into(), Value::U32(5)]);
236        assert_eq!(ser("(su)", &value), b"abc\0\x05\0\0\0\x04");
237    }
238
239    #[test]
240    fn fixed_element_array_packs_without_offsets() {
241        let value = Value::Array(vec![
242            Value::Tuple(vec![Value::U32(1), Value::U32(2), Value::U32(3)]),
243            Value::Tuple(vec![Value::U32(4), Value::U32(5), Value::U32(6)]),
244        ]);
245        assert_eq!(
246            ser("a(uuu)", &value),
247            [
248                1, 0, 0, 0, 2, 0, 0, 0, 3, 0, 0, 0, 4, 0, 0, 0, 5, 0, 0, 0, 6, 0, 0, 0
249            ]
250        );
251    }
252
253    #[test]
254    fn fixed_tuple_end_padding() {
255        let value = Value::Tuple(vec![Value::U64(1), Value::Byte(2)]);
256        assert_eq!(
257            ser("(ty)", &value),
258            [1, 0, 0, 0, 0, 0, 0, 0, 2, 0, 0, 0, 0, 0, 0, 0]
259        );
260    }
261
262    #[test]
263    fn two_byte_offsets_past_255_bytes() {
264        // 30 nine-byte strings: 270 data bytes force 2-byte framing offsets,
265        // so the array is 270 + 30 * 2 bytes.
266        let items: Vec<Value> = (0..30)
267            .map(|i| Value::Str(format!("string{i:02}")))
268            .collect();
269        let bytes = ser("as", &Value::Array(items));
270        assert_eq!(bytes.len(), 270 + 60);
271        // First framing offset: end of the first 9-byte element, 2 bytes LE.
272        assert_eq!(&bytes[270..272], &9u16.to_le_bytes());
273        // Last framing offset: end of the data area.
274        assert_eq!(&bytes[328..330], &270u16.to_le_bytes());
275    }
276
277    #[test]
278    fn rejects_value_depth_bomb() {
279        // 128 nested variants are the deepest the encode path takes, and 129
280        // exceed MAX_VALUE_DEPTH.
281        let mut value = Value::variant(Type::Byte, Value::Byte(1));
282        for _ in 0..127 {
283            value = Value::variant(Type::Variant, value);
284        }
285        let v = Type::parse("v").unwrap();
286        assert!(to_bytes(&v, &value).is_ok());
287        value = Value::variant(Type::Variant, value);
288        assert_eq!(to_bytes(&v, &value), Err(Error::DepthExceeded));
289    }
290
291    #[test]
292    fn rejects_interior_nul_in_string() {
293        let err = to_bytes(&Type::parse("s").unwrap(), &Value::Str("a\0b".into())).unwrap_err();
294        assert_eq!(
295            err,
296            Error::InvalidValue("string contains an interior NUL byte")
297        );
298    }
299
300    #[test]
301    fn rejects_mismatched_value() {
302        let err = to_bytes(&Type::parse("u").unwrap(), &Value::Str("x".into())).unwrap_err();
303        assert!(matches!(err, Error::TypeMismatch { .. }));
304        // ay must be Bytes, not Array of Byte.
305        let err = to_bytes(
306            &Type::parse("ay").unwrap(),
307            &Value::Array(vec![Value::Byte(1)]),
308        )
309        .unwrap_err();
310        assert!(matches!(err, Error::TypeMismatch { .. }));
311        let err = to_bytes(
312            &Type::parse("(uu)").unwrap(),
313            &Value::Tuple(vec![Value::U32(1)]),
314        )
315        .unwrap_err();
316        assert!(matches!(err, Error::TypeMismatch { .. }));
317    }
318}