Skip to main content

ostrya_gvariant/
de.rs

1use crate::codec::{ArrayReader, TupleReader};
2use crate::ser::offset_max;
3use crate::{Error, GvDecode, Result, Type, Value};
4
5/// The maximum nesting depth of a value.
6///
7/// A nested variant lets the nesting of a value exceed the static depth of the
8/// type signature. For this reason, the parser and the serializer apply their
9/// own limit.
10pub(crate) const MAX_VALUE_DEPTH: usize = 128;
11
12/// Deserializes normal-form GVariant bytes of type `ty` into a [`Value`].
13///
14/// The parser accepts normal form only, so a value that it returns
15/// re-serializes to the identical bytes. The object checksum depends on this
16/// property. The parser preallocates at most 4096 elements for an array, so
17/// hostile input cannot force an allocation proportional to its length.
18///
19/// # Depth limit
20///
21/// A leaf can sit under at most 128 levels of containers. Each variant, array,
22/// maybe, tuple, and dict entry adds one level. The bytes of an `ay` add no
23/// level. A `v` that holds 128 nested variants decodes, and a `v` that holds
24/// 129 returns [`Error::DepthExceeded`].
25///
26/// # Errors
27///
28/// - [`Error::NotNormal`] if `data` deviates from normal form in any way. The
29///   variant carries a reason that names the deviation. These are the
30///   deviations:
31///   - a scalar of the wrong size, or a boolean byte that is not 0 or 1
32///   - a string with no NUL terminator, with an interior NUL byte, or with
33///     bytes that are not UTF-8
34///   - padding bytes that are not zero
35///   - framing offsets that are out of bounds, out of order, or wider than
36///     normal form needs
37///   - an array of fixed-size elements whose size is not a multiple of the
38///     element size
39///   - a fixed-size tuple of the wrong size, or tuple members that do not fill
40///     the tuple
41///   - an empty tuple `()` that is not a single zero byte
42///   - a maybe of a variable-size element with no terminating zero byte
43///   - a variant with no type separator, or with a type signature that is not
44///     UTF-8 or not valid
45/// - [`Error::DepthExceeded`] if the value nests deeper than the
46///   [depth limit](from_bytes#depth-limit).
47pub fn from_bytes(ty: &Type, data: &[u8]) -> Result<Value> {
48    parse(ty, data, 0)
49}
50
51/// Checks that `data` is normal-form GVariant bytes of type `ty`.
52///
53/// The check accepts exactly the input that [`from_bytes`] accepts, with the
54/// same [depth limit](from_bytes#depth-limit) of 128 levels. It keeps no
55/// decoded value, so its memory does not grow with the element count of the
56/// input.
57///
58/// # Errors
59///
60/// For each input that [`from_bytes`] rejects, this function returns the same
61/// error:
62///
63/// - [`Error::NotNormal`] if `data` deviates from normal form. The
64///   [`from_bytes` errors](from_bytes#errors) list the deviations.
65/// - [`Error::DepthExceeded`] if the value nests deeper than 128 levels.
66pub fn validate(ty: &Type, data: &[u8]) -> Result<()> {
67    check(ty, data, 0)
68}
69
70/// Deserializes one member of a serialized tuple into a [`Value`].
71///
72/// `ty` is the type of the whole tuple. `index` is the zero-based position of
73/// the member to decode.
74///
75/// The function checks the framing of every member the way [`from_bytes`]
76/// checks it: the framing offsets, the padding, and the size of the tuple. It
77/// does not decode the other members, so it does not detect a fault inside
78/// them. If the other members of a serialized value are large, a reader of one
79/// member pays only for their framing.
80///
81/// # Errors
82///
83/// - [`Error::NotNormal`] with the reason "the type is not a tuple" if `ty` is
84///   not a tuple.
85/// - [`Error::NotNormal`] with the reason "the tuple holds no member of that
86///   index" if `index` is not less than the member count.
87/// - [`Error::NotNormal`] if the framing of the tuple is not normal form, or
88///   if the member at `index` is not normal form. The
89///   [`from_bytes` errors](from_bytes#errors) list the deviations.
90/// - [`Error::DepthExceeded`] if the member nests deeper than the
91///   [depth limit](from_bytes#depth-limit). The tuple counts as one level.
92pub fn tuple_field_from_bytes(ty: &Type, data: &[u8], index: usize) -> Result<Value> {
93    let Type::Tuple(members) = ty else {
94        return Err(Error::NotNormal("the type is not a tuple"));
95    };
96    let n = members.len();
97    if index >= n {
98        return Err(Error::NotNormal("the tuple holds no member of that index"));
99    }
100    let n_offsets = members
101        .iter()
102        .take(n - 1)
103        .filter(|member| member.fixed_size().is_none())
104        .count();
105    let mut reader = TupleReader::new(data, n_offsets, ty.fixed_size())?;
106    let mut field = None;
107    let last = n - 1;
108    for (i, member_ty) in members.iter().enumerate() {
109        let slice = reader.field(member_ty.alignment(), member_ty.fixed_size(), i == last)?;
110        if i == index {
111            field = Some(parse(member_ty, slice, 1)?);
112        }
113    }
114    reader.finish()?;
115    Ok(field.expect("the index names a member of the tuple"))
116}
117
118fn parse(ty: &Type, data: &[u8], depth: usize) -> Result<Value> {
119    if depth > MAX_VALUE_DEPTH {
120        return Err(Error::DepthExceeded);
121    }
122    match ty {
123        // Scalar and string leaves use the strict checks of the typed
124        // decoders. The `Value` path only wraps their results.
125        Type::Bool => Ok(Value::Bool(bool::decode(data)?)),
126        Type::Byte => Ok(Value::Byte(u8::decode(data)?)),
127        Type::I16 => Ok(Value::I16(i16::from_le_bytes(exact::<2>(data)?))),
128        Type::U16 => Ok(Value::U16(u16::from_le_bytes(exact::<2>(data)?))),
129        Type::I32 | Type::Handle => Ok(Value::I32(i32::from_le_bytes(exact::<4>(data)?))),
130        Type::U32 => Ok(Value::U32(u32::decode(data)?)),
131        Type::I64 => Ok(Value::I64(i64::from_le_bytes(exact::<8>(data)?))),
132        Type::U64 => Ok(Value::U64(u64::decode(data)?)),
133        Type::Double => Ok(Value::Double(u64::from_le_bytes(exact::<8>(data)?))),
134        Type::Str | Type::ObjectPath | Type::Signature => {
135            Ok(Value::Str(<&str>::decode(data)?.to_owned()))
136        }
137        Type::Maybe(elem) => parse_maybe(elem, data, depth),
138        Type::Array(elem) if **elem == Type::Byte => Ok(Value::Bytes(data.to_vec())),
139        Type::Array(elem) => parse_array(elem, data, depth),
140        Type::Tuple(members) => parse_struct(ty, members.iter(), data, depth),
141        Type::DictEntry(key, value) => {
142            parse_struct(ty, [&**key, &**value].into_iter(), data, depth)
143        }
144        Type::Variant => {
145            let (child, _, child_ty) = split_variant(data)?;
146            let value = parse(&child_ty, child, depth + 1)?;
147            Ok(Value::variant(child_ty, value))
148        }
149    }
150}
151
152/// Applies the checks of [`parse`] and builds no value.
153fn check(ty: &Type, data: &[u8], depth: usize) -> Result<()> {
154    if depth > MAX_VALUE_DEPTH {
155        return Err(Error::DepthExceeded);
156    }
157    match ty {
158        Type::Bool => bool::decode(data).map(drop),
159        Type::Byte => u8::decode(data).map(drop),
160        Type::I16 | Type::U16 => exact::<2>(data).map(drop),
161        Type::I32 | Type::Handle | Type::U32 => exact::<4>(data).map(drop),
162        Type::I64 | Type::U64 | Type::Double => exact::<8>(data).map(drop),
163        Type::Str | Type::ObjectPath | Type::Signature => <&str>::decode(data).map(drop),
164        Type::Maybe(elem) => {
165            if data.is_empty() {
166                return Ok(());
167            }
168            let child = if elem.fixed_size().is_some() {
169                data
170            } else {
171                match data.split_last() {
172                    Some((0, rest)) => rest,
173                    _ => return Err(Error::NotNormal("maybe lacks its terminating zero byte")),
174                }
175            };
176            check(elem, child, depth + 1)
177        }
178        Type::Array(elem) if **elem == Type::Byte => Ok(()),
179        Type::Array(elem) => {
180            let mut reader = ArrayReader::new(data, elem.alignment(), elem.fixed_size())?;
181            while let Some(slice) = reader.next_slice() {
182                check(elem, slice?, depth + 1)?;
183            }
184            Ok(())
185        }
186        Type::Tuple(members) => check_struct(ty, members.iter(), data, depth),
187        Type::DictEntry(key, value) => {
188            check_struct(ty, [&**key, &**value].into_iter(), data, depth)
189        }
190        Type::Variant => {
191            let (child, _, child_ty) = split_variant(data)?;
192            check(&child_ty, child, depth + 1)
193        }
194    }
195}
196
197/// Applies the checks of [`parse_struct`] and builds no value.
198fn check_struct<'t>(
199    whole: &Type,
200    members: impl ExactSizeIterator<Item = &'t Type> + Clone,
201    data: &[u8],
202    depth: usize,
203) -> Result<()> {
204    let n = members.len();
205    if n == 0 {
206        if data != [0] {
207            return Err(Error::NotNormal("empty tuple is not a single zero byte"));
208        }
209        return Ok(());
210    }
211    let n_offsets = members
212        .clone()
213        .take(n - 1)
214        .filter(|m| m.fixed_size().is_none())
215        .count();
216    let mut reader = TupleReader::new(data, n_offsets, whole.fixed_size())?;
217    let last = n - 1;
218    for (i, member_ty) in members.enumerate() {
219        let slice = reader.field(member_ty.alignment(), member_ty.fixed_size(), i == last)?;
220        check(member_ty, slice, depth + 1)?;
221    }
222    reader.finish()
223}
224
225/// The maximum element count that the parser preallocates for an array.
226///
227/// The parser preallocates before it checks any element. The count comes
228/// directly from the input length (one element per byte for fixed-size
229/// elements). With the cap, hostile input cannot force an allocation
230/// proportional to its own size. A large valid array still grows past the cap,
231/// with amortized cost.
232const ARRAY_PREALLOC_CAP: usize = 4096;
233
234/// Parses `m<T>`.
235///
236/// If the input has no bytes, the value is `Nothing`. Any other input is
237/// `Just`. For a fixed-size element, the element bytes are the whole input.
238/// For a variable-size element, the element bytes are the input less its
239/// trailing zero byte.
240fn parse_maybe(elem: &Type, data: &[u8], depth: usize) -> Result<Value> {
241    if data.is_empty() {
242        return Ok(Value::Maybe(None));
243    }
244    let child = if elem.fixed_size().is_some() {
245        data
246    } else {
247        match data.split_last() {
248            Some((0, rest)) => rest,
249            _ => return Err(Error::NotNormal("maybe lacks its terminating zero byte")),
250        }
251    };
252    Ok(Value::Maybe(Some(Box::new(parse(elem, child, depth + 1)?))))
253}
254
255fn parse_array(elem: &Type, data: &[u8], depth: usize) -> Result<Value> {
256    let mut reader = ArrayReader::new(data, elem.alignment(), elem.fixed_size())?;
257    let mut items = Vec::with_capacity(reader.len().min(ARRAY_PREALLOC_CAP));
258    while let Some(slice) = reader.next_slice() {
259        items.push(parse(elem, slice?, depth + 1)?);
260    }
261    Ok(Value::Array(items))
262}
263
264fn parse_struct<'t>(
265    whole: &Type,
266    members: impl ExactSizeIterator<Item = &'t Type> + Clone,
267    data: &[u8],
268    depth: usize,
269) -> Result<Value> {
270    let n = members.len();
271    if n == 0 {
272        if data != [0] {
273            return Err(Error::NotNormal("empty tuple is not a single zero byte"));
274        }
275        return Ok(Value::Tuple(Vec::new()));
276    }
277    // Framing offsets cover each variable-size member except the last member.
278    let n_offsets = members
279        .clone()
280        .take(n - 1)
281        .filter(|m| m.fixed_size().is_none())
282        .count();
283    let mut reader = TupleReader::new(data, n_offsets, whole.fixed_size())?;
284    let mut items = Vec::with_capacity(n);
285    let last = n - 1;
286    for (i, member_ty) in members.enumerate() {
287        let slice = reader.field(member_ty.alignment(), member_ty.fixed_size(), i == last)?;
288        items.push(parse(member_ty, slice, depth + 1)?);
289    }
290    reader.finish()?;
291    Ok(Value::Tuple(items))
292}
293
294pub(crate) fn exact<const N: usize>(data: &[u8]) -> Result<[u8; N]> {
295    data.try_into()
296        .map_err(|_| Error::NotNormal("scalar has the wrong size"))
297}
298
299/// Splits a serialized variant into its parts.
300///
301/// The parts are the child bytes, the borrowed signature bytes, and the parsed
302/// child type. The `Value` decoder and the typed decoders both use this
303/// function.
304pub(crate) fn split_variant(data: &[u8]) -> Result<(&[u8], &[u8], Type)> {
305    let Some(sep) = data.iter().rposition(|&b| b == 0) else {
306        return Err(Error::NotNormal("variant lacks a type separator"));
307    };
308    let signature = &data[sep + 1..];
309    let sig = std::str::from_utf8(signature)
310        .map_err(|_| Error::NotNormal("variant type signature is not UTF-8"))?;
311    let ty = Type::parse(sig).map_err(|_| Error::NotNormal("variant type signature is invalid"))?;
312    Ok((&data[..sep], signature, ty))
313}
314
315pub(crate) fn check_padding(padding: &[u8]) -> Result<()> {
316    if padding.iter().any(|&b| b != 0) {
317        return Err(Error::NotNormal("padding bytes are not zero"));
318    }
319    Ok(())
320}
321
322/// Returns the framing-offset size for a container of `len` serialized bytes.
323///
324/// The result is the smallest size whose range covers `len`:
325///
326/// - 1 if `len` is at most `0xFF`.
327/// - 2 if `len` is more than `0xFF` and at most `0xFFFF`.
328/// - 4 if `len` is more than `0xFFFF` and at most `0xFFFF_FFFF`.
329/// - 8 if `len` is more than `0xFFFF_FFFF`.
330///
331/// [`choose_offset_size`] picks the size on the encode side.
332///
333/// A reader of a container too large to buffer uses this function to find the
334/// framing offsets at the end from the total length. A static-delta part
335/// payload, read as a stream, is such a container. [`from_bytes`] finds the
336/// offsets the same way.
337///
338/// [`choose_offset_size`]: crate::choose_offset_size
339pub fn offset_size_for(len: usize) -> usize {
340    for z in [1usize, 2, 4] {
341        if len <= offset_max(z) {
342            return z;
343        }
344    }
345    8
346}
347
348pub(crate) fn read_offset(bytes: &[u8], z: usize) -> usize {
349    let mut buf = [0u8; 8];
350    buf[..z].copy_from_slice(bytes);
351    u64::from_le_bytes(buf) as usize
352}
353
354#[cfg(test)]
355mod tests {
356    use super::*;
357    use crate::to_bytes;
358
359    fn round_trip(sig: &str, value: &Value) {
360        let ty = Type::parse(sig).unwrap();
361        let bytes = to_bytes(&ty, value).unwrap();
362        let parsed = from_bytes(&ty, &bytes).unwrap();
363        assert_eq!(&parsed, value, "value round-trip for {sig}");
364        assert_eq!(
365            to_bytes(&ty, &parsed).unwrap(),
366            bytes,
367            "byte round-trip for {sig}"
368        );
369    }
370
371    fn checksum_bytes(seed: u8) -> Value {
372        Value::Bytes((0..32).map(|i| seed.wrapping_add(i)).collect())
373    }
374
375    /// One member of a tuple decodes to the value that the whole parse gives it.
376    ///
377    /// The decode still checks the framing of every member. The function
378    /// refuses an index outside the tuple.
379    #[test]
380    fn decodes_one_tuple_member() {
381        let ty = Type::parse("(asa{sv}t)").unwrap();
382        let value = Value::Tuple(vec![
383            Value::Array(vec!["a".into(), "bb".into()]),
384            Value::Array(vec![Value::Tuple(vec![
385                "k".into(),
386                Value::variant(Type::U32, Value::U32(9)),
387            ])]),
388            Value::U64(0x0123_4567_89ab_cdef),
389        ]);
390        let bytes = to_bytes(&ty, &value).unwrap();
391        let Value::Tuple(members) = from_bytes(&ty, &bytes).unwrap() else {
392            panic!("the summary type is a tuple");
393        };
394        for (index, member) in members.iter().enumerate() {
395            assert_eq!(
396                &tuple_field_from_bytes(&ty, &bytes, index).unwrap(),
397                member,
398                "member {index}"
399            );
400        }
401        assert!(tuple_field_from_bytes(&ty, &bytes, 3).is_err());
402        assert!(tuple_field_from_bytes(&Type::Str, &bytes, 0).is_err());
403        // For each index, the decode reads the framing of every member.
404        let mut torn = bytes.clone();
405        let last = torn.len() - 1;
406        torn[last] = 0xff;
407        assert!(tuple_field_from_bytes(&ty, &torn, 2).is_err());
408    }
409
410    #[test]
411    fn round_trips_scalars_and_simple_containers() {
412        round_trip("y", &Value::Byte(7));
413        round_trip("b", &Value::Bool(true));
414        round_trip("u", &Value::U32(0xdead_beef));
415        round_trip("t", &Value::U64(0x0123_4567_89ab_cdef));
416        round_trip("s", &Value::Str("héllo wörld".into()));
417        round_trip("ay", &Value::Bytes(vec![0, 1, 2, 0, 4]));
418        round_trip(
419            "as",
420            &Value::Array(vec!["a".into(), "".into(), "ccc".into()]),
421        );
422        round_trip(
423            "aay",
424            &Value::Array(vec![Value::Bytes(vec![]), Value::Bytes(vec![1, 2])]),
425        );
426        round_trip("v", &Value::variant(Type::Str, "nested".into()));
427        round_trip(
428            "v",
429            &Value::variant(
430                Type::parse("v").unwrap(),
431                Value::variant(Type::U32, Value::U32(5)),
432            ),
433        );
434    }
435
436    /// The types outside the on-disk format round-trip.
437    ///
438    /// The `ostree commit --add-metadata` command writes these types into the
439    /// metadata dict of a commit.
440    #[test]
441    fn round_trips_the_metadata_only_types() {
442        round_trip("n", &Value::I16(-5));
443        round_trip("q", &Value::U16(5));
444        round_trip("i", &Value::I32(-42));
445        round_trip("h", &Value::I32(7));
446        round_trip("x", &Value::I64(-5));
447        round_trip("d", &Value::double(1.5));
448        round_trip("o", &Value::Str("/a/b".into()));
449        round_trip("g", &Value::Str("ay".into()));
450        round_trip("ms", &Value::Maybe(None));
451        round_trip("ms", &Value::Maybe(Some(Box::new(Value::Str("x".into())))));
452        round_trip(
453            "ms",
454            &Value::Maybe(Some(Box::new(Value::Str(String::new())))),
455        );
456        round_trip("mi", &Value::Maybe(None));
457        round_trip("mi", &Value::Maybe(Some(Box::new(Value::I32(3)))));
458        round_trip(
459            "ami",
460            &Value::Array(vec![
461                Value::Maybe(Some(Box::new(Value::I32(1)))),
462                Value::Maybe(None),
463            ]),
464        );
465        round_trip(
466            "(sid)",
467            &Value::Tuple(vec![
468                Value::Str("a".into()),
469                Value::I32(5),
470                Value::double(-0.5),
471            ]),
472        );
473    }
474
475    /// A maybe of a variable-size element ends in one zero byte.
476    ///
477    /// This byte tells `Just ""` apart from `Nothing`.
478    #[test]
479    fn maybe_framing() {
480        let ty = Type::parse("ms").unwrap();
481        assert_eq!(
482            to_bytes(&ty, &Value::Maybe(None)).unwrap(),
483            Vec::<u8>::new()
484        );
485        assert_eq!(
486            to_bytes(
487                &ty,
488                &Value::Maybe(Some(Box::new(Value::Str(String::new()))))
489            )
490            .unwrap(),
491            [0, 0]
492        );
493        assert_eq!(
494            from_bytes(&ty, &[]).unwrap(),
495            Value::Maybe(None),
496            "no bytes is Nothing"
497        );
498        assert!(from_bytes(&ty, &[1]).is_err(), "a missing terminator");
499    }
500
501    #[test]
502    fn round_trips_commit_shaped_value() {
503        // (a{sv}aya(say)sstayay) with representative metadata.
504        let metadata = Value::Array(vec![
505            Value::Tuple(vec![
506                "ostree.ref-binding".into(),
507                Value::variant(
508                    Type::parse("as").unwrap(),
509                    Value::Array(vec!["test/main".into()]),
510                ),
511            ]),
512            Value::Tuple(vec![
513                "version".into(),
514                Value::variant(Type::Str, "1.0".into()),
515            ]),
516        ]);
517        let commit = Value::Tuple(vec![
518            metadata,
519            Value::Bytes(vec![]), // root commit: no parent
520            Value::Array(vec![]), // related objects
521            "subject".into(),
522            "".into(),
523            Value::U64(1_700_000_000u64.swap_bytes()),
524            checksum_bytes(0x10),
525            checksum_bytes(0x50),
526        ]);
527        round_trip("(a{sv}aya(say)sstayay)", &commit);
528    }
529
530    #[test]
531    fn round_trips_summary_shaped_value() {
532        // (a(s(taya{sv}))a{sv}) with one ref entry and global metadata.
533        let ref_meta = Value::Array(vec![Value::Tuple(vec![
534            "ostree.commit.timestamp".into(),
535            Value::variant(Type::U64, Value::U64(1_700_000_000u64.swap_bytes())),
536        ])]);
537        let refs = Value::Array(vec![Value::Tuple(vec![
538            "test/main".into(),
539            Value::Tuple(vec![Value::U64(431), checksum_bytes(0x30), ref_meta]),
540        ])]);
541        let global = Value::Array(vec![Value::Tuple(vec![
542            "ostree.summary.mode".into(),
543            Value::variant(Type::Str, "bare".into()),
544        ])]);
545        round_trip("(a(s(taya{sv}))a{sv})", &Value::Tuple(vec![refs, global]));
546    }
547
548    #[test]
549    fn round_trips_delta_shaped_values() {
550        let meta_entry = Value::Tuple(vec![
551            Value::U32(0),
552            checksum_bytes(0x60),
553            Value::U64(4096),
554            Value::U64(8192),
555            Value::Bytes(vec![1; 33]),
556        ]);
557        round_trip("(uayttay)", &meta_entry);
558
559        let fallback = Value::Tuple(vec![
560            Value::Byte(1),
561            checksum_bytes(0x70),
562            Value::U64(100),
563            Value::U64(200),
564        ]);
565        round_trip("(yaytt)", &fallback);
566
567        let modes = Value::Array(vec![Value::Tuple(vec![
568            Value::U32(0o100644u32.swap_bytes()),
569            Value::U32(0),
570            Value::U32(0),
571        ])]);
572        let xattrs = Value::Array(vec![Value::Array(vec![])]);
573        let part = Value::Tuple(vec![
574            modes,
575            xattrs,
576            Value::Bytes(vec![0xaa; 40]),
577            Value::Bytes(vec![b'S', 0x01]),
578        ]);
579        round_trip("(a(uuu)aa(ayay)ayay)", &part);
580    }
581
582    #[test]
583    fn round_trips_offset_size_boundaries() {
584        for n in [250usize, 255, 256, 300, 70_000] {
585            let value = Value::Array(vec![Value::Bytes(vec![0x5a; n])]);
586            round_trip("aay", &value);
587        }
588    }
589
590    #[test]
591    fn array_length_does_not_drive_preallocation() {
592        // A large all-0xFF `ab` buffer names one bool element per byte. The
593        // first element fails to decode, so the parse returns an error. The
594        // untrusted element count must not drive a preallocation proportional
595        // to it before the parser checks any element. `parse_array` applies
596        // the bound. Only an inspection of `parse_array` enforces the ratio.
597        let data = vec![0xffu8; 1 << 20];
598        assert_eq!(
599            from_bytes(&Type::parse("ab").unwrap(), &data),
600            Err(Error::NotNormal("boolean is not 0 or 1"))
601        );
602    }
603
604    /// `validate` accepts exactly the input that `from_bytes` accepts.
605    ///
606    /// For each rejected input, both return the same error. The cases are
607    /// valid and malformed inputs of every shape.
608    #[test]
609    fn validate_agrees_with_from_bytes() {
610        let dict = Value::Array(vec![
611            Value::Tuple(vec![
612                "a".into(),
613                Value::variant(Type::parse("ab").unwrap(), Value::Array(vec![true.into()])),
614            ]),
615            Value::Tuple(vec![
616                "b".into(),
617                Value::variant(Type::parse("ms").unwrap(), Value::Maybe(None)),
618            ]),
619            Value::Tuple(vec![
620                "c".into(),
621                Value::variant(
622                    Type::parse("(sid)").unwrap(),
623                    Value::Tuple(vec!["x".into(), Value::I32(-1), Value::double(0.5)]),
624                ),
625            ]),
626        ]);
627        let asv = Type::parse("a{sv}").unwrap();
628        let good = to_bytes(&asv, &dict).unwrap();
629        let mut cases: Vec<(&str, Vec<u8>)> = vec![("a{sv}", good.clone())];
630        for i in 0..good.len() {
631            let mut torn = good.clone();
632            torn[i] ^= 0xff;
633            cases.push(("a{sv}", torn));
634            cases.push(("a{sv}", good[..i].to_vec()));
635        }
636        let mut deep = vec![1u8, 0, b'y'];
637        for _ in 0..128 {
638            deep.extend_from_slice(&[0, b'v']);
639        }
640        cases.extend([
641            ("v", deep),
642            ("ab", vec![0xff; 64]),
643            ("ab", vec![0, 1, 1]),
644            ("ms", vec![1]),
645            ("ms", vec![0, 0]),
646            ("mi", vec![1, 2, 3, 4]),
647            ("()", vec![0]),
648            ("()", vec![1]),
649            ("(uuu)", vec![0; 13]),
650            ("(su)", b"a\0\0\0\x05\0\0\0\0\0\x02".to_vec()),
651            ("as", vec![b'a', 0, 1, 2]),
652            ("au", vec![0; 6]),
653            ("s", vec![0xff, 0xfe, 0]),
654            ("v", b"a\0d".to_vec()),
655            ("ay", vec![1, 2, 3]),
656            ("aay", vec![1, 2, 0]),
657        ]);
658        for (sig, bytes) in &cases {
659            let ty = Type::parse(sig).unwrap();
660            assert_eq!(
661                validate(&ty, bytes),
662                from_bytes(&ty, bytes).map(drop),
663                "{sig} {bytes:?}"
664            );
665        }
666    }
667
668    #[test]
669    fn rejects_bad_scalars() {
670        let u = Type::parse("u").unwrap();
671        assert!(from_bytes(&u, &[1, 2, 3]).is_err());
672        assert!(from_bytes(&u, &[1, 2, 3, 4, 5]).is_err());
673        let b = Type::parse("b").unwrap();
674        assert_eq!(
675            from_bytes(&b, &[2]),
676            Err(Error::NotNormal("boolean is not 0 or 1"))
677        );
678    }
679
680    #[test]
681    fn rejects_bad_strings() {
682        let s = Type::parse("s").unwrap();
683        assert!(from_bytes(&s, b"abc").is_err()); // no terminator
684        assert!(from_bytes(&s, b"a\0b\0").is_err()); // interior NUL
685        assert!(from_bytes(&s, &[0xff, 0xfe, 0]).is_err()); // not UTF-8
686        assert!(from_bytes(&s, b"").is_err()); // empty
687    }
688
689    #[test]
690    fn rejects_nonzero_padding() {
691        // (su) with "abcd": bytes 5..8 are alignment padding for the u32.
692        let ty = Type::parse("(su)").unwrap();
693        let good = to_bytes(&ty, &Value::Tuple(vec!["abcd".into(), Value::U32(9)])).unwrap();
694        assert!(from_bytes(&ty, &good).is_ok());
695        let mut bad = good.clone();
696        bad[6] = 1;
697        assert_eq!(
698            from_bytes(&ty, &bad),
699            Err(Error::NotNormal("padding bytes are not zero"))
700        );
701    }
702
703    #[test]
704    fn rejects_malformed_array_framing() {
705        let ty = Type::parse("as").unwrap();
706        // Framing offset points past the framing area.
707        assert!(from_bytes(&ty, &[b'a', 0, 3]).is_err());
708        // The offsets carve out an element without a NUL terminator.
709        assert!(from_bytes(&ty, &[b'a', 0, 1, 2]).is_err());
710        // Fixed-element array with a partial element.
711        let au = Type::parse("au").unwrap();
712        assert!(from_bytes(&au, &[0; 6]).is_err());
713    }
714
715    #[test]
716    fn rejects_malformed_tuples() {
717        let empty = Type::parse("()").unwrap();
718        assert!(from_bytes(&empty, &[0]).is_ok());
719        assert!(from_bytes(&empty, &[1]).is_err());
720        assert!(from_bytes(&empty, &[]).is_err());
721        assert!(from_bytes(&empty, &[0, 0]).is_err());
722        // Fixed-size tuple with trailing garbage.
723        let uuu = Type::parse("(uuu)").unwrap();
724        assert!(from_bytes(&uuu, &[0; 13]).is_err());
725        // Variable tuple whose members do not reach the framing area.
726        let su = Type::parse("(su)").unwrap();
727        assert!(from_bytes(&su, b"a\0\0\0\x05\0\0\0\0\0\x02").is_err());
728    }
729
730    #[test]
731    fn rejects_malformed_variants() {
732        let v = Type::parse("v").unwrap();
733        assert!(from_bytes(&v, b"").is_err()); // empty
734        assert!(from_bytes(&v, b"ab").is_err()); // no separator
735        assert!(from_bytes(&v, b"a\0d").is_err()); // unsupported child type
736        assert!(from_bytes(&v, b"\0").is_err()); // empty signature
737    }
738
739    #[test]
740    fn rejects_variant_depth_bomb() {
741        // Build 129 nested variants by hand, because the serializer rejects
742        // values this deep. The bytes are the innermost byte, then one
743        // signature for each wrapper.
744        let ty = Type::parse("v").unwrap();
745        let mut bytes = vec![1u8, 0, b'y'];
746        for _ in 0..128 {
747            bytes.push(0);
748            bytes.push(b'v');
749        }
750        assert_eq!(from_bytes(&ty, &bytes), Err(Error::DepthExceeded));
751
752        // 128 nested variants sit exactly at the limit and round-trip. One
753        // more wrapper fails with the same error on the encode path.
754        let mut value = Value::variant(Type::Byte, Value::Byte(1));
755        for _ in 0..127 {
756            value = Value::variant(Type::Variant, value);
757        }
758        let ok = to_bytes(&ty, &value).unwrap();
759        assert_eq!(from_bytes(&ty, &ok).unwrap(), value);
760        let bomb = Value::variant(Type::Variant, value);
761        assert_eq!(to_bytes(&ty, &bomb), Err(Error::DepthExceeded));
762    }
763
764    /// The layout lookups of a parse, a check, and a serialization grow in
765    /// proportion to the depth of the value.
766    ///
767    /// Each container type keeps the alignment and the fixed size of the
768    /// types in it, so a lookup does not walk the type. The value is an array
769    /// of nested one-member tuples. Two times the depth gives at most two
770    /// times the lookups. A lookup that walks the type gives four times or
771    /// more.
772    #[test]
773    fn layout_lookups_grow_linearly_with_depth() {
774        fn value(depth: usize) -> (Type, Value) {
775            let sig = format!("a{}s{}", "(".repeat(depth), ")".repeat(depth));
776            let ty = Type::parse(&sig).unwrap();
777            let mut element = Value::Str("leaf".into());
778            for _ in 0..depth {
779                element = Value::Tuple(vec![element]);
780            }
781            (ty, Value::Array(vec![element; 4]))
782        }
783        fn lookups(run: impl FnOnce()) -> usize {
784            crate::ty::LAYOUT_CALLS.with(|calls| calls.set(0));
785            run();
786            crate::ty::LAYOUT_CALLS.with(std::cell::Cell::get)
787        }
788        let counts = |depth: usize| {
789            let (ty, value) = value(depth);
790            let bytes = to_bytes(&ty, &value).unwrap();
791            [
792                lookups(|| drop(to_bytes(&ty, &value).unwrap())),
793                lookups(|| drop(from_bytes(&ty, &bytes).unwrap())),
794                lookups(|| validate(&ty, &bytes).unwrap()),
795            ]
796        };
797        let (shallow, deep) = (counts(32), counts(64));
798        for (what, (shallow, deep)) in ["serialize", "parse", "check"]
799            .into_iter()
800            .zip(shallow.into_iter().zip(deep))
801        {
802            assert!(shallow > 0, "{what} looks up no layout");
803            assert!(
804                deep <= 2 * shallow,
805                "{what}: {deep} lookups at depth 64, {shallow} at depth 32"
806            );
807        }
808    }
809}