Skip to main content

ostrya_gvariant/
codec.rs

1//! Typed codec layer over the serialized bytes.
2//!
3//! [`GvDecode`] reads fields in place from a serialized buffer and [`GvEncode`]
4//! writes normal-form bytes directly, without going through the [`Value`] tree.
5//! Decode is borrow-first: strings and byte arrays decode as `&str` and
6//! `&[u8]` borrowing the input, and arrays decode as [`ArrayIter`], a lazy
7//! iterator over the framing offsets. Traversing a read-heavy object -- a
8//! dirtree walk, an xattr scan -- therefore performs no heap allocation.
9//!
10//! The framing is driven entirely by two associated constants,
11//! [`GvType::ALIGNMENT`] and [`GvType::FIXED_SIZE`], which compose in
12//! `const` context, so no type signature is parsed on the traversal path. The
13//! reader and writer primitives reuse the same offset and padding helpers as
14//! [`from_bytes`](crate::from_bytes) and [`to_bytes`](crate::to_bytes), so a
15//! value decoded here re-encodes to the identical bytes.
16//!
17//! This crate stays free of ostree knowledge. The impls here cover the scalar
18//! and container building blocks; the ostree object structs implement the
19//! traits in a later phase, where the value-level conventions (big-endian
20//! scalars, checksum-length and sort-order validation) are applied.
21
22use std::marker::PhantomData;
23
24use crate::de::{check_padding, exact, offset_size_for, read_offset, split_variant};
25use crate::ser::{choose_offset_size, write_offset};
26use crate::ty::align_up;
27use crate::{Error, Result, Type, Value};
28
29/// Type-level facts about a GVariant-encodable type: its signature, alignment,
30/// and fixed size. [`GvEncode`] and [`GvDecode`] both require it, so a type
31/// states these three constants once for both directions.
32///
33/// The framing on the traversal path is driven entirely by [`ALIGNMENT`] and
34/// [`FIXED_SIZE`], which compose in `const` context, so no type signature is
35/// parsed while reading.
36///
37/// [`ALIGNMENT`]: GvType::ALIGNMENT
38/// [`FIXED_SIZE`]: GvType::FIXED_SIZE
39pub trait GvType {
40    /// The GVariant type signature, for the nameable leaf and object types.
41    /// Composite container impls (tuples, arrays) leave it empty: their
42    /// signature is compositional and is not needed to encode.
43    const SIGNATURE: &'static str = "";
44    /// Alignment of the serialized form, in bytes.
45    const ALIGNMENT: usize;
46    /// Serialized size if fixed-size, else `None`.
47    const FIXED_SIZE: Option<usize>;
48}
49
50/// Encode a value into normal-form GVariant bytes.
51///
52/// `encode` appends this value at the current end of `out`; container impls
53/// pad each member to its alignment before delegating, so the top-level call
54/// only needs an empty (or already-aligned) buffer.
55pub trait GvEncode: GvType {
56    /// Append the normal-form serialization of `self` to `out`.
57    fn encode(&self, out: &mut Vec<u8>) -> Result<()>;
58}
59
60/// Decode normal-form GVariant bytes, borrowing from `data` where possible.
61///
62/// Scalar, string, tuple, and variant decoders reject any deviation from
63/// normal form (nonzero padding, out-of-order offsets, unterminated or
64/// non-UTF-8 strings, wrong sizes) at decode time. [`ArrayIter`]'s decode
65/// checks the array's outer framing and defers the per-element checks to
66/// iteration; draining the iterator applies the same checks as
67/// [`from_bytes`](crate::from_bytes).
68pub trait GvDecode<'a>: GvType + Sized {
69    /// Decode a value from the slice covering exactly its serialized form.
70    fn decode(data: &'a [u8]) -> Result<Self>;
71}
72
73/// Encode a top-level value to a fresh byte vector.
74pub fn encode_to_vec<T: GvEncode>(value: &T) -> Result<Vec<u8>> {
75    let mut out = Vec::new();
76    value.encode(&mut out)?;
77    Ok(out)
78}
79
80// -- scalar leaves ---------------------------------------------------------
81
82impl GvType for bool {
83    const SIGNATURE: &'static str = "b";
84    const ALIGNMENT: usize = 1;
85    const FIXED_SIZE: Option<usize> = Some(1);
86}
87
88impl GvEncode for bool {
89    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
90        out.push(*self as u8);
91        Ok(())
92    }
93}
94
95impl<'a> GvDecode<'a> for bool {
96    fn decode(data: &'a [u8]) -> Result<Self> {
97        match exact::<1>(data)?[0] {
98            0 => Ok(false),
99            1 => Ok(true),
100            _ => Err(Error::NotNormal("boolean is not 0 or 1")),
101        }
102    }
103}
104
105impl GvType for u8 {
106    const SIGNATURE: &'static str = "y";
107    const ALIGNMENT: usize = 1;
108    const FIXED_SIZE: Option<usize> = Some(1);
109}
110
111impl GvEncode for u8 {
112    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
113        out.push(*self);
114        Ok(())
115    }
116}
117
118impl<'a> GvDecode<'a> for u8 {
119    fn decode(data: &'a [u8]) -> Result<Self> {
120        Ok(exact::<1>(data)?[0])
121    }
122}
123
124impl GvType for u32 {
125    const SIGNATURE: &'static str = "u";
126    const ALIGNMENT: usize = 4;
127    const FIXED_SIZE: Option<usize> = Some(4);
128}
129
130impl GvEncode for u32 {
131    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
132        out.extend_from_slice(&self.to_le_bytes());
133        Ok(())
134    }
135}
136
137impl<'a> GvDecode<'a> for u32 {
138    fn decode(data: &'a [u8]) -> Result<Self> {
139        Ok(u32::from_le_bytes(exact(data)?))
140    }
141}
142
143impl GvType for u64 {
144    const SIGNATURE: &'static str = "t";
145    const ALIGNMENT: usize = 8;
146    const FIXED_SIZE: Option<usize> = Some(8);
147}
148
149impl GvEncode for u64 {
150    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
151        out.extend_from_slice(&self.to_le_bytes());
152        Ok(())
153    }
154}
155
156impl<'a> GvDecode<'a> for u64 {
157    fn decode(data: &'a [u8]) -> Result<Self> {
158        Ok(u64::from_le_bytes(exact(data)?))
159    }
160}
161
162// -- string and byte array -------------------------------------------------
163
164impl GvType for &str {
165    const SIGNATURE: &'static str = "s";
166    const ALIGNMENT: usize = 1;
167    const FIXED_SIZE: Option<usize> = None;
168}
169
170impl GvEncode for &str {
171    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
172        let s: &str = self;
173        if s.as_bytes().contains(&0) {
174            return Err(Error::InvalidValue("string contains an interior NUL byte"));
175        }
176        out.extend_from_slice(s.as_bytes());
177        out.push(0);
178        Ok(())
179    }
180}
181
182impl<'a> GvDecode<'a> for &'a str {
183    fn decode(data: &'a [u8]) -> Result<Self> {
184        let Some((&0, content)) = data.split_last() else {
185            return Err(Error::NotNormal("string is not NUL-terminated"));
186        };
187        if content.contains(&0) {
188            return Err(Error::NotNormal("string contains an interior NUL byte"));
189        }
190        std::str::from_utf8(content).map_err(|_| Error::NotNormal("string is not valid UTF-8"))
191    }
192}
193
194impl GvType for String {
195    const SIGNATURE: &'static str = "s";
196    const ALIGNMENT: usize = 1;
197    const FIXED_SIZE: Option<usize> = None;
198}
199
200/// Encode an owned string by delegating to the `&str` path, so an owned value
201/// (a dirtree entry name, say) can be a tuple or array member without first
202/// being reborrowed into a temporary slice of references.
203impl GvEncode for String {
204    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
205        self.as_str().encode(out)
206    }
207}
208
209impl GvType for &[u8] {
210    const SIGNATURE: &'static str = "ay";
211    const ALIGNMENT: usize = 1;
212    const FIXED_SIZE: Option<usize> = None;
213}
214
215impl GvEncode for &[u8] {
216    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
217        out.extend_from_slice(self);
218        Ok(())
219    }
220}
221
222impl<'a> GvDecode<'a> for &'a [u8] {
223    fn decode(data: &'a [u8]) -> Result<Self> {
224        Ok(data)
225    }
226}
227
228// -- arrays ----------------------------------------------------------------
229
230/// A lazy reader over the elements of a serialized array. Holds only the
231/// backing slice and a cursor, so iteration allocates nothing.
232#[derive(Clone, Copy)]
233pub(crate) struct ArrayReader<'a> {
234    data: &'a [u8],
235    elem_alignment: usize,
236    /// `Some` for a fixed-size element type; drives the packing/framing split.
237    elem_size: Option<usize>,
238    /// Framing-offset size (variable-element arrays only).
239    z: usize,
240    /// End of the element data, where the framing area begins (variable only).
241    data_end: usize,
242    /// Element count.
243    n: usize,
244    /// Next element index.
245    i: usize,
246    /// Current data position (variable-element cursor).
247    pos: usize,
248}
249
250impl<'a> ArrayReader<'a> {
251    pub(crate) fn new(
252        data: &'a [u8],
253        elem_alignment: usize,
254        elem_fixed_size: Option<usize>,
255    ) -> Result<Self> {
256        let mut r = ArrayReader {
257            data,
258            elem_alignment,
259            elem_size: elem_fixed_size,
260            z: 0,
261            data_end: 0,
262            n: 0,
263            i: 0,
264            pos: 0,
265        };
266        if data.is_empty() {
267            return Ok(r);
268        }
269        if let Some(size) = elem_fixed_size {
270            if !data.len().is_multiple_of(size) {
271                return Err(Error::NotNormal(
272                    "array size is not a multiple of the element size",
273                ));
274            }
275            r.n = data.len() / size;
276            return Ok(r);
277        }
278        let z = offset_size_for(data.len());
279        if data.len() < z {
280            return Err(Error::NotNormal("array is too small for its framing"));
281        }
282        let data_end = read_offset(&data[data.len() - z..], z);
283        if data_end > data.len() - z {
284            return Err(Error::NotNormal("array framing offset is out of bounds"));
285        }
286        let offsets_len = data.len() - data_end;
287        if !offsets_len.is_multiple_of(z) {
288            return Err(Error::NotNormal("array framing area has a partial offset"));
289        }
290        r.z = z;
291        r.data_end = data_end;
292        r.n = offsets_len / z;
293        // Normal form uses the smallest offset size that fits the element data
294        // plus its own offsets. A wider size re-encodes to fewer bytes, so a
295        // buffer that would not survive re-encode is rejected here.
296        if choose_offset_size(data_end, r.n) != z {
297            return Err(Error::NotNormal(
298                "array framing offset size is not normal-form",
299            ));
300        }
301        Ok(r)
302    }
303
304    /// The full serialized array slice, including the framing area.
305    fn bytes(&self) -> &'a [u8] {
306        self.data
307    }
308
309    /// The element count carved from the framing.
310    pub(crate) fn len(&self) -> usize {
311        self.n
312    }
313
314    pub(crate) fn next_slice(&mut self) -> Option<Result<&'a [u8]>> {
315        if self.i >= self.n {
316            return None;
317        }
318        let idx = self.i;
319        self.i += 1;
320        if let Some(size) = self.elem_size {
321            let start = idx * size;
322            return Some(Ok(&self.data[start..start + size]));
323        }
324        let off_at = self.data_end + idx * self.z;
325        let end = read_offset(&self.data[off_at..off_at + self.z], self.z);
326        let start = align_up(self.pos, self.elem_alignment);
327        if start > end || end > self.data_end {
328            // A framing error leaves `pos` unusable; fuse the reader.
329            self.i = self.n;
330            return Some(Err(Error::NotNormal(
331                "array element offsets are out of order",
332            )));
333        }
334        if let Err(e) = check_padding(&self.data[self.pos..start]) {
335            self.i = self.n;
336            return Some(Err(e));
337        }
338        let slice = &self.data[start..end];
339        self.pos = end;
340        Some(Ok(slice))
341    }
342}
343
344/// A decoded array: a lazy iterator that decodes one element per step.
345///
346/// `ArrayIter` borrows the source buffer and yields `Result<E>`, so
347/// per-element normal-form checks surface as the elements are visited. It is
348/// `Copy`, so it can be re-iterated from the start. A framing error fuses the
349/// iterator: the `Err` is yielded once and every following call returns
350/// `None`.
351#[derive(Clone, Copy)]
352pub struct ArrayIter<'a, E> {
353    reader: ArrayReader<'a>,
354    _marker: PhantomData<fn() -> E>,
355}
356
357impl<'a, E: GvDecode<'a>> Iterator for ArrayIter<'a, E> {
358    type Item = Result<E>;
359    fn next(&mut self) -> Option<Result<E>> {
360        match self.reader.next_slice()? {
361            Ok(slice) => Some(E::decode(slice)),
362            Err(e) => Some(Err(e)),
363        }
364    }
365}
366
367impl<'a, E: GvType> GvType for ArrayIter<'a, E> {
368    const ALIGNMENT: usize = E::ALIGNMENT;
369    const FIXED_SIZE: Option<usize> = None;
370}
371
372impl<'a, E: GvDecode<'a>> GvDecode<'a> for ArrayIter<'a, E> {
373    fn decode(data: &'a [u8]) -> Result<Self> {
374        Ok(ArrayIter {
375            reader: ArrayReader::new(data, E::ALIGNMENT, E::FIXED_SIZE)?,
376            _marker: PhantomData,
377        })
378    }
379}
380
381impl<'a, E: GvDecode<'a>> GvEncode for ArrayIter<'a, E> {
382    /// Re-emit the borrowed array. The reader's backing slice is already
383    /// normal-form and, re-placed at the same alignment, reproduces its bytes.
384    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
385        out.extend_from_slice(self.reader.bytes());
386        Ok(())
387    }
388}
389
390/// An array to encode from a Rust slice of encodable elements.
391pub struct Slice<'s, E>(pub &'s [E]);
392
393impl<'s, E: GvEncode> GvType for Slice<'s, E> {
394    const ALIGNMENT: usize = E::ALIGNMENT;
395    const FIXED_SIZE: Option<usize> = None;
396}
397
398impl<'s, E: GvEncode> GvEncode for Slice<'s, E> {
399    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
400        write_array(
401            out,
402            E::ALIGNMENT,
403            E::FIXED_SIZE.is_some(),
404            self.0.len(),
405            |out, i| self.0[i].encode(out),
406        )
407    }
408}
409
410/// Append `n` array elements with normal-form framing. `write_elem(out, i)`
411/// appends element `i`; the caller supplies the element encoding while this
412/// function owns the padding and the framing-offset area, so the array rule
413/// exists once for both the typed and the `Value` encoders. It is public so a
414/// caller with its own element storage (an ostree object's owned field arrays)
415/// can emit array framing without first collecting element references.
416pub fn write_array<F>(
417    out: &mut Vec<u8>,
418    elem_alignment: usize,
419    elem_fixed: bool,
420    n: usize,
421    mut write_elem: F,
422) -> Result<()>
423where
424    F: FnMut(&mut Vec<u8>, usize) -> Result<()>,
425{
426    let start = out.len();
427    if elem_fixed {
428        // Fixed sizes are multiples of the element alignment, so elements pack
429        // back to back with no padding and no framing offsets.
430        for i in 0..n {
431            write_elem(out, i)?;
432        }
433        return Ok(());
434    }
435    let mut ends = Vec::with_capacity(n);
436    for i in 0..n {
437        pad_to(out, elem_alignment);
438        write_elem(out, i)?;
439        ends.push(out.len() - start);
440    }
441    if !ends.is_empty() {
442        let z = choose_offset_size(out.len() - start, ends.len());
443        for &end in &ends {
444            write_offset(out, end, z);
445        }
446    }
447    Ok(())
448}
449
450// -- variant ---------------------------------------------------------------
451
452/// A decoded variant: the child's type and value together with the borrowed
453/// child bytes and signature.
454///
455/// Variants carry a dynamic child type, so [`decode`](GvDecode::decode) parses
456/// the child into a [`Value`] once and keeps it; [`Variant::value`] borrows
457/// that value without re-walking the bytes or cloning. This is the one building
458/// block that allocates on decode; it sits off the traversal hot path (variants
459/// appear only inside `a{sv}` metadata). [`encode`](GvEncode::encode) re-emits the
460/// borrowed child bytes and signature, so it reproduces the input byte-for-byte
461/// without rebuilding the signature string.
462pub struct Variant<'a> {
463    ty: Type,
464    child: &'a [u8],
465    signature: &'a [u8],
466    value: Value,
467}
468
469impl<'a> Variant<'a> {
470    /// The child's GVariant type.
471    pub fn ty(&self) -> &Type {
472        &self.ty
473    }
474
475    /// The child payload as a [`Value`], borrowed from the value parsed at
476    /// decode time.
477    pub fn value(&self) -> &Value {
478        &self.value
479    }
480}
481
482impl<'a> GvType for Variant<'a> {
483    const SIGNATURE: &'static str = "v";
484    const ALIGNMENT: usize = 8;
485    const FIXED_SIZE: Option<usize> = None;
486}
487
488impl<'a> GvDecode<'a> for Variant<'a> {
489    fn decode(data: &'a [u8]) -> Result<Self> {
490        let (child, signature, ty) = split_variant(data)?;
491        // Walk the child once, as `from_bytes` does for `v`, and keep the value.
492        let value = crate::from_bytes(&ty, child)?;
493        Ok(Variant {
494            ty,
495            child,
496            signature,
497            value,
498        })
499    }
500}
501
502impl<'a> GvEncode for Variant<'a> {
503    fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
504        out.extend_from_slice(self.child);
505        out.push(0);
506        out.extend_from_slice(self.signature);
507        Ok(())
508    }
509}
510
511// -- tuples ----------------------------------------------------------------
512
513/// The alignment of a container: the greatest member alignment, at least 1.
514pub(crate) const fn max_align(aligns: &[usize]) -> usize {
515    let mut m = 1;
516    let mut i = 0;
517    while i < aligns.len() {
518        if aligns[i] > m {
519            m = aligns[i];
520        }
521        i += 1;
522    }
523    m
524}
525
526/// The fixed size of a struct given each member's `(alignment, fixed_size)`,
527/// or `None` if any member is variable-size. Matches `Type::fixed_size`.
528pub(crate) const fn struct_fixed_size(
529    members: &[(usize, Option<usize>)],
530    whole_align: usize,
531) -> Option<usize> {
532    if members.is_empty() {
533        return Some(1);
534    }
535    let mut size = 0;
536    let mut i = 0;
537    while i < members.len() {
538        let (align, fixed) = members[i];
539        match fixed {
540            Some(f) => size = align_up(size, align) + f,
541            None => return None,
542        }
543        i += 1;
544    }
545    Some(align_up(size, whole_align))
546}
547
548/// A cursor that carves a serialized tuple/dict-entry body into member slices,
549/// applying the same framing and padding checks as `from_bytes`.
550pub(crate) struct TupleReader<'a> {
551    data: &'a [u8],
552    framing_start: usize,
553    z: usize,
554    pos: usize,
555    offset_index: usize,
556    fixed: bool,
557}
558
559impl<'a> TupleReader<'a> {
560    pub(crate) fn new(data: &'a [u8], n_offsets: usize, fixed_size: Option<usize>) -> Result<Self> {
561        if let Some(size) = fixed_size
562            && data.len() != size
563        {
564            return Err(Error::NotNormal("fixed-size tuple has the wrong size"));
565        }
566        let z = offset_size_for(data.len());
567        let framing_start = data
568            .len()
569            .checked_sub(n_offsets * z)
570            .ok_or(Error::NotNormal("tuple is too small for its framing"))?;
571        // With framing offsets present, the offset size must be the one the
572        // encoder would pick for this member area; a wider size re-encodes to
573        // fewer bytes and is rejected. Fully fixed and last-member-only tuples
574        // carry no offsets, so `z` is irrelevant there.
575        if n_offsets > 0 && choose_offset_size(framing_start, n_offsets) != z {
576            return Err(Error::NotNormal(
577                "tuple framing offset size is not normal-form",
578            ));
579        }
580        Ok(TupleReader {
581            data,
582            framing_start,
583            z,
584            pos: 0,
585            offset_index: 0,
586            fixed: fixed_size.is_some(),
587        })
588    }
589
590    pub(crate) fn field(
591        &mut self,
592        alignment: usize,
593        fixed_size: Option<usize>,
594        is_last: bool,
595    ) -> Result<&'a [u8]> {
596        let start = align_up(self.pos, alignment);
597        let end = if let Some(size) = fixed_size {
598            start.checked_add(size)
599        } else if is_last {
600            Some(self.framing_start)
601        } else {
602            let at = self.data.len() - (self.offset_index + 1) * self.z;
603            self.offset_index += 1;
604            Some(read_offset(&self.data[at..at + self.z], self.z))
605        };
606        let end = end.ok_or(Error::NotNormal("tuple member offset overflows"))?;
607        if start > end || end > self.framing_start {
608            return Err(Error::NotNormal("tuple member offsets are out of order"));
609        }
610        check_padding(&self.data[self.pos..start])?;
611        let slice = &self.data[start..end];
612        self.pos = end;
613        Ok(slice)
614    }
615
616    pub(crate) fn finish(self) -> Result<()> {
617        if self.fixed {
618            check_padding(&self.data[self.pos..])
619        } else if self.pos != self.framing_start {
620            Err(Error::NotNormal("tuple members do not fill the tuple"))
621        } else {
622            Ok(())
623        }
624    }
625}
626
627/// A writer that appends tuple members with correct alignment, padding, and
628/// framing offsets, producing the same bytes as `to_bytes`.
629pub(crate) struct TupleWriter<'b> {
630    out: &'b mut Vec<u8>,
631    start: usize,
632    /// End offsets of variable-size members other than the last, in member
633    /// order; emitted in reverse by [`finish`](Self::finish).
634    offsets: Vec<usize>,
635}
636
637impl<'b> TupleWriter<'b> {
638    /// The offsets buffer starts empty and grows only for variable-size
639    /// members, so a fully fixed-size tuple allocates nothing.
640    pub(crate) fn new(out: &'b mut Vec<u8>) -> Self {
641        let start = out.len();
642        TupleWriter {
643            out,
644            start,
645            offsets: Vec::new(),
646        }
647    }
648
649    /// Append a member with runtime alignment and fixed-size, delegating the
650    /// member encoding to `write`. The framing rule lives here for both the
651    /// typed and the `Value` encoders.
652    pub(crate) fn field_dyn(
653        &mut self,
654        alignment: usize,
655        fixed_size: Option<usize>,
656        is_last: bool,
657        write: impl FnOnce(&mut Vec<u8>) -> Result<()>,
658    ) -> Result<()> {
659        pad_to(self.out, alignment);
660        write(self.out)?;
661        if !is_last && fixed_size.is_none() {
662            self.offsets.push(self.out.len() - self.start);
663        }
664        Ok(())
665    }
666
667    pub(crate) fn field<T: GvEncode>(&mut self, value: &T, is_last: bool) -> Result<()> {
668        self.field_dyn(T::ALIGNMENT, T::FIXED_SIZE, is_last, |out| {
669            value.encode(out)
670        })
671    }
672
673    pub(crate) fn finish(self, fixed_size: Option<usize>) {
674        if let Some(size) = fixed_size {
675            // All members fixed: pad the end to the tuple alignment.
676            self.out.resize(self.start + size, 0);
677        } else if !self.offsets.is_empty() {
678            let z = choose_offset_size(self.out.len() - self.start, self.offsets.len());
679            for &end in self.offsets.iter().rev() {
680                write_offset(self.out, end, z);
681            }
682        }
683    }
684}
685
686pub(crate) fn pad_to(out: &mut Vec<u8>, alignment: usize) {
687    out.resize(align_up(out.len(), alignment), 0);
688}
689
690macro_rules! impl_tuple {
691    ($($T:ident $idx:tt),+ ; $Last:ident $last_idx:tt) => {
692        impl<$($T: GvType,)+ $Last: GvType> GvType for ($($T,)+ $Last,) {
693            const ALIGNMENT: usize = max_align(&[$($T::ALIGNMENT,)+ $Last::ALIGNMENT]);
694            const FIXED_SIZE: Option<usize> = struct_fixed_size(
695                &[$(($T::ALIGNMENT, $T::FIXED_SIZE),)+ ($Last::ALIGNMENT, $Last::FIXED_SIZE)],
696                max_align(&[$($T::ALIGNMENT,)+ $Last::ALIGNMENT]),
697            );
698        }
699
700        impl<'a, $($T: GvDecode<'a>,)+ $Last: GvDecode<'a>> GvDecode<'a> for ($($T,)+ $Last,) {
701            fn decode(data: &'a [u8]) -> Result<Self> {
702                let n_offsets = [$($T::FIXED_SIZE.is_none(),)+]
703                    .into_iter()
704                    .filter(|&v| v)
705                    .count();
706                let mut r = TupleReader::new(data, n_offsets, <Self as GvType>::FIXED_SIZE)?;
707                let value = (
708                    $( <$T as GvDecode<'a>>::decode(r.field($T::ALIGNMENT, $T::FIXED_SIZE, false)?)?, )+
709                    <$Last as GvDecode<'a>>::decode(r.field($Last::ALIGNMENT, $Last::FIXED_SIZE, true)?)?,
710                );
711                r.finish()?;
712                Ok(value)
713            }
714        }
715
716        impl<$($T: GvEncode,)+ $Last: GvEncode> GvEncode for ($($T,)+ $Last,) {
717            fn encode(&self, out: &mut Vec<u8>) -> Result<()> {
718                let mut w = TupleWriter::new(out);
719                $( w.field(&self.$idx, false)?; )+
720                w.field(&self.$last_idx, true)?;
721                w.finish(<Self as GvType>::FIXED_SIZE);
722                Ok(())
723            }
724        }
725    };
726}
727
728impl_tuple!(A 0 ; B 1);
729impl_tuple!(A 0, B 1 ; C 2);
730impl_tuple!(A 0, B 1, C 2 ; D 3);
731impl_tuple!(A 0, B 1, C 2, D 3 ; E 4);
732impl_tuple!(A 0, B 1, C 2, D 3, E 4 ; F 5);
733impl_tuple!(A 0, B 1, C 2, D 3, E 4, F 5 ; G 6);
734impl_tuple!(A 0, B 1, C 2, D 3, E 4, F 5, G 6 ; H 7);
735
736#[cfg(test)]
737mod tests {
738    use super::*;
739    use crate::{from_bytes, to_bytes};
740
741    /// The `(uuua(ayay))` dirmeta shape as a borrowed view.
742    type DirMetaView<'a> = (u32, u32, u32, ArrayIter<'a, (&'a [u8], &'a [u8])>);
743
744    /// Round-trip a typed value against `to_bytes`/`from_bytes` for the given
745    /// signature: the typed encoding must equal the `Value` encoding, `Value`
746    /// decode of those bytes must reproduce `expected_value`, and typed decode
747    /// must re-encode to the same bytes.
748    ///
749    /// The decode-and-re-encode step is supplied as `decode_reencode` so the
750    /// borrowed view binds to the locally produced buffer: a borrowed type
751    /// such as `&str` cannot be decoded into a fixed lifetime chosen by the
752    /// caller, so the closure decodes and re-encodes within a single call.
753    fn check<T, F>(sig: &str, value: &T, expected_value: &Value, decode_reencode: F)
754    where
755        T: GvEncode,
756        F: Fn(&[u8]) -> Result<Vec<u8>>,
757    {
758        let ty = Type::parse(sig).unwrap();
759        let typed = encode_to_vec(value).unwrap();
760        let from_value = to_bytes(&ty, expected_value).unwrap();
761        assert_eq!(
762            typed, from_value,
763            "typed encode matches Value encode for {sig}"
764        );
765        assert_eq!(
766            from_bytes(&ty, &typed).unwrap(),
767            *expected_value,
768            "Value decode of typed bytes for {sig}"
769        );
770        assert_eq!(
771            decode_reencode(&typed).unwrap(),
772            typed,
773            "typed decode re-encodes identically for {sig}"
774        );
775    }
776
777    #[test]
778    fn scalars_match_value_path() {
779        check("y", &0xabu8, &Value::Byte(0xab), |b: &[u8]| {
780            encode_to_vec(&<u8>::decode(b)?)
781        });
782        check("b", &true, &Value::Bool(true), |b: &[u8]| {
783            encode_to_vec(&<bool>::decode(b)?)
784        });
785        check(
786            "u",
787            &0x0102_0304u32,
788            &Value::U32(0x0102_0304),
789            |b: &[u8]| encode_to_vec(&<u32>::decode(b)?),
790        );
791        check(
792            "t",
793            &0x0102_0304_0506_0708u64,
794            &Value::U64(0x0102_0304_0506_0708),
795            |b: &[u8]| encode_to_vec(&<u64>::decode(b)?),
796        );
797        check("s", &"hi", &Value::Str("hi".into()), |b: &[u8]| {
798            encode_to_vec(&<&str>::decode(b)?)
799        });
800        let bytes: &[u8] = &[0, 1, 2, 0, 4];
801        check(
802            "ay",
803            &bytes,
804            &Value::Bytes(vec![0, 1, 2, 0, 4]),
805            |b: &[u8]| encode_to_vec(&<&[u8]>::decode(b)?),
806        );
807    }
808
809    #[test]
810    fn dirmeta_shape_round_trips() {
811        // (uuua(ayay)) with a single xattr entry.
812        let xattr: (&[u8], &[u8]) = (b"user.foo", b"bar");
813        let value = (
814            0u32,
815            0u32,
816            0o40755u32.swap_bytes(),
817            Slice(std::slice::from_ref(&xattr)),
818        );
819        let ty = Type::parse("(uuua(ayay))").unwrap();
820        let typed = encode_to_vec(&value).unwrap();
821        let expected = Value::Tuple(vec![
822            Value::U32(0),
823            Value::U32(0),
824            Value::U32(0o40755u32.swap_bytes()),
825            Value::Array(vec![Value::Tuple(vec![
826                Value::Bytes(b"user.foo".to_vec()),
827                Value::Bytes(b"bar".to_vec()),
828            ])]),
829        ]);
830        assert_eq!(typed, to_bytes(&ty, &expected).unwrap());
831
832        // Decode borrow-first and re-encode to identical bytes.
833        let decoded = <DirMetaView as GvDecode>::decode(&typed).unwrap();
834        assert_eq!(decoded.0, 0);
835        assert_eq!(decoded.2, 0o40755u32.swap_bytes());
836        let xattrs: Vec<(&[u8], &[u8])> = decoded.3.map(Result::unwrap).collect();
837        assert_eq!(xattrs, [(b"user.foo".as_slice(), b"bar".as_slice())]);
838        assert_eq!(encode_to_vec(&decoded).unwrap(), typed);
839    }
840
841    #[test]
842    fn variable_tuple_with_fixed_final_member() {
843        // (su): string needs a framing offset, the trailing u32 does not.
844        let value: (&str, u32) = ("abc", 5);
845        check(
846            "(su)",
847            &value,
848            &Value::Tuple(vec!["abc".into(), Value::U32(5)]),
849            |b: &[u8]| encode_to_vec(&<(&str, u32)>::decode(b)?),
850        );
851    }
852
853    #[test]
854    fn fixed_element_array_packs_without_offsets() {
855        let items = [(1u32, 2u32, 3u32), (4, 5, 6)];
856        let ty = Type::parse("a(uuu)").unwrap();
857        let typed = encode_to_vec(&Slice(&items)).unwrap();
858        let expected = Value::Array(vec![
859            Value::Tuple(vec![Value::U32(1), Value::U32(2), Value::U32(3)]),
860            Value::Tuple(vec![Value::U32(4), Value::U32(5), Value::U32(6)]),
861        ]);
862        assert_eq!(typed, to_bytes(&ty, &expected).unwrap());
863        let decoded = <ArrayIter<(u32, u32, u32)> as GvDecode>::decode(&typed).unwrap();
864        let got: Vec<(u32, u32, u32)> = decoded.map(Result::unwrap).collect();
865        assert_eq!(got, items);
866    }
867
868    #[test]
869    fn variant_round_trips_via_value() {
870        // A dict entry {sv} carrying a string value, the a{sv} building block.
871        let child = to_bytes(&Type::parse("s").unwrap(), &Value::Str("1".into())).unwrap();
872        let mut variant_bytes = child.clone();
873        variant_bytes.push(0);
874        variant_bytes.extend_from_slice(b"s");
875        let variant = Variant::decode(&variant_bytes).unwrap();
876        assert_eq!(variant.ty(), &Type::Str);
877        assert_eq!(variant.value(), &Value::Str("1".into()));
878        assert_eq!(encode_to_vec(&variant).unwrap(), variant_bytes);
879
880        let entry: (&str, Variant) = ("version", variant);
881        let ty = Type::parse("{sv}").unwrap();
882        let expected = Value::Tuple(vec![
883            "version".into(),
884            Value::variant(Type::Str, "1".into()),
885        ]);
886        assert_eq!(
887            encode_to_vec(&entry).unwrap(),
888            to_bytes(&ty, &expected).unwrap()
889        );
890    }
891
892    #[test]
893    fn signature_constants() {
894        assert_eq!(<u32 as GvType>::SIGNATURE, "u");
895        assert_eq!(<u64 as GvType>::SIGNATURE, "t");
896        assert_eq!(<&str as GvType>::SIGNATURE, "s");
897        assert_eq!(<&[u8] as GvType>::SIGNATURE, "ay");
898        assert_eq!(<Variant as GvType>::SIGNATURE, "v");
899    }
900
901    #[test]
902    fn alignment_and_fixed_size_match_type() {
903        assert_eq!(<(u32, u32, u32) as GvType>::ALIGNMENT, 4);
904        assert_eq!(<(u32, u32, u32) as GvType>::FIXED_SIZE, Some(12));
905        assert_eq!(<(u64, u8) as GvType>::FIXED_SIZE, Some(16));
906        assert_eq!(<DirMetaView<'static> as GvType>::FIXED_SIZE, None);
907        assert_eq!(<DirMetaView<'static> as GvType>::ALIGNMENT, 4);
908    }
909
910    /// Constants of the typed view must agree with the parsed [`Type`].
911    fn assert_consts_match<'a, T: GvEncode + GvDecode<'a>>(sig: &str) {
912        let ty = Type::parse(sig).unwrap();
913        assert_eq!(
914            <T as GvType>::ALIGNMENT,
915            ty.alignment(),
916            "alignment for {sig}"
917        );
918        assert_eq!(
919            <T as GvType>::FIXED_SIZE,
920            ty.fixed_size(),
921            "fixed size for {sig}"
922        );
923    }
924
925    #[test]
926    fn tuple_constants_match_type_for_aligned_arrays() {
927        assert_consts_match::<(u8, ArrayIter<(u32, u32)>)>("(ya(uu))");
928        assert_consts_match::<(&str, ArrayIter<(u32, u32, u32)>)>("(sa(uuu))");
929        assert_consts_match::<(u64, &[u8], ArrayIter<(&str, Variant)>)>("(taya{sv})");
930    }
931
932    #[test]
933    fn aligned_array_behind_unaligned_member_reencodes_identically() {
934        // (ya(uu)): the leading byte leaves the 4-aligned array preceded by
935        // padding, which the re-encode of the borrowed array must reproduce.
936        let ty = Type::parse("(ya(uu))").unwrap();
937        let value = Value::Tuple(vec![
938            Value::Byte(7),
939            Value::Array(vec![
940                Value::Tuple(vec![Value::U32(1), Value::U32(2)]),
941                Value::Tuple(vec![Value::U32(3), Value::U32(4)]),
942            ]),
943        ]);
944        let bytes = to_bytes(&ty, &value).unwrap();
945        let decoded = <(u8, ArrayIter<(u32, u32)>) as GvDecode>::decode(&bytes).unwrap();
946        let reencoded = encode_to_vec(&decoded).unwrap();
947        assert_eq!(reencoded, bytes, "(ya(uu)) re-encode is byte-identical");
948        assert_eq!(from_bytes(&ty, &reencoded).unwrap(), value);
949
950        // (sa(uuu)): a variable-size member ahead of the aligned array.
951        let ty = Type::parse("(sa(uuu))").unwrap();
952        let value = Value::Tuple(vec![
953            "ab".into(),
954            Value::Array(vec![Value::Tuple(vec![
955                Value::U32(1),
956                Value::U32(2),
957                Value::U32(3),
958            ])]),
959        ]);
960        let bytes = to_bytes(&ty, &value).unwrap();
961        let decoded = <(&str, ArrayIter<(u32, u32, u32)>) as GvDecode>::decode(&bytes).unwrap();
962        assert_eq!(
963            encode_to_vec(&decoded).unwrap(),
964            bytes,
965            "(sa(uuu)) re-encode is byte-identical"
966        );
967
968        // (taya{sv}): an 8-aligned dict-entry array behind a byte array.
969        let ty = Type::parse("(taya{sv})").unwrap();
970        let value = Value::Tuple(vec![
971            Value::U64(9),
972            Value::Bytes(vec![0xaa, 0xbb, 0xcc]),
973            Value::Array(vec![Value::Tuple(vec![
974                "k".into(),
975                Value::variant(Type::Str, "x".into()),
976            ])]),
977        ]);
978        let bytes = to_bytes(&ty, &value).unwrap();
979        let decoded =
980            <(u64, &[u8], ArrayIter<(&str, Variant)>) as GvDecode>::decode(&bytes).unwrap();
981        assert_eq!(
982            encode_to_vec(&decoded).unwrap(),
983            bytes,
984            "(taya{{sv}}) re-encode is byte-identical"
985        );
986    }
987
988    #[test]
989    fn array_iter_fuses_after_framing_error() {
990        // Two-element "as" whose first framing offset exceeds the data area:
991        // the framing error surfaces once, then iteration ends.
992        let data = [b'a', 0, b'b', 0, 5, 4];
993        let mut it = <ArrayIter<&str> as GvDecode>::decode(&data).unwrap();
994        assert_eq!(
995            it.next(),
996            Some(Err(Error::NotNormal(
997                "array element offsets are out of order"
998            )))
999        );
1000        assert_eq!(it.next(), None);
1001        assert_eq!(it.next(), None);
1002    }
1003
1004    #[test]
1005    fn array_decode_defers_element_checks_to_iteration() {
1006        // Valid outer framing around a corrupt element: decode succeeds and
1007        // the element error surfaces when the element is visited (D3).
1008        let data = [0xff, 0, 2];
1009        let mut it = <ArrayIter<&str> as GvDecode>::decode(&data).unwrap();
1010        assert_eq!(
1011            it.next(),
1012            Some(Err(Error::NotNormal("string is not valid UTF-8")))
1013        );
1014        assert_eq!(it.next(), None);
1015    }
1016
1017    #[test]
1018    fn rejects_interior_nul_in_string() {
1019        let err = encode_to_vec(&"a\0b").unwrap_err();
1020        assert_eq!(
1021            err,
1022            Error::InvalidValue("string contains an interior NUL byte")
1023        );
1024    }
1025
1026    #[test]
1027    fn rejects_bad_typed_bytes() {
1028        assert!(<u32 as GvDecode>::decode(&[1, 2, 3]).is_err());
1029        assert!(<&str as GvDecode>::decode(b"abc").is_err());
1030        assert!(<bool as GvDecode>::decode(&[2]).is_err());
1031    }
1032
1033    #[test]
1034    fn rejects_non_normal_array_offset_size() {
1035        // A 256-byte `as` with one 254-byte string element framed by a 2-byte
1036        // offset. Normal form uses a 1-byte offset (255 bytes total), so the
1037        // wider encoding must be rejected rather than decoded and silently
1038        // re-serialized to shorter, differently-checksummed bytes.
1039        let mut data = vec![b'x'; 253];
1040        data.push(0); // NUL terminator -> 254-byte element data area
1041        data.extend_from_slice(&254u16.to_le_bytes());
1042        assert_eq!(data.len(), 256);
1043        assert_eq!(
1044            from_bytes(&Type::parse("as").unwrap(), &data),
1045            Err(Error::NotNormal(
1046                "array framing offset size is not normal-form"
1047            ))
1048        );
1049    }
1050
1051    #[test]
1052    fn rejects_non_normal_tuple_offset_size() {
1053        // A 256-byte `(ss)` whose single framing offset is 2 bytes; normal
1054        // form uses a 1-byte offset (255 bytes total). The member area is the
1055        // two NUL-terminated strings; the trailing offset points to the end
1056        // of the first.
1057        let mut data = Vec::new();
1058        data.extend_from_slice(b"a\0"); // first string, 2 bytes
1059        data.extend_from_slice(&vec![b'b'; 251]);
1060        data.push(0); // second string, 252 bytes -> 254-byte member area
1061        data.extend_from_slice(&2u16.to_le_bytes()); // 2-byte offset to s1 end
1062        assert_eq!(data.len(), 256);
1063        assert_eq!(
1064            from_bytes(&Type::parse("(ss)").unwrap(), &data),
1065            Err(Error::NotNormal(
1066                "tuple framing offset size is not normal-form"
1067            ))
1068        );
1069    }
1070}