Skip to main content

ostrya_gvariant/
ty.rs

1use std::fmt;
2use std::num::NonZeroU64;
3use std::ops::Deref;
4
5use crate::{Error, Result};
6
7/// The maximum container nesting depth in a type signature.
8///
9/// The value parser and the serializer use the same depth limit, so this
10/// parser accepts the type of each value that one of them accepts.
11const MAX_TYPE_DEPTH: usize = crate::de::MAX_VALUE_DEPTH;
12
13/// A GVariant type.
14///
15/// The ostree on-disk format uses booleans, bytes, `u32`, `u64`, strings,
16/// variants, arrays, tuples, and dict entries. The other GVariant types are
17/// the signed and the 16-bit integers, the handle, the double, the object
18/// path, the signature, and the maybe.
19///
20/// The other types get into a repository through the `ostree commit
21/// --add-metadata` command. That command accepts a value of any type in the
22/// GVariant text form, which [`from_text`] reads.
23///
24/// A container type keeps the alignment and the fixed size of the types in
25/// it, which it computes one time when it is constructed. So
26/// [`alignment`](Type::alignment) and [`fixed_size`](Type::fixed_size) do
27/// not walk the type. [`Type::maybe`], [`Type::array`], [`Type::tuple`], and
28/// [`Type::dict_entry`] construct a container type.
29///
30/// [`from_text`]: crate::from_text
31#[derive(Debug, Clone, PartialEq, Eq)]
32pub enum Type {
33    /// `b`
34    Bool,
35    /// `y`
36    Byte,
37    /// `n`
38    I16,
39    /// `q`
40    U16,
41    /// `i`
42    I32,
43    /// `u`
44    U32,
45    /// `x`
46    I64,
47    /// `t`
48    U64,
49    /// `h`
50    Handle,
51    /// `d`
52    Double,
53    /// `s`
54    Str,
55    /// `o`
56    ObjectPath,
57    /// `g`
58    Signature,
59    /// `v`
60    Variant,
61    /// `m<T>`
62    Maybe(ElementType),
63    /// `a<T>`
64    Array(ElementType),
65    /// `(<T>...)`
66    Tuple(MemberTypes),
67    /// `{<K><V>}`
68    ///
69    /// The key `K` must be a [basic type](Type::is_basic).
70    DictEntry(ElementType, ElementType),
71}
72
73/// The alignment and the fixed size of a type, in one word.
74///
75/// The low 4 bits hold the alignment in bytes: 1, 2, 4, or 8. The other bits
76/// hold the fixed size, or 0 for a type of variable size. No type has the
77/// fixed size 0.
78#[derive(Clone, Copy, PartialEq, Eq)]
79struct Layout {
80    inner: NonZeroU64,
81}
82
83impl Layout {
84    const fn new(fixed: Option<usize>, alignment: usize) -> Layout {
85        let size = match fixed {
86            Some(size) => size as u64,
87            None => 0,
88        };
89        match NonZeroU64::new(size << 4 | alignment as u64) {
90            Some(inner) => Layout { inner },
91            None => unreachable!(),
92        }
93    }
94
95    /// The layout of a scalar, whose size is its alignment.
96    const fn scalar(size: usize) -> Layout {
97        Layout::new(Some(size), size)
98    }
99
100    /// The layout of a type of variable size.
101    const fn variable(alignment: usize) -> Layout {
102        Layout::new(None, alignment)
103    }
104
105    fn alignment(self) -> usize {
106        (self.inner.get() & 0xf) as usize
107    }
108
109    fn fixed(self) -> Option<usize> {
110        match self.inner.get() >> 4 {
111            0 => None,
112            size => Some(size as usize),
113        }
114    }
115
116    /// The layout of a tuple or a dict entry with members of the layouts
117    /// `members`.
118    ///
119    /// The alignment is the greatest member alignment, at least 1. If a member
120    /// has a variable size, the structure has a variable size. The size of a
121    /// fixed structure includes the padding at its end to its alignment, and
122    /// the empty structure has the fixed size 1.
123    fn of_struct(members: impl Iterator<Item = Layout>) -> Layout {
124        let mut alignment = 1;
125        let mut size = Some(0);
126        let mut any = false;
127        for m in members {
128            any = true;
129            alignment = alignment.max(m.alignment());
130            size = match (size, m.fixed()) {
131                (Some(size), Some(fixed)) => Some(align_up(size, m.alignment()) + fixed),
132                _ => None,
133            };
134        }
135        let size = if any {
136            size.map(|size| align_up(size, alignment))
137        } else {
138            Some(1)
139        };
140        Layout::new(size, alignment)
141    }
142}
143
144/// A type in a container type: the element of a maybe or of an array, or the
145/// key or the value of a dict entry.
146///
147/// It dereferences to the [`Type`] that it holds. It keeps the alignment and
148/// the fixed size of that type, which it computes one time when it is
149/// constructed.
150#[derive(Clone, PartialEq, Eq)]
151pub struct ElementType {
152    ty: Box<Type>,
153    layout: Layout,
154}
155
156impl ElementType {
157    fn new(ty: Type) -> ElementType {
158        let layout = ty.layout();
159        ElementType {
160            ty: Box::new(ty),
161            layout,
162        }
163    }
164}
165
166impl Deref for ElementType {
167    type Target = Type;
168
169    fn deref(&self) -> &Type {
170        &self.ty
171    }
172}
173
174impl AsRef<Type> for ElementType {
175    fn as_ref(&self) -> &Type {
176        &self.ty
177    }
178}
179
180impl fmt::Debug for ElementType {
181    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
182        fmt::Debug::fmt(&self.ty, f)
183    }
184}
185
186/// The member types of a tuple type, in order.
187///
188/// It dereferences to the slice of the member types. It keeps the alignment
189/// and the fixed size of the tuple, which it computes one time when it is
190/// constructed.
191#[derive(Clone, PartialEq, Eq)]
192pub struct MemberTypes {
193    types: Vec<Type>,
194    layout: Layout,
195}
196
197impl MemberTypes {
198    fn new(types: Vec<Type>) -> MemberTypes {
199        let layout = Layout::of_struct(types.iter().map(Type::layout));
200        MemberTypes { types, layout }
201    }
202}
203
204impl Deref for MemberTypes {
205    type Target = [Type];
206
207    fn deref(&self) -> &[Type] {
208        &self.types
209    }
210}
211
212impl<'a> IntoIterator for &'a MemberTypes {
213    type Item = &'a Type;
214    type IntoIter = std::slice::Iter<'a, Type>;
215
216    fn into_iter(self) -> Self::IntoIter {
217        self.types.iter()
218    }
219}
220
221impl fmt::Debug for MemberTypes {
222    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
223        fmt::Debug::fmt(&self.types, f)
224    }
225}
226
227#[cfg(test)]
228thread_local! {
229    /// The number of calls of [`Type::layout`] on this thread.
230    ///
231    /// A test of the cost of a parse reads it.
232    pub(crate) static LAYOUT_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
233}
234
235impl Type {
236    /// Returns the maybe type `m<elem>`.
237    pub fn maybe(elem: Type) -> Type {
238        Type::Maybe(ElementType::new(elem))
239    }
240
241    /// Returns the array type `a<elem>`.
242    pub fn array(elem: Type) -> Type {
243        Type::Array(ElementType::new(elem))
244    }
245
246    /// Returns the tuple type of `members`, in order.
247    pub fn tuple(members: Vec<Type>) -> Type {
248        Type::Tuple(MemberTypes::new(members))
249    }
250
251    /// Returns the dict entry type `{<key><value>}`.
252    ///
253    /// The call does not check that `key` is a [basic type](Type::is_basic).
254    pub fn dict_entry(key: Type, value: Type) -> Type {
255        Type::DictEntry(ElementType::new(key), ElementType::new(value))
256    }
257
258    /// Parses a complete type signature.
259    ///
260    /// The string must hold exactly one complete type. For example,
261    /// `(a{sv}aya(say)sstayay)` is the signature of an ostree commit.
262    ///
263    /// # Errors
264    ///
265    /// The function returns [`Error::InvalidTypeString`] if the parse fails.
266    /// Its `offset` is the byte offset of the failure. Its `reason` is one of
267    /// these:
268    ///
269    /// - `unexpected end of signature` if the string ends before a complete
270    ///   type, for example `""`, `"a"`, or `"(s"`.
271    /// - `unsupported type character` if a character is outside the GVariant
272    ///   type alphabet.
273    /// - `trailing characters after a complete type` if characters follow
274    ///   the first complete type, for example `"ss"`.
275    /// - `dict-entry key must be a basic type` if the key of a dict entry is
276    ///   not a [basic type](Type::is_basic), for example `"{vs}"`.
277    /// - `expected '}' after the dict-entry value` if a dict entry holds more
278    ///   than two types or has no `}`.
279    /// - `nesting exceeds the supported depth` if the signature nests more
280    ///   than 128 levels of containers.
281    ///
282    /// # Depth limit
283    ///
284    /// A type can nest at most 128 levels of containers. Each `m`, `a`, `(`,
285    /// and `{` adds one level to the types inside it. The signature of 128
286    /// `a` characters and one `y` parses. With 129 `a` characters, the parse
287    /// fails with the reason `nesting exceeds the supported depth`.
288    ///
289    /// [`from_bytes`] and [`to_bytes`] apply the same limit of 128 levels to a
290    /// value.
291    ///
292    /// [`from_bytes`]: crate::from_bytes
293    /// [`to_bytes`]: crate::to_bytes
294    pub fn parse(signature: &str) -> Result<Type> {
295        let sig = signature.as_bytes();
296        let mut pos = 0;
297        let err = |offset, reason| Error::InvalidTypeString {
298            signature: signature.to_owned(),
299            offset,
300            reason,
301        };
302        let ty = parse_one(sig, &mut pos, 0).map_err(|(offset, reason)| err(offset, reason))?;
303        if pos != sig.len() {
304            return Err(err(pos, "trailing characters after a complete type"));
305        }
306        Ok(ty)
307    }
308
309    /// Returns the signature string of this type.
310    pub fn signature(&self) -> String {
311        let mut out = String::new();
312        self.write_signature(&mut out);
313        out
314    }
315
316    fn write_signature(&self, out: &mut String) {
317        match self {
318            Type::Bool => out.push('b'),
319            Type::Byte => out.push('y'),
320            Type::I16 => out.push('n'),
321            Type::U16 => out.push('q'),
322            Type::I32 => out.push('i'),
323            Type::U32 => out.push('u'),
324            Type::I64 => out.push('x'),
325            Type::U64 => out.push('t'),
326            Type::Handle => out.push('h'),
327            Type::Double => out.push('d'),
328            Type::Str => out.push('s'),
329            Type::ObjectPath => out.push('o'),
330            Type::Signature => out.push('g'),
331            Type::Variant => out.push('v'),
332            Type::Maybe(elem) => {
333                out.push('m');
334                elem.write_signature(out);
335            }
336            Type::Array(elem) => {
337                out.push('a');
338                elem.write_signature(out);
339            }
340            Type::Tuple(members) => {
341                out.push('(');
342                for m in members {
343                    m.write_signature(out);
344                }
345                out.push(')');
346            }
347            Type::DictEntry(key, value) => {
348                out.push('{');
349                key.write_signature(out);
350                value.write_signature(out);
351                out.push('}');
352            }
353        }
354    }
355
356    /// Returns the alignment requirement of the serialized form, in bytes.
357    pub fn alignment(&self) -> usize {
358        self.layout().alignment()
359    }
360
361    /// Returns the serialized size, or `None` if the type has a variable size.
362    ///
363    /// The size of a tuple or a dict entry includes the padding at its end to
364    /// its alignment, so `(ty)` has the size 16. The empty tuple `()` has the
365    /// fixed size 1.
366    pub fn fixed_size(&self) -> Option<usize> {
367        self.layout().fixed()
368    }
369
370    /// Returns the layout of this type.
371    ///
372    /// A container type holds the layouts of the types in it, so the call
373    /// does not walk the type.
374    fn layout(&self) -> Layout {
375        #[cfg(test)]
376        LAYOUT_CALLS.with(|calls| calls.set(calls.get() + 1));
377        match self {
378            Type::Bool | Type::Byte => Layout::scalar(1),
379            Type::I16 | Type::U16 => Layout::scalar(2),
380            Type::I32 | Type::U32 | Type::Handle => Layout::scalar(4),
381            Type::I64 | Type::U64 | Type::Double => Layout::scalar(8),
382            Type::Str | Type::ObjectPath | Type::Signature => Layout::variable(1),
383            Type::Variant => Layout::variable(8),
384            Type::Maybe(elem) | Type::Array(elem) => Layout::variable(elem.layout.alignment()),
385            Type::Tuple(members) => members.layout,
386            Type::DictEntry(key, value) => {
387                Layout::of_struct([key.layout, value.layout].into_iter())
388            }
389        }
390    }
391
392    /// Returns `true` if this type is a scalar or a string.
393    ///
394    /// These types are the basic types. The key of a dict entry must be a
395    /// basic type.
396    pub fn is_basic(&self) -> bool {
397        matches!(
398            self,
399            Type::Bool
400                | Type::Byte
401                | Type::I16
402                | Type::U16
403                | Type::I32
404                | Type::U32
405                | Type::I64
406                | Type::U64
407                | Type::Handle
408                | Type::Double
409                | Type::Str
410                | Type::ObjectPath
411                | Type::Signature
412        )
413    }
414}
415
416pub(crate) const fn align_up(n: usize, alignment: usize) -> usize {
417    (n + alignment - 1) & !(alignment - 1)
418}
419
420type SigError = (usize, &'static str);
421
422fn parse_one(sig: &[u8], pos: &mut usize, depth: usize) -> std::result::Result<Type, SigError> {
423    if depth > MAX_TYPE_DEPTH {
424        return Err((*pos, "nesting exceeds the supported depth"));
425    }
426    let Some(&c) = sig.get(*pos) else {
427        return Err((*pos, "unexpected end of signature"));
428    };
429    *pos += 1;
430    match c {
431        b'b' => Ok(Type::Bool),
432        b'y' => Ok(Type::Byte),
433        b'n' => Ok(Type::I16),
434        b'q' => Ok(Type::U16),
435        b'i' => Ok(Type::I32),
436        b'u' => Ok(Type::U32),
437        b'x' => Ok(Type::I64),
438        b't' => Ok(Type::U64),
439        b'h' => Ok(Type::Handle),
440        b'd' => Ok(Type::Double),
441        b's' => Ok(Type::Str),
442        b'o' => Ok(Type::ObjectPath),
443        b'g' => Ok(Type::Signature),
444        b'v' => Ok(Type::Variant),
445        b'm' => Ok(Type::maybe(parse_one(sig, pos, depth + 1)?)),
446        b'a' => Ok(Type::array(parse_one(sig, pos, depth + 1)?)),
447        b'(' => {
448            let mut members = Vec::new();
449            while sig.get(*pos) != Some(&b')') {
450                members.push(parse_one(sig, pos, depth + 1)?);
451            }
452            *pos += 1;
453            Ok(Type::tuple(members))
454        }
455        b'{' => {
456            let key_offset = *pos;
457            let key = parse_one(sig, pos, depth + 1)?;
458            if !key.is_basic() {
459                return Err((key_offset, "dict-entry key must be a basic type"));
460            }
461            let value = parse_one(sig, pos, depth + 1)?;
462            if sig.get(*pos) != Some(&b'}') {
463                return Err((*pos, "expected '}' after the dict-entry value"));
464            }
465            *pos += 1;
466            Ok(Type::dict_entry(key, value))
467        }
468        _ => Err((*pos - 1, "unsupported type character")),
469    }
470}
471
472#[cfg(test)]
473mod tests {
474    use super::*;
475
476    /// The type strings that the ostree on-disk format uses.
477    const OSTREE_SIGNATURES: &[&str] = &[
478        "(a{sv}aya(say)sstayay)",                                 // commit
479        "(a(say)a(sayay))",                                       // dirtree
480        "(uuua(ayay))",                                           // dirmeta, user.ostreemeta
481        "(uuuusa(ayay))",                                         // uncompressed file header
482        "(tuuuusa(ayay))",                                        // archive file header
483        "a{sv}",                                                  // commitmeta, summary.sig
484        "(a(s(taya{sv}))a{sv})",                                  // summary
485        "a{sa(s(taya{sv}))}",                                     // collection map
486        "(a(uuu)aa(ayay)ayay)",                                   // delta part payload
487        "(uayttay)",                                              // delta meta entry
488        "(yaytt)",                                                // delta fallback
489        "(a{sv}tayay(a{sv}aya(say)sstayay)aya(uayttay)a(yaytt))", // delta superblock
490        "(taya{sv})",                                             // signed delta
491        "(yay)",                                                  // delta part framing
492        "(su)",                                                   // object name
493        "ay",
494        "aay",
495        "as",
496    ];
497
498    /// Type strings that use the type characters outside the on-disk format.
499    ///
500    /// These types get into a repository through the `ostree commit
501    /// --add-metadata` command.
502    const METADATA_SIGNATURES: &[&str] = &[
503        "n", "q", "i", "x", "h", "d", "o", "g", "ms", "mi", "ami", "a{sd}", "(sid)", "mmy",
504    ];
505
506    #[test]
507    fn parses_and_round_trips_every_ostree_signature() {
508        for sig in OSTREE_SIGNATURES.iter().chain(METADATA_SIGNATURES) {
509            let ty = Type::parse(sig).unwrap();
510            assert_eq!(ty.signature(), *sig);
511        }
512    }
513
514    #[test]
515    fn alignment_and_fixed_size() {
516        let cases: &[(&str, usize, Option<usize>)] = &[
517            ("y", 1, Some(1)),
518            ("b", 1, Some(1)),
519            ("u", 4, Some(4)),
520            ("t", 8, Some(8)),
521            ("s", 1, None),
522            ("v", 8, None),
523            ("ay", 1, None),
524            ("a(uuu)", 4, None),
525            ("(uuu)", 4, Some(12)),
526            ("(ty)", 8, Some(16)), // end padding to the tuple alignment
527            ("(uuua(ayay))", 4, None),
528            ("(tuuuusa(ayay))", 8, None),
529            ("(su)", 4, None),
530            ("(yaytt)", 8, None),
531            ("{sv}", 8, None),
532            ("()", 1, Some(1)),
533            ("n", 2, Some(2)),
534            ("q", 2, Some(2)),
535            ("i", 4, Some(4)),
536            ("h", 4, Some(4)),
537            ("x", 8, Some(8)),
538            ("d", 8, Some(8)),
539            ("o", 1, None),
540            ("g", 1, None),
541            ("ms", 1, None),
542            ("mi", 4, None),
543            ("(id)", 8, Some(16)),
544        ];
545        for (sig, alignment, fixed) in cases {
546            let ty = Type::parse(sig).unwrap();
547            assert_eq!(ty.alignment(), *alignment, "alignment of {sig}");
548            assert_eq!(ty.fixed_size(), *fixed, "fixed size of {sig}");
549        }
550    }
551
552    #[test]
553    fn rejects_invalid_signatures() {
554        for sig in ["", "r", "*", "?", "(s", "{vs}", "{s", "{sv", "ss", "a", "m"] {
555            assert!(Type::parse(sig).is_err(), "expected {sig:?} to be rejected");
556        }
557    }
558
559    #[test]
560    fn rejects_overdeep_nesting() {
561        // The three cases are the depth limit of the value parser and the
562        // serializer, the first depth past that limit, and the depth after that.
563        let sig = format!("{}y", "a".repeat(MAX_TYPE_DEPTH));
564        assert!(Type::parse(&sig).is_ok());
565        let sig = format!("{}y", "a".repeat(MAX_TYPE_DEPTH + 1));
566        assert!(Type::parse(&sig).is_err());
567        let sig = format!("{}y", "a".repeat(MAX_TYPE_DEPTH + 2));
568        assert!(Type::parse(&sig).is_err());
569    }
570}