Skip to main content

ostrya_gvariant/
codec.rs

1//! The typed codec. It shares the offset and padding helpers of `de` and
2//! `ser` with the `Value` codec.
3
4use std::marker::PhantomData;
5
6use crate::de::{check_padding, exact, offset_size_for, read_offset, split_variant};
7use crate::ser::{choose_offset_size, write_offset};
8use crate::ty::align_up;
9use crate::{Error, Result, Type, Value};
10
11/// The type-level facts of a type that encodes as GVariant.
12///
13/// The facts are the signature, the alignment, and the fixed size.
14/// [`GvEncode`] and [`GvDecode`] both require this trait, so a type states
15/// the three constants once for both directions.
16///
17/// The framing of a traversal uses only [`ALIGNMENT`] and [`FIXED_SIZE`].
18/// These two constants compose in `const` context, so the read path parses
19/// no type signature.
20///
21/// # Implementations
22///
23/// This crate implements the traits for the scalar and container building
24/// blocks:
25///
26/// - `bool`, `u8`, `u32`, `u64`, `&str`, and `&[u8]` implement all three
27///   traits.
28/// - `String` and [`Slice`] implement [`GvType`] and [`GvEncode`].
29/// - [`ArrayIter`], [`Variant`], and [`VariantBytes`] implement all three
30///   traits.
31/// - A tuple of 2 to 9 members implements each trait that all of its members
32///   implement. A one-member tuple implements none of them.
33///
34/// The ostree object structs in `ostrya-core` implement the traits. These
35/// impls apply the value-level conventions: big-endian scalars,
36/// checksum-length checks, and sort-order checks.
37///
38/// [`ALIGNMENT`]: GvType::ALIGNMENT
39/// [`FIXED_SIZE`]: GvType::FIXED_SIZE
40pub trait GvType {
41    /// The GVariant type signature, or `""` for a container type.
42    ///
43    /// The impls for scalars, strings, byte arrays, and variants set it. The
44    /// object structs of `ostrya-core` set it too. The impls for tuples,
45    /// [`ArrayIter`], and [`Slice`] leave it empty, because their element
46    /// types give the signature. The encoder does not read it.
47    const SIGNATURE: &'static str = "";
48    /// The alignment of the serialized form, in bytes.
49    const ALIGNMENT: usize;
50    /// The serialized size, or `None` for a variable-size type.
51    const FIXED_SIZE: Option<usize>;
52}
53
54/// A type that writes itself as normal-form GVariant bytes.
55///
56/// [`encode`](GvEncode::encode) writes the bytes directly and builds no
57/// [`Value`] tree. The bytes equal the output of [`to_bytes`] for the same
58/// type and value. The tests in `tests/differential.rs` check this for each
59/// ostree object shape.
60///
61/// `encode` appends the value at the current end of `out`. A container impl
62/// pads each member to its alignment, so the top-level call needs only an
63/// empty or already-aligned buffer.
64///
65/// [`to_bytes`]: crate::to_bytes
66pub trait GvEncode: GvType {
67    /// Appends the normal-form bytes of `self` to `out`.
68    ///
69    /// # Errors
70    ///
71    /// - [`Error::InvalidValue`] if a `&str` or a `String` holds an interior
72    ///   NUL byte.
73    /// - For a tuple or a [`Slice`], the first error of a member.
74    ///
75    /// The other impls of this crate return no error.
76    fn encode(&self, out: &mut Vec<u8>) -> Result<()>;
77}
78
79/// A type that reads itself from normal-form GVariant bytes.
80///
81/// [`decode`](GvDecode::decode) reads the fields in place and builds no
82/// [`Value`] tree. A value that decodes encodes again to the input bytes,
83/// because the typed path shares the offset and padding helpers of
84/// [`from_bytes`] and [`to_bytes`].
85///
86/// The decode of an [`ArrayIter`] checks only the outer framing of the array.
87/// The iterator checks each element when it visits the element. A full drain
88/// of the iterator applies the same checks as [`from_bytes`].
89///
90/// # Allocation
91///
92/// A decode borrows from `data`:
93///
94/// - A string decodes as `&str`.
95/// - A byte array decodes as `&[u8]`.
96/// - An array decodes as [`ArrayIter`], a lazy iterator over the framing
97///   offsets.
98/// - A variant decodes as [`VariantBytes`], the borrowed child bytes and
99///   signature.
100///
101/// With these types, the traversal of a read-heavy object does no heap
102/// allocation. A dirtree walk and an xattr scan are such traversals. The test
103/// `tests/alloc.rs` checks this property.
104///
105/// [`Variant`] is the exception. Its decode parses the child into a [`Value`],
106/// and this allocates.
107///
108/// # Examples
109///
110/// ```
111/// use ostrya_gvariant::{ArrayIter, GvDecode, Slice, encode_to_vec};
112///
113/// let bytes = encode_to_vec(&(7u32, Slice(&["a", "bc"])))?;
114/// let (n, names) = <(u32, ArrayIter<&str>)>::decode(&bytes)?;
115/// assert_eq!(n, 7);
116/// let names: Vec<&str> = names.collect::<Result<_, _>>()?;
117/// assert_eq!(names, ["a", "bc"]);
118/// # Ok::<(), ostrya_gvariant::Error>(())
119/// ```
120///
121/// [`from_bytes`]: crate::from_bytes
122/// [`to_bytes`]: crate::to_bytes
123pub trait GvDecode<'a>: GvType + Sized {
124    /// Decodes a value from the slice that covers exactly its serialized form.
125    ///
126    /// # Errors
127    ///
128    /// - [`Error::NotNormal`] if `data` is not in normal form:
129    ///   - a scalar of the wrong size, or a boolean that is not 0 or 1
130    ///   - a string that is not NUL-terminated, that holds an interior NUL
131    ///     byte, or that is not UTF-8
132    ///   - an array or a tuple with a wrong size or nonzero padding
133    ///   - framing offsets out of order or out of bounds, or an offset size
134    ///     that is not the smallest that fits
135    ///   - a variant with no type separator, or with a signature that is not
136    ///     UTF-8 or not a valid type
137    /// - [`Error::DepthExceeded`] if the child of a [`Variant`] exceeds the
138    ///   [depth limit](crate::from_bytes#depth-limit) of [`from_bytes`].
139    ///
140    /// An [`ArrayIter`] returns the error of an element from
141    /// [`next`](Iterator::next), when it visits that element.
142    ///
143    /// [`from_bytes`]: crate::from_bytes
144    fn decode(data: &'a [u8]) -> Result<Self>;
145}
146
147/// Encodes a top-level value into a new byte vector.
148///
149/// # Errors
150///
151/// The errors of [`GvEncode::encode`].
152pub fn encode_to_vec<T: GvEncode>(value: &T) -> Result<Vec<u8>> {
153    let mut out = Vec::new();
154    value.encode(&mut out)?;
155    Ok(out)
156}
157
158// -- scalar leaves ---------------------------------------------------------
159
160impl GvType for bool {
161    const SIGNATURE: &'static str = "b";
162    const ALIGNMENT: usize = 1;
163    const FIXED_SIZE: Option<usize> = Some(1);
164}
165
166impl GvEncode for bool {
167    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
168        out.push(*self as u8);
169        Ok(())
170    }
171}
172
173impl<'a> GvDecode<'a> for bool {
174    fn decode(data: &'a [u8]) -> Result<Self> {
175        match exact::<1>(data)?[0] {
176            0 => Ok(false),
177            1 => Ok(true),
178            _ => Err(Error::NotNormal("boolean is not 0 or 1")),
179        }
180    }
181}
182
183impl GvType for u8 {
184    const SIGNATURE: &'static str = "y";
185    const ALIGNMENT: usize = 1;
186    const FIXED_SIZE: Option<usize> = Some(1);
187}
188
189impl GvEncode for u8 {
190    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
191        out.push(*self);
192        Ok(())
193    }
194}
195
196impl<'a> GvDecode<'a> for u8 {
197    fn decode(data: &'a [u8]) -> Result<Self> {
198        Ok(exact::<1>(data)?[0])
199    }
200}
201
202impl GvType for u32 {
203    const SIGNATURE: &'static str = "u";
204    const ALIGNMENT: usize = 4;
205    const FIXED_SIZE: Option<usize> = Some(4);
206}
207
208impl GvEncode for u32 {
209    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
210        out.extend_from_slice(&self.to_le_bytes());
211        Ok(())
212    }
213}
214
215impl<'a> GvDecode<'a> for u32 {
216    fn decode(data: &'a [u8]) -> Result<Self> {
217        Ok(u32::from_le_bytes(exact(data)?))
218    }
219}
220
221impl GvType for u64 {
222    const SIGNATURE: &'static str = "t";
223    const ALIGNMENT: usize = 8;
224    const FIXED_SIZE: Option<usize> = Some(8);
225}
226
227impl GvEncode for u64 {
228    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
229        out.extend_from_slice(&self.to_le_bytes());
230        Ok(())
231    }
232}
233
234impl<'a> GvDecode<'a> for u64 {
235    fn decode(data: &'a [u8]) -> Result<Self> {
236        Ok(u64::from_le_bytes(exact(data)?))
237    }
238}
239
240// -- string and byte array -------------------------------------------------
241
242impl GvType for &str {
243    const SIGNATURE: &'static str = "s";
244    const ALIGNMENT: usize = 1;
245    const FIXED_SIZE: Option<usize> = None;
246}
247
248impl GvEncode for &str {
249    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
250        let s: &str = self;
251        if s.as_bytes().contains(&0) {
252            return Err(Error::InvalidValue("string contains an interior NUL byte"));
253        }
254        out.extend_from_slice(s.as_bytes());
255        out.push(0);
256        Ok(())
257    }
258}
259
260impl<'a> GvDecode<'a> for &'a str {
261    fn decode(data: &'a [u8]) -> Result<Self> {
262        let Some((&0, content)) = data.split_last() else {
263            return Err(Error::NotNormal("string is not NUL-terminated"));
264        };
265        if content.contains(&0) {
266            return Err(Error::NotNormal("string contains an interior NUL byte"));
267        }
268        std::str::from_utf8(content).map_err(|_| Error::NotNormal("string is not valid UTF-8"))
269    }
270}
271
272impl GvType for String {
273    const SIGNATURE: &'static str = "s";
274    const ALIGNMENT: usize = 1;
275    const FIXED_SIZE: Option<usize> = None;
276}
277
278/// Writes the same bytes as `&str`.
279///
280/// An owned string can be a tuple or array member. An owned value, for
281/// example a dirtree entry name, needs no reborrow into a temporary slice of
282/// references.
283impl GvEncode for String {
284    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
285        self.as_str().encode(out)
286    }
287}
288
289impl GvType for &[u8] {
290    const SIGNATURE: &'static str = "ay";
291    const ALIGNMENT: usize = 1;
292    const FIXED_SIZE: Option<usize> = None;
293}
294
295impl GvEncode for &[u8] {
296    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
297        out.extend_from_slice(self);
298        Ok(())
299    }
300}
301
302impl<'a> GvDecode<'a> for &'a [u8] {
303    fn decode(data: &'a [u8]) -> Result<Self> {
304        Ok(data)
305    }
306}
307
308// -- arrays ----------------------------------------------------------------
309
310/// A lazy reader over the elements of a serialized array.
311///
312/// It holds only the backing slice and a cursor, so iteration allocates
313/// nothing.
314#[derive(Clone, Copy)]
315pub(crate) struct ArrayReader<'a> {
316    data: &'a [u8],
317    elem_alignment: usize,
318    /// `Some` for a fixed-size element type.
319    ///
320    /// If `Some`, the elements pack back to back. If `None`, framing offsets
321    /// delimit the elements.
322    elem_size: Option<usize>,
323    /// The framing-offset size, for variable-element arrays only.
324    z: usize,
325    /// The end of the element data, where the framing area starts.
326    ///
327    /// It applies to variable-element arrays only.
328    data_end: usize,
329    /// Element count.
330    n: usize,
331    /// Next element index.
332    i: usize,
333    /// The current data position, which is the cursor for variable elements.
334    pos: usize,
335}
336
337impl<'a> ArrayReader<'a> {
338    pub(crate) fn new(
339        data: &'a [u8],
340        elem_alignment: usize,
341        elem_fixed_size: Option<usize>,
342    ) -> Result<Self> {
343        let mut r = ArrayReader {
344            data,
345            elem_alignment,
346            elem_size: elem_fixed_size,
347            z: 0,
348            data_end: 0,
349            n: 0,
350            i: 0,
351            pos: 0,
352        };
353        if data.is_empty() {
354            return Ok(r);
355        }
356        if let Some(size) = elem_fixed_size {
357            if !data.len().is_multiple_of(size) {
358                return Err(Error::NotNormal(
359                    "array size is not a multiple of the element size",
360                ));
361            }
362            r.n = data.len() / size;
363            return Ok(r);
364        }
365        let z = offset_size_for(data.len());
366        if data.len() < z {
367            return Err(Error::NotNormal("array is too small for its framing"));
368        }
369        let data_end = read_offset(&data[data.len() - z..], z);
370        if data_end > data.len() - z {
371            return Err(Error::NotNormal("array framing offset is out of bounds"));
372        }
373        let offsets_len = data.len() - data_end;
374        if !offsets_len.is_multiple_of(z) {
375            return Err(Error::NotNormal("array framing area has a partial offset"));
376        }
377        r.z = z;
378        r.data_end = data_end;
379        r.n = offsets_len / z;
380        // Normal form uses the smallest offset size that fits the element data
381        // plus its own offsets. A wider size re-encodes to fewer bytes, so
382        // this check rejects a buffer that does not re-encode to its bytes.
383        if choose_offset_size(data_end, r.n) != z {
384            return Err(Error::NotNormal(
385                "array framing offset size is not normal-form",
386            ));
387        }
388        Ok(r)
389    }
390
391    /// The full serialized array slice, with the framing area.
392    fn bytes(&self) -> &'a [u8] {
393        self.data
394    }
395
396    /// The element count carved from the framing.
397    pub(crate) fn len(&self) -> usize {
398        self.n
399    }
400
401    pub(crate) fn next_slice(&mut self) -> Option<Result<&'a [u8]>> {
402        if self.i >= self.n {
403            return None;
404        }
405        let idx = self.i;
406        self.i += 1;
407        if let Some(size) = self.elem_size {
408            let start = idx * size;
409            return Some(Ok(&self.data[start..start + size]));
410        }
411        let off_at = self.data_end + idx * self.z;
412        let end = read_offset(&self.data[off_at..off_at + self.z], self.z);
413        let start = align_up(self.pos, self.elem_alignment);
414        if start > end || end > self.data_end {
415            // A framing error leaves `pos` unusable. Fuse the reader.
416            self.i = self.n;
417            return Some(Err(Error::NotNormal(
418                "array element offsets are out of order",
419            )));
420        }
421        if let Err(e) = check_padding(&self.data[self.pos..start]) {
422            self.i = self.n;
423            return Some(Err(e));
424        }
425        let slice = &self.data[start..end];
426        self.pos = end;
427        Some(Ok(slice))
428    }
429}
430
431/// A lazy iterator over the elements of a serialized array.
432///
433/// `ArrayIter` borrows the source buffer and yields `Result<E>`. It decodes
434/// one element in each step, so the normal-form check of an element runs when
435/// the iterator visits it. It is `Copy`, so a caller can iterate it again from
436/// the start.
437///
438/// A framing error fuses the iterator. The iterator yields the `Err` once,
439/// and every later call returns `None`.
440///
441/// Its [`SIGNATURE`](GvType::SIGNATURE) is `""`, because the signature of an
442/// array comes from its element type.
443#[derive(Clone, Copy)]
444pub struct ArrayIter<'a, E> {
445    reader: ArrayReader<'a>,
446    _marker: PhantomData<fn() -> E>,
447}
448
449impl<'a, E: GvDecode<'a>> Iterator for ArrayIter<'a, E> {
450    type Item = Result<E>;
451    fn next(&mut self) -> Option<Result<E>> {
452        match self.reader.next_slice()? {
453            Ok(slice) => Some(E::decode(slice)),
454            Err(e) => Some(Err(e)),
455        }
456    }
457}
458
459impl<'a, E: GvType> GvType for ArrayIter<'a, E> {
460    const ALIGNMENT: usize = E::ALIGNMENT;
461    const FIXED_SIZE: Option<usize> = None;
462}
463
464impl<'a, E: GvDecode<'a>> GvDecode<'a> for ArrayIter<'a, E> {
465    fn decode(data: &'a [u8]) -> Result<Self> {
466        Ok(ArrayIter {
467            reader: ArrayReader::new(data, E::ALIGNMENT, E::FIXED_SIZE)?,
468            _marker: PhantomData,
469        })
470    }
471}
472
473impl<'a, E: GvDecode<'a>> GvEncode for ArrayIter<'a, E> {
474    /// Writes the bytes of the borrowed array again.
475    ///
476    /// The backing slice of the reader is already in normal form. At the same
477    /// alignment, the slice gives its original bytes.
478    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
479        out.extend_from_slice(self.reader.bytes());
480        Ok(())
481    }
482}
483
484/// An array to encode from a Rust slice of encodable elements.
485///
486/// Its [`SIGNATURE`](GvType::SIGNATURE) is `""`, because the signature of an
487/// array comes from its element type.
488pub struct Slice<'s, E>(pub &'s [E]);
489
490impl<'s, E: GvEncode> GvType for Slice<'s, E> {
491    const ALIGNMENT: usize = E::ALIGNMENT;
492    const FIXED_SIZE: Option<usize> = None;
493}
494
495impl<'s, E: GvEncode> GvEncode for Slice<'s, E> {
496    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
497        write_array(
498            out,
499            E::ALIGNMENT,
500            E::FIXED_SIZE.is_some(),
501            self.0.len(),
502            |out, i| self.0[i].encode(out),
503        )
504    }
505}
506
507/// Appends `n` array elements with normal-form framing to `out`.
508///
509/// `write_elem(out, i)` appends element `i`. This function writes the padding
510/// and the framing-offset area. The framing is the same as the framing that
511/// [`to_bytes`] writes.
512///
513/// The other parameters describe the element type:
514///
515/// - `elem_alignment`: the alignment of the element type, in bytes. If
516///   `elem_fixed` is `false`, the function pads to it before each element.
517/// - `elem_fixed`: `true` if the element type has a fixed size. Fixed-size
518///   elements pack back to back with no padding and no framing offsets.
519/// - `n`: the number of elements.
520///
521/// A caller with its own element storage can write the array framing with
522/// this function. An example is the owned field arrays of an ostree object.
523/// The caller needs no collected element references.
524///
525/// # Errors
526///
527/// The first error that `write_elem` returns, unchanged. The function has no
528/// error of its own.
529///
530/// [`to_bytes`]: crate::to_bytes
531pub fn write_array<F>(
532    out: &mut Vec<u8>,
533    elem_alignment: usize,
534    elem_fixed: bool,
535    n: usize,
536    mut write_elem: F,
537) -> Result<()>
538where
539    F: FnMut(&mut Vec<u8>, usize) -> Result<()>,
540{
541    let start = out.len();
542    if elem_fixed {
543        // A fixed size is a multiple of the element alignment, so the
544        // elements pack back to back with no padding and no framing offsets.
545        for i in 0..n {
546            write_elem(out, i)?;
547        }
548        return Ok(());
549    }
550    let mut ends = Vec::with_capacity(n);
551    for i in 0..n {
552        pad_to(out, elem_alignment);
553        write_elem(out, i)?;
554        ends.push(out.len() - start);
555    }
556    if !ends.is_empty() {
557        let z = choose_offset_size(out.len() - start, ends.len());
558        for &end in &ends {
559            write_offset(out, end, z);
560        }
561    }
562    Ok(())
563}
564
565// -- variant ---------------------------------------------------------------
566
567/// A decoded variant that holds the type and the value of its child.
568///
569/// A variant carries a dynamic child type, so [`decode`](GvDecode::decode)
570/// parses the child into a [`Value`] once and keeps it. [`Variant::value`]
571/// borrows that value. It walks no bytes again and clones nothing.
572///
573/// `Variant` is the one building block that allocates on decode. Variants
574/// occur only inside `a{sv}` metadata, so a dirtree walk or an xattr scan does
575/// not decode one.
576///
577/// A `Variant` also keeps the borrowed child bytes and signature.
578/// [`encode`](GvEncode::encode) writes them again, so the output equals the
579/// input byte for byte. The encode builds no signature string.
580pub struct Variant<'a> {
581    ty: Type,
582    child: &'a [u8],
583    signature: &'a [u8],
584    value: Value,
585}
586
587impl<'a> Variant<'a> {
588    /// Returns the type of the child.
589    pub fn ty(&self) -> &Type {
590        &self.ty
591    }
592
593    /// Returns the child as a [`Value`] that [`decode`](GvDecode::decode)
594    /// parsed once.
595    pub fn value(&self) -> &Value {
596        &self.value
597    }
598}
599
600impl<'a> GvType for Variant<'a> {
601    const SIGNATURE: &'static str = "v";
602    const ALIGNMENT: usize = 8;
603    const FIXED_SIZE: Option<usize> = None;
604}
605
606impl<'a> GvDecode<'a> for Variant<'a> {
607    fn decode(data: &'a [u8]) -> Result<Self> {
608        let (child, signature, ty) = split_variant(data)?;
609        // Walk the child once, as `from_bytes` does for `v`, and keep the value.
610        let value = crate::from_bytes(&ty, child)?;
611        Ok(Variant {
612            ty,
613            child,
614            signature,
615            value,
616        })
617    }
618}
619
620impl<'a> GvEncode for Variant<'a> {
621    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
622        out.extend_from_slice(self.child);
623        out.push(0);
624        out.extend_from_slice(self.signature);
625        Ok(())
626    }
627}
628
629/// A variant read in place, as borrowed child bytes and signature.
630///
631/// [`decode`](GvDecode::decode) splits the variant at its type separator and
632/// checks that the signature is UTF-8. It parses neither the signature nor
633/// the child, so it allocates nothing.
634///
635/// If a caller needs a checked child, the caller runs [`validate`] over the
636/// whole serialized value first.
637///
638/// [`validate`]: crate::validate
639#[derive(Clone, Copy)]
640pub struct VariantBytes<'a> {
641    child: &'a [u8],
642    signature: &'a str,
643}
644
645impl<'a> VariantBytes<'a> {
646    /// Returns the serialized child.
647    pub fn child(&self) -> &'a [u8] {
648        self.child
649    }
650
651    /// Returns the type signature of the child, as the variant spells it.
652    ///
653    /// The decode checks only that the signature is UTF-8. It does not parse
654    /// the signature, so the signature can be an invalid type string.
655    pub fn signature(&self) -> &'a str {
656        self.signature
657    }
658}
659
660impl<'a> GvType for VariantBytes<'a> {
661    const SIGNATURE: &'static str = "v";
662    const ALIGNMENT: usize = 8;
663    const FIXED_SIZE: Option<usize> = None;
664}
665
666impl<'a> GvEncode for VariantBytes<'a> {
667    /// Writes the child bytes, the type separator, and the signature again.
668    ///
669    /// The output equals the bytes that decode read.
670    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
671        out.extend_from_slice(self.child);
672        out.push(0);
673        out.extend_from_slice(self.signature.as_bytes());
674        Ok(())
675    }
676}
677
678impl<'a> GvDecode<'a> for VariantBytes<'a> {
679    fn decode(data: &'a [u8]) -> Result<Self> {
680        let Some(sep) = data.iter().rposition(|&b| b == 0) else {
681            return Err(Error::NotNormal("variant lacks a type separator"));
682        };
683        let signature = std::str::from_utf8(&data[sep + 1..])
684            .map_err(|_| Error::NotNormal("variant type signature is not UTF-8"))?;
685        Ok(VariantBytes {
686            child: &data[..sep],
687            signature,
688        })
689    }
690}
691
692// -- tuples ----------------------------------------------------------------
693
694/// The alignment of a container: the greatest member alignment, at least 1.
695pub(crate) const fn max_align(aligns: &[usize]) -> usize {
696    let mut m = 1;
697    let mut i = 0;
698    while i < aligns.len() {
699        if aligns[i] > m {
700            m = aligns[i];
701        }
702        i += 1;
703    }
704    m
705}
706
707/// The fixed size of a struct from the `(alignment, fixed_size)` of each
708/// member.
709///
710/// If any member is variable-size, the result is `None`. The result matches
711/// `Type::fixed_size`.
712pub(crate) const fn struct_fixed_size(
713    members: &[(usize, Option<usize>)],
714    whole_align: usize,
715) -> Option<usize> {
716    if members.is_empty() {
717        return Some(1);
718    }
719    let mut size = 0;
720    let mut i = 0;
721    while i < members.len() {
722        let (align, fixed) = members[i];
723        match fixed {
724            Some(f) => size = align_up(size, align) + f,
725            None => return None,
726        }
727        i += 1;
728    }
729    Some(align_up(size, whole_align))
730}
731
732/// A cursor that splits a serialized tuple or dict-entry body into member
733/// slices.
734///
735/// It applies the same framing and padding checks as `from_bytes`.
736pub(crate) struct TupleReader<'a> {
737    data: &'a [u8],
738    framing_start: usize,
739    z: usize,
740    pos: usize,
741    offset_index: usize,
742    fixed: bool,
743}
744
745impl<'a> TupleReader<'a> {
746    pub(crate) fn new(data: &'a [u8], n_offsets: usize, fixed_size: Option<usize>) -> Result<Self> {
747        if let Some(size) = fixed_size
748            && data.len() != size
749        {
750            return Err(Error::NotNormal("fixed-size tuple has the wrong size"));
751        }
752        let z = offset_size_for(data.len());
753        let framing_start = data
754            .len()
755            .checked_sub(n_offsets * z)
756            .ok_or(Error::NotNormal("tuple is too small for its framing"))?;
757        // If framing offsets are present, the offset size must be the size
758        // that the encoder picks for this member area. A wider size re-encodes
759        // to fewer bytes, so this check rejects it. A tuple carries no offsets
760        // if all of its members are fixed-size, or if its last member is the
761        // only variable-size member. For such a tuple, `z` has no effect.
762        if n_offsets > 0 && choose_offset_size(framing_start, n_offsets) != z {
763            return Err(Error::NotNormal(
764                "tuple framing offset size is not normal-form",
765            ));
766        }
767        Ok(TupleReader {
768            data,
769            framing_start,
770            z,
771            pos: 0,
772            offset_index: 0,
773            fixed: fixed_size.is_some(),
774        })
775    }
776
777    pub(crate) fn field(
778        &mut self,
779        alignment: usize,
780        fixed_size: Option<usize>,
781        is_last: bool,
782    ) -> Result<&'a [u8]> {
783        let start = align_up(self.pos, alignment);
784        let end = if let Some(size) = fixed_size {
785            start.checked_add(size)
786        } else if is_last {
787            Some(self.framing_start)
788        } else {
789            let at = self.data.len() - (self.offset_index + 1) * self.z;
790            self.offset_index += 1;
791            Some(read_offset(&self.data[at..at + self.z], self.z))
792        };
793        let end = end.ok_or(Error::NotNormal("tuple member offset overflows"))?;
794        if start > end || end > self.framing_start {
795            return Err(Error::NotNormal("tuple member offsets are out of order"));
796        }
797        check_padding(&self.data[self.pos..start])?;
798        let slice = &self.data[start..end];
799        self.pos = end;
800        Ok(slice)
801    }
802
803    pub(crate) fn finish(self) -> Result<()> {
804        if self.fixed {
805            check_padding(&self.data[self.pos..])
806        } else if self.pos != self.framing_start {
807            Err(Error::NotNormal("tuple members do not fill the tuple"))
808        } else {
809            Ok(())
810        }
811    }
812}
813
814/// A writer that appends tuple members with correct alignment, padding, and
815/// framing offsets.
816///
817/// It writes the same bytes as `to_bytes`.
818pub(crate) struct TupleWriter<'b> {
819    out: &'b mut Vec<u8>,
820    start: usize,
821    /// The end offsets of the variable-size members other than the last, in
822    /// member order.
823    ///
824    /// [`finish`](Self::finish) writes them in reverse order.
825    offsets: Vec<usize>,
826}
827
828impl<'b> TupleWriter<'b> {
829    /// Creates a writer that appends members at the end of `out`.
830    ///
831    /// The offsets buffer starts empty and grows only for variable-size
832    /// members, so a fully fixed-size tuple allocates nothing.
833    pub(crate) fn new(out: &'b mut Vec<u8>) -> Self {
834        let start = out.len();
835        TupleWriter {
836            out,
837            start,
838            offsets: Vec::new(),
839        }
840    }
841
842    /// Appends a member with a runtime alignment and fixed size.
843    ///
844    /// `write` encodes the member. The framing rule exists here once for the
845    /// typed encoder and the `Value` encoder.
846    pub(crate) fn field_dyn(
847        &mut self,
848        alignment: usize,
849        fixed_size: Option<usize>,
850        is_last: bool,
851        write: impl FnOnce(&mut Vec<u8>) -> Result<()>,
852    ) -> Result<()> {
853        pad_to(self.out, alignment);
854        write(self.out)?;
855        if !is_last && fixed_size.is_none() {
856            self.offsets.push(self.out.len() - self.start);
857        }
858        Ok(())
859    }
860
861    pub(crate) fn field<T: GvEncode>(&mut self, value: &T, is_last: bool) -> Result<()> {
862        self.field_dyn(T::ALIGNMENT, T::FIXED_SIZE, is_last, |out| {
863            value.encode(out)
864        })
865    }
866
867    pub(crate) fn finish(self, fixed_size: Option<usize>) {
868        if let Some(size) = fixed_size {
869            // All members fixed: pad the end to the tuple alignment.
870            self.out.resize(self.start + size, 0);
871        } else if !self.offsets.is_empty() {
872            let z = choose_offset_size(self.out.len() - self.start, self.offsets.len());
873            for &end in self.offsets.iter().rev() {
874                write_offset(self.out, end, z);
875            }
876        }
877    }
878}
879
880pub(crate) fn pad_to(out: &mut Vec<u8>, alignment: usize) {
881    out.resize(align_up(out.len(), alignment), 0);
882}
883
884macro_rules! impl_tuple {
885    ($($T:ident $idx:tt),+ ; $Last:ident $last_idx:tt) => {
886        impl<$($T: GvType,)+ $Last: GvType> GvType for ($($T,)+ $Last,) {
887            const ALIGNMENT: usize = max_align(&[$($T::ALIGNMENT,)+ $Last::ALIGNMENT]);
888            const FIXED_SIZE: Option<usize> = struct_fixed_size(
889                &[$(($T::ALIGNMENT, $T::FIXED_SIZE),)+ ($Last::ALIGNMENT, $Last::FIXED_SIZE)],
890                max_align(&[$($T::ALIGNMENT,)+ $Last::ALIGNMENT]),
891            );
892        }
893
894        impl<'a, $($T: GvDecode<'a>,)+ $Last: GvDecode<'a>> GvDecode<'a> for ($($T,)+ $Last,) {
895            fn decode(data: &'a [u8]) -> Result<Self> {
896                let n_offsets = [$($T::FIXED_SIZE.is_none(),)+]
897                    .into_iter()
898                    .filter(|&v| v)
899                    .count();
900                let mut r = TupleReader::new(data, n_offsets, <Self as GvType>::FIXED_SIZE)?;
901                let value = (
902                    $( <$T as GvDecode<'a>>::decode(r.field($T::ALIGNMENT, $T::FIXED_SIZE, false)?)?, )+
903                    <$Last as GvDecode<'a>>::decode(r.field($Last::ALIGNMENT, $Last::FIXED_SIZE, true)?)?,
904                );
905                r.finish()?;
906                Ok(value)
907            }
908        }
909
910        impl<$($T: GvEncode,)+ $Last: GvEncode> GvEncode for ($($T,)+ $Last,) {
911            fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
912                let mut w = TupleWriter::new(out);
913                $( w.field(&self.$idx, false)?; )+
914                w.field(&self.$last_idx, true)?;
915                w.finish(<Self as GvType>::FIXED_SIZE);
916                Ok(())
917            }
918        }
919    };
920}
921
922impl_tuple!(A 0 ; B 1);
923impl_tuple!(A 0, B 1 ; C 2);
924impl_tuple!(A 0, B 1, C 2 ; D 3);
925impl_tuple!(A 0, B 1, C 2, D 3 ; E 4);
926impl_tuple!(A 0, B 1, C 2, D 3, E 4 ; F 5);
927impl_tuple!(A 0, B 1, C 2, D 3, E 4, F 5 ; G 6);
928impl_tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6 ; H 7);
929impl_tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6, H 7 ; I 8);
930
931#[cfg(test)]
932mod tests {
933    use super::*;
934    use crate::{from_bytes, to_bytes};
935
936    /// The `(uuua(ayay))` dirmeta shape as a borrowed view.
937    type DirMetaView<'a> = (u32, u32, u32, ArrayIter<'a, (&'a [u8], &'a [u8])>);
938
939    /// Round-trips a typed value against `to_bytes`/`from_bytes` for a signature.
940    ///
941    /// The typed encoding must equal the `Value` encoding. The `Value` decode
942    /// of those bytes must give `expected_value`. The typed decode must
943    /// re-encode to the same bytes.
944    ///
945    /// The caller supplies the decode-and-re-encode step as `decode_reencode`,
946    /// so the borrowed view binds to the buffer that this function makes. A
947    /// borrowed type such as `&str` cannot decode into a fixed lifetime that
948    /// the caller chooses, so the closure decodes and re-encodes in one call.
949    fn check<T, F>(sig: &str, value: &T, expected_value: &Value, decode_reencode: F)
950    where
951        T: GvEncode,
952        F: Fn(&[u8]) -> Result<Vec<u8>>,
953    {
954        let ty = Type::parse(sig).unwrap();
955        let typed = encode_to_vec(value).unwrap();
956        let from_value = to_bytes(&ty, expected_value).unwrap();
957        assert_eq!(
958            typed, from_value,
959            "typed encode matches Value encode for {sig}"
960        );
961        assert_eq!(
962            from_bytes(&ty, &typed).unwrap(),
963            *expected_value,
964            "Value decode of typed bytes for {sig}"
965        );
966        assert_eq!(
967            decode_reencode(&typed).unwrap(),
968            typed,
969            "typed decode re-encodes identically for {sig}"
970        );
971    }
972
973    #[test]
974    fn scalars_match_value_path() {
975        check("y", &0xabu8, &Value::Byte(0xab), |b: &[u8]| {
976            encode_to_vec(&<u8>::decode(b)?)
977        });
978        check("b", &true, &Value::Bool(true), |b: &[u8]| {
979            encode_to_vec(&<bool>::decode(b)?)
980        });
981        check(
982            "u",
983            &0x0102_0304u32,
984            &Value::U32(0x0102_0304),
985            |b: &[u8]| encode_to_vec(&<u32>::decode(b)?),
986        );
987        check(
988            "t",
989            &0x0102_0304_0506_0708u64,
990            &Value::U64(0x0102_0304_0506_0708),
991            |b: &[u8]| encode_to_vec(&<u64>::decode(b)?),
992        );
993        check("s", &"hi", &Value::Str("hi".into()), |b: &[u8]| {
994            encode_to_vec(&<&str>::decode(b)?)
995        });
996        let bytes: &[u8] = &[0, 1, 2, 0, 4];
997        check(
998            "ay",
999            &bytes,
1000            &Value::Bytes(vec![0, 1, 2, 0, 4]),
1001            |b: &[u8]| encode_to_vec(&<&[u8]>::decode(b)?),
1002        );
1003    }
1004
1005    #[test]
1006    fn dirmeta_shape_round_trips() {
1007        // (uuua(ayay)) with a single xattr entry.
1008        let xattr: (&[u8], &[u8]) = (b"user.foo", b"bar");
1009        let value = (
1010            0u32,
1011            0u32,
1012            0o40755u32.swap_bytes(),
1013            Slice(std::slice::from_ref(&xattr)),
1014        );
1015        let ty = Type::parse("(uuua(ayay))").unwrap();
1016        let typed = encode_to_vec(&value).unwrap();
1017        let expected = Value::Tuple(vec![
1018            Value::U32(0),
1019            Value::U32(0),
1020            Value::U32(0o40755u32.swap_bytes()),
1021            Value::Array(vec![Value::Tuple(vec![
1022                Value::Bytes(b"user.foo".to_vec()),
1023                Value::Bytes(b"bar".to_vec()),
1024            ])]),
1025        ]);
1026        assert_eq!(typed, to_bytes(&ty, &expected).unwrap());
1027
1028        // Decode borrow-first and re-encode to identical bytes.
1029        let decoded = <DirMetaView as GvDecode>::decode(&typed).unwrap();
1030        assert_eq!(decoded.0, 0);
1031        assert_eq!(decoded.2, 0o40755u32.swap_bytes());
1032        let xattrs: Vec<(&[u8], &[u8])> = decoded.3.map(Result::unwrap).collect();
1033        assert_eq!(xattrs, [(b"user.foo".as_slice(), b"bar".as_slice())]);
1034        assert_eq!(encode_to_vec(&decoded).unwrap(), typed);
1035    }
1036
1037    #[test]
1038    fn variable_tuple_with_fixed_final_member() {
1039        // (su): the string needs a framing offset. The trailing u32 needs none.
1040        let value: (&str, u32) = ("abc", 5);
1041        check(
1042            "(su)",
1043            &value,
1044            &Value::Tuple(vec!["abc".into(), Value::U32(5)]),
1045            |b: &[u8]| encode_to_vec(&<(&str, u32)>::decode(b)?),
1046        );
1047    }
1048
1049    #[test]
1050    fn fixed_element_array_packs_without_offsets() {
1051        let items = [(1u32, 2u32, 3u32), (4, 5, 6)];
1052        let ty = Type::parse("a(uuu)").unwrap();
1053        let typed = encode_to_vec(&Slice(&items)).unwrap();
1054        let expected = Value::Array(vec![
1055            Value::Tuple(vec![Value::U32(1), Value::U32(2), Value::U32(3)]),
1056            Value::Tuple(vec![Value::U32(4), Value::U32(5), Value::U32(6)]),
1057        ]);
1058        assert_eq!(typed, to_bytes(&ty, &expected).unwrap());
1059        let decoded = <ArrayIter<(u32, u32, u32)> as GvDecode>::decode(&typed).unwrap();
1060        let got: Vec<(u32, u32, u32)> = decoded.map(Result::unwrap).collect();
1061        assert_eq!(got, items);
1062    }
1063
1064    #[test]
1065    fn variant_round_trips_via_value() {
1066        // A dict entry {sv} with a string value. It is the a{sv} building block.
1067        let child = to_bytes(&Type::parse("s").unwrap(), &Value::Str("1".into())).unwrap();
1068        let mut variant_bytes = child.clone();
1069        variant_bytes.push(0);
1070        variant_bytes.extend_from_slice(b"s");
1071        let variant = Variant::decode(&variant_bytes).unwrap();
1072        assert_eq!(variant.ty(), &Type::Str);
1073        assert_eq!(variant.value(), &Value::Str("1".into()));
1074        assert_eq!(encode_to_vec(&variant).unwrap(), variant_bytes);
1075
1076        let entry: (&str, Variant) = ("version", variant);
1077        let ty = Type::parse("{sv}").unwrap();
1078        let expected = Value::Tuple(vec![
1079            "version".into(),
1080            Value::variant(Type::Str, "1".into()),
1081        ]);
1082        assert_eq!(
1083            encode_to_vec(&entry).unwrap(),
1084            to_bytes(&ty, &expected).unwrap()
1085        );
1086    }
1087
1088    /// An `a{sv}` read as `(&str, VariantBytes)` entries gives each key, the
1089    /// child bytes, and the child signature of each value, in order.
1090    #[test]
1091    fn variant_bytes_read_a_dict_in_place() {
1092        let ty = Type::parse("a{sv}").unwrap();
1093        let dict = Value::Array(vec![
1094            Value::Tuple(vec!["a".into(), Value::variant(Type::Str, "text".into())]),
1095            Value::Tuple(vec![
1096                "b".into(),
1097                Value::variant(
1098                    Type::parse("aay").unwrap(),
1099                    Value::Array(vec![Value::Bytes(b"xy".to_vec())]),
1100                ),
1101            ]),
1102        ]);
1103        let bytes = to_bytes(&ty, &dict).unwrap();
1104        let entries: Vec<(&str, VariantBytes)> =
1105            <ArrayIter<(&str, VariantBytes)> as GvDecode>::decode(&bytes)
1106                .unwrap()
1107                .map(Result::unwrap)
1108                .collect();
1109        assert_eq!(entries.len(), 2);
1110        assert_eq!(entries[0].0, "a");
1111        assert_eq!(entries[0].1.signature(), "s");
1112        assert_eq!(entries[0].1.child(), b"text\0");
1113        assert_eq!(entries[1].0, "b");
1114        assert_eq!(entries[1].1.signature(), "aay");
1115        assert_eq!(
1116            from_bytes(&Type::parse("aay").unwrap(), entries[1].1.child()).unwrap(),
1117            Value::Array(vec![Value::Bytes(b"xy".to_vec())])
1118        );
1119        assert_eq!(
1120            VariantBytes::decode(b"no separator").err(),
1121            Some(Error::NotNormal("variant lacks a type separator"))
1122        );
1123    }
1124
1125    /// The entries of an `a{sv}`, read and written again, give the dict bytes.
1126    ///
1127    /// The test reads the entries as `(&str, VariantBytes)` and writes them
1128    /// again with [`write_array`]. One variant encodes to the bytes that
1129    /// decode read.
1130    #[test]
1131    fn variant_bytes_encode_the_bytes_they_were_read_from() {
1132        let ty = Type::parse("a{sv}").unwrap();
1133        let dict = Value::Array(vec![
1134            Value::Tuple(vec!["a".into(), Value::variant(Type::Str, "text".into())]),
1135            Value::Tuple(vec![
1136                "b".into(),
1137                Value::variant(Type::parse("t").unwrap(), Value::U64(7)),
1138            ]),
1139            Value::Tuple(vec![
1140                "c".into(),
1141                Value::variant(
1142                    Type::parse("aay").unwrap(),
1143                    Value::Array(vec![Value::Bytes(b"xy".to_vec())]),
1144                ),
1145            ]),
1146        ]);
1147        let bytes = to_bytes(&ty, &dict).unwrap();
1148        let entries: Vec<(&str, VariantBytes)> =
1149            <ArrayIter<(&str, VariantBytes)> as GvDecode>::decode(&bytes)
1150                .unwrap()
1151                .map(Result::unwrap)
1152                .collect();
1153        let mut out = Vec::new();
1154        write_array(&mut out, 8, false, entries.len(), |out, i| {
1155            entries[i].encode(out)
1156        })
1157        .unwrap();
1158        assert_eq!(out, bytes);
1159
1160        let variant = to_bytes(&Type::Variant, &Value::variant(Type::Str, "text".into())).unwrap();
1161        let read = VariantBytes::decode(&variant).unwrap();
1162        assert_eq!(encode_to_vec(&read).unwrap(), variant);
1163    }
1164
1165    #[test]
1166    fn signature_constants() {
1167        assert_eq!(<u32 as GvType>::SIGNATURE, "u");
1168        assert_eq!(<u64 as GvType>::SIGNATURE, "t");
1169        assert_eq!(<&str as GvType>::SIGNATURE, "s");
1170        assert_eq!(<&[u8] as GvType>::SIGNATURE, "ay");
1171        assert_eq!(<Variant as GvType>::SIGNATURE, "v");
1172    }
1173
1174    #[test]
1175    fn alignment_and_fixed_size_match_type() {
1176        assert_eq!(<(u32, u32, u32) as GvType>::ALIGNMENT, 4);
1177        assert_eq!(<(u32, u32, u32) as GvType>::FIXED_SIZE, Some(12));
1178        assert_eq!(<(u64, u8) as GvType>::FIXED_SIZE, Some(16));
1179        assert_eq!(<DirMetaView<'static> as GvType>::FIXED_SIZE, None);
1180        assert_eq!(<DirMetaView<'static> as GvType>::ALIGNMENT, 4);
1181    }
1182
1183    /// Constants of the typed view must agree with the parsed [`Type`].
1184    fn assert_consts_match<'a, T: GvEncode + GvDecode<'a>>(sig: &str) {
1185        let ty = Type::parse(sig).unwrap();
1186        assert_eq!(
1187            <T as GvType>::ALIGNMENT,
1188            ty.alignment(),
1189            "alignment for {sig}"
1190        );
1191        assert_eq!(
1192            <T as GvType>::FIXED_SIZE,
1193            ty.fixed_size(),
1194            "fixed size for {sig}"
1195        );
1196    }
1197
1198    #[test]
1199    fn tuple_constants_match_type_for_aligned_arrays() {
1200        assert_consts_match::<(u8, ArrayIter<(u32, u32)>)>("(ya(uu))");
1201        assert_consts_match::<(&str, ArrayIter<(u32, u32, u32)>)>("(sa(uuu))");
1202        assert_consts_match::<(u64, &[u8], ArrayIter<(&str, Variant)>)>("(taya{sv})");
1203    }
1204
1205    #[test]
1206    fn aligned_array_behind_unaligned_member_reencodes_identically() {
1207        // (ya(uu)): padding follows the leading byte and precedes the
1208        // 4-aligned array. The re-encode of the borrowed array must reproduce
1209        // this padding.
1210        let ty = Type::parse("(ya(uu))").unwrap();
1211        let value = Value::Tuple(vec![
1212            Value::Byte(7),
1213            Value::Array(vec![
1214                Value::Tuple(vec![Value::U32(1), Value::U32(2)]),
1215                Value::Tuple(vec![Value::U32(3), Value::U32(4)]),
1216            ]),
1217        ]);
1218        let bytes = to_bytes(&ty, &value).unwrap();
1219        let decoded = <(u8, ArrayIter<(u32, u32)>) as GvDecode>::decode(&bytes).unwrap();
1220        let reencoded = encode_to_vec(&decoded).unwrap();
1221        assert_eq!(reencoded, bytes, "(ya(uu)) re-encode is byte-identical");
1222        assert_eq!(from_bytes(&ty, &reencoded).unwrap(), value);
1223
1224        // (sa(uuu)): a variable-size member ahead of the aligned array.
1225        let ty = Type::parse("(sa(uuu))").unwrap();
1226        let value = Value::Tuple(vec![
1227            "ab".into(),
1228            Value::Array(vec![Value::Tuple(vec![
1229                Value::U32(1),
1230                Value::U32(2),
1231                Value::U32(3),
1232            ])]),
1233        ]);
1234        let bytes = to_bytes(&ty, &value).unwrap();
1235        let decoded = <(&str, ArrayIter<(u32, u32, u32)>) as GvDecode>::decode(&bytes).unwrap();
1236        assert_eq!(
1237            encode_to_vec(&decoded).unwrap(),
1238            bytes,
1239            "(sa(uuu)) re-encode is byte-identical"
1240        );
1241
1242        // (taya{sv}): an 8-aligned dict-entry array behind a byte array.
1243        let ty = Type::parse("(taya{sv})").unwrap();
1244        let value = Value::Tuple(vec![
1245            Value::U64(9),
1246            Value::Bytes(vec![0xaa, 0xbb, 0xcc]),
1247            Value::Array(vec![Value::Tuple(vec![
1248                "k".into(),
1249                Value::variant(Type::Str, "x".into()),
1250            ])]),
1251        ]);
1252        let bytes = to_bytes(&ty, &value).unwrap();
1253        let decoded =
1254            <(u64, &[u8], ArrayIter<(&str, Variant)>) as GvDecode>::decode(&bytes).unwrap();
1255        assert_eq!(
1256            encode_to_vec(&decoded).unwrap(),
1257            bytes,
1258            "(taya{{sv}}) re-encode is byte-identical"
1259        );
1260    }
1261
1262    #[test]
1263    fn array_iter_fuses_after_framing_error() {
1264        // A two-element "as" whose first framing offset exceeds the data area.
1265        // The iterator yields the framing error once. Then iteration ends.
1266        let data = [b'a', 0, b'b', 0, 5, 4];
1267        let mut it = <ArrayIter<&str> as GvDecode>::decode(&data).unwrap();
1268        assert_eq!(
1269            it.next(),
1270            Some(Err(Error::NotNormal(
1271                "array element offsets are out of order"
1272            )))
1273        );
1274        assert_eq!(it.next(), None);
1275        assert_eq!(it.next(), None);
1276    }
1277
1278    #[test]
1279    fn array_decode_defers_element_checks_to_iteration() {
1280        // Valid outer framing around a corrupt element. Decode succeeds. The
1281        // iterator yields the element error at the visit of that element.
1282        let data = [0xff, 0, 2];
1283        let mut it = <ArrayIter<&str> as GvDecode>::decode(&data).unwrap();
1284        assert_eq!(
1285            it.next(),
1286            Some(Err(Error::NotNormal("string is not valid UTF-8")))
1287        );
1288        assert_eq!(it.next(), None);
1289    }
1290
1291    #[test]
1292    fn rejects_interior_nul_in_string() {
1293        let err = encode_to_vec(&"a\0b").unwrap_err();
1294        assert_eq!(
1295            err,
1296            Error::InvalidValue("string contains an interior NUL byte")
1297        );
1298    }
1299
1300    #[test]
1301    fn rejects_bad_typed_bytes() {
1302        assert!(<u32 as GvDecode>::decode(&[1, 2, 3]).is_err());
1303        assert!(<&str as GvDecode>::decode(b"abc").is_err());
1304        assert!(<bool as GvDecode>::decode(&[2]).is_err());
1305    }
1306
1307    #[test]
1308    fn rejects_non_normal_array_offset_size() {
1309        // A 256-byte `as` with one 254-byte string element and a 2-byte
1310        // framing offset. Normal form uses a 1-byte offset, 255 bytes in
1311        // total, so decode must reject the wider encoding. If decode accepts
1312        // it, a re-serialize silently gives shorter bytes with another checksum.
1313        let mut data = vec![b'x'; 253];
1314        data.push(0); // NUL terminator -> 254-byte element data area
1315        data.extend_from_slice(&254u16.to_le_bytes());
1316        assert_eq!(data.len(), 256);
1317        assert_eq!(
1318            from_bytes(&Type::parse("as").unwrap(), &data),
1319            Err(Error::NotNormal(
1320                "array framing offset size is not normal-form"
1321            ))
1322        );
1323    }
1324
1325    #[test]
1326    fn rejects_non_normal_tuple_offset_size() {
1327        // A 256-byte `(ss)` whose single framing offset is 2 bytes. Normal
1328        // form uses a 1-byte offset, 255 bytes in total. The member area holds
1329        // the two NUL-terminated strings. The trailing offset points to the end
1330        // of the first string.
1331        let mut data = Vec::new();
1332        data.extend_from_slice(b"a\0"); // first string, 2 bytes
1333        data.extend_from_slice(&vec![b'b'; 251]);
1334        data.push(0); // second string, 252 bytes -> 254-byte member area
1335        data.extend_from_slice(&2u16.to_le_bytes()); // 2-byte offset to s1 end
1336        assert_eq!(data.len(), 256);
1337        assert_eq!(
1338            from_bytes(&Type::parse("(ss)").unwrap(), &data),
1339            Err(Error::NotNormal(
1340                "tuple framing offset size is not normal-form"
1341            ))
1342        );
1343    }
1344}