ostrya-gvariant 0.19.1

Byte-exact GVariant codec for the ostree on-disk format
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
use std::fmt;
use std::num::NonZeroU64;
use std::ops::Deref;

use crate::{Error, Result};

/// The maximum container nesting depth in a type signature.
///
/// The value parser and the serializer use the same depth limit, so this
/// parser accepts the type of each value that one of them accepts.
const MAX_TYPE_DEPTH: usize = crate::de::MAX_VALUE_DEPTH;

/// A GVariant type.
///
/// The ostree on-disk format uses booleans, bytes, `u32`, `u64`, strings,
/// variants, arrays, tuples, and dict entries. The other GVariant types are
/// the signed and the 16-bit integers, the handle, the double, the object
/// path, the signature, and the maybe.
///
/// The other types get into a repository through the `ostree commit
/// --add-metadata` command. That command accepts a value of any type in the
/// GVariant text form, which [`from_text`] reads.
///
/// A container type keeps the alignment and the fixed size of the types in
/// it, which it computes one time when it is constructed. So
/// [`alignment`](Type::alignment) and [`fixed_size`](Type::fixed_size) do
/// not walk the type. [`Type::maybe`], [`Type::array`], [`Type::tuple`], and
/// [`Type::dict_entry`] construct a container type.
///
/// [`from_text`]: crate::from_text
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum Type {
    /// `b`
    Bool,
    /// `y`
    Byte,
    /// `n`
    I16,
    /// `q`
    U16,
    /// `i`
    I32,
    /// `u`
    U32,
    /// `x`
    I64,
    /// `t`
    U64,
    /// `h`
    Handle,
    /// `d`
    Double,
    /// `s`
    Str,
    /// `o`
    ObjectPath,
    /// `g`
    Signature,
    /// `v`
    Variant,
    /// `m<T>`
    Maybe(ElementType),
    /// `a<T>`
    Array(ElementType),
    /// `(<T>...)`
    Tuple(MemberTypes),
    /// `{<K><V>}`
    ///
    /// The key `K` must be a [basic type](Type::is_basic).
    DictEntry(ElementType, ElementType),
}

/// The alignment and the fixed size of a type, in one word.
///
/// The low 4 bits hold the alignment in bytes: 1, 2, 4, or 8. The other bits
/// hold the fixed size, or 0 for a type of variable size. No type has the
/// fixed size 0.
#[derive(Clone, Copy, PartialEq, Eq)]
struct Layout {
    inner: NonZeroU64,
}

impl Layout {
    const fn new(fixed: Option<usize>, alignment: usize) -> Layout {
        let size = match fixed {
            Some(size) => size as u64,
            None => 0,
        };
        match NonZeroU64::new(size << 4 | alignment as u64) {
            Some(inner) => Layout { inner },
            None => unreachable!(),
        }
    }

    /// The layout of a scalar, whose size is its alignment.
    const fn scalar(size: usize) -> Layout {
        Layout::new(Some(size), size)
    }

    /// The layout of a type of variable size.
    const fn variable(alignment: usize) -> Layout {
        Layout::new(None, alignment)
    }

    fn alignment(self) -> usize {
        (self.inner.get() & 0xf) as usize
    }

    fn fixed(self) -> Option<usize> {
        match self.inner.get() >> 4 {
            0 => None,
            size => Some(size as usize),
        }
    }

    /// The layout of a tuple or a dict entry with members of the layouts
    /// `members`.
    ///
    /// The alignment is the greatest member alignment, at least 1. If a member
    /// has a variable size, the structure has a variable size. The size of a
    /// fixed structure includes the padding at its end to its alignment, and
    /// the empty structure has the fixed size 1.
    fn of_struct(members: impl Iterator<Item = Layout>) -> Layout {
        let mut alignment = 1;
        let mut size = Some(0);
        let mut any = false;
        for m in members {
            any = true;
            alignment = alignment.max(m.alignment());
            size = match (size, m.fixed()) {
                (Some(size), Some(fixed)) => Some(align_up(size, m.alignment()) + fixed),
                _ => None,
            };
        }
        let size = if any {
            size.map(|size| align_up(size, alignment))
        } else {
            Some(1)
        };
        Layout::new(size, alignment)
    }
}

/// A type in a container type: the element of a maybe or of an array, or the
/// key or the value of a dict entry.
///
/// It dereferences to the [`Type`] that it holds. It keeps the alignment and
/// the fixed size of that type, which it computes one time when it is
/// constructed.
#[derive(Clone, PartialEq, Eq)]
pub struct ElementType {
    ty: Box<Type>,
    layout: Layout,
}

impl ElementType {
    fn new(ty: Type) -> ElementType {
        let layout = ty.layout();
        ElementType {
            ty: Box::new(ty),
            layout,
        }
    }
}

impl Deref for ElementType {
    type Target = Type;

    fn deref(&self) -> &Type {
        &self.ty
    }
}

impl AsRef<Type> for ElementType {
    fn as_ref(&self) -> &Type {
        &self.ty
    }
}

impl fmt::Debug for ElementType {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.ty, f)
    }
}

/// The member types of a tuple type, in order.
///
/// It dereferences to the slice of the member types. It keeps the alignment
/// and the fixed size of the tuple, which it computes one time when it is
/// constructed.
#[derive(Clone, PartialEq, Eq)]
pub struct MemberTypes {
    types: Vec<Type>,
    layout: Layout,
}

impl MemberTypes {
    fn new(types: Vec<Type>) -> MemberTypes {
        let layout = Layout::of_struct(types.iter().map(Type::layout));
        MemberTypes { types, layout }
    }
}

impl Deref for MemberTypes {
    type Target = [Type];

    fn deref(&self) -> &[Type] {
        &self.types
    }
}

impl<'a> IntoIterator for &'a MemberTypes {
    type Item = &'a Type;
    type IntoIter = std::slice::Iter<'a, Type>;

    fn into_iter(self) -> Self::IntoIter {
        self.types.iter()
    }
}

impl fmt::Debug for MemberTypes {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        fmt::Debug::fmt(&self.types, f)
    }
}

#[cfg(test)]
thread_local! {
    /// The number of calls of [`Type::layout`] on this thread.
    ///
    /// A test of the cost of a parse reads it.
    pub(crate) static LAYOUT_CALLS: std::cell::Cell<usize> = const { std::cell::Cell::new(0) };
}

impl Type {
    /// Returns the maybe type `m<elem>`.
    pub fn maybe(elem: Type) -> Type {
        Type::Maybe(ElementType::new(elem))
    }

    /// Returns the array type `a<elem>`.
    pub fn array(elem: Type) -> Type {
        Type::Array(ElementType::new(elem))
    }

    /// Returns the tuple type of `members`, in order.
    pub fn tuple(members: Vec<Type>) -> Type {
        Type::Tuple(MemberTypes::new(members))
    }

    /// Returns the dict entry type `{<key><value>}`.
    ///
    /// The call does not check that `key` is a [basic type](Type::is_basic).
    pub fn dict_entry(key: Type, value: Type) -> Type {
        Type::DictEntry(ElementType::new(key), ElementType::new(value))
    }

    /// Parses a complete type signature.
    ///
    /// The string must hold exactly one complete type. For example,
    /// `(a{sv}aya(say)sstayay)` is the signature of an ostree commit.
    ///
    /// # Errors
    ///
    /// The function returns [`Error::InvalidTypeString`] if the parse fails.
    /// Its `offset` is the byte offset of the failure. Its `reason` is one of
    /// these:
    ///
    /// - `unexpected end of signature` if the string ends before a complete
    ///   type, for example `""`, `"a"`, or `"(s"`.
    /// - `unsupported type character` if a character is outside the GVariant
    ///   type alphabet.
    /// - `trailing characters after a complete type` if characters follow
    ///   the first complete type, for example `"ss"`.
    /// - `dict-entry key must be a basic type` if the key of a dict entry is
    ///   not a [basic type](Type::is_basic), for example `"{vs}"`.
    /// - `expected '}' after the dict-entry value` if a dict entry holds more
    ///   than two types or has no `}`.
    /// - `nesting exceeds the supported depth` if the signature nests more
    ///   than 128 levels of containers.
    ///
    /// # Depth limit
    ///
    /// A type can nest at most 128 levels of containers. Each `m`, `a`, `(`,
    /// and `{` adds one level to the types inside it. The signature of 128
    /// `a` characters and one `y` parses. With 129 `a` characters, the parse
    /// fails with the reason `nesting exceeds the supported depth`.
    ///
    /// [`from_bytes`] and [`to_bytes`] apply the same limit of 128 levels to a
    /// value.
    ///
    /// [`from_bytes`]: crate::from_bytes
    /// [`to_bytes`]: crate::to_bytes
    pub fn parse(signature: &str) -> Result<Type> {
        let sig = signature.as_bytes();
        let mut pos = 0;
        let err = |offset, reason| Error::InvalidTypeString {
            signature: signature.to_owned(),
            offset,
            reason,
        };
        let ty = parse_one(sig, &mut pos, 0).map_err(|(offset, reason)| err(offset, reason))?;
        if pos != sig.len() {
            return Err(err(pos, "trailing characters after a complete type"));
        }
        Ok(ty)
    }

    /// Returns the signature string of this type.
    pub fn signature(&self) -> String {
        let mut out = String::new();
        self.write_signature(&mut out);
        out
    }

    fn write_signature(&self, out: &mut String) {
        match self {
            Type::Bool => out.push('b'),
            Type::Byte => out.push('y'),
            Type::I16 => out.push('n'),
            Type::U16 => out.push('q'),
            Type::I32 => out.push('i'),
            Type::U32 => out.push('u'),
            Type::I64 => out.push('x'),
            Type::U64 => out.push('t'),
            Type::Handle => out.push('h'),
            Type::Double => out.push('d'),
            Type::Str => out.push('s'),
            Type::ObjectPath => out.push('o'),
            Type::Signature => out.push('g'),
            Type::Variant => out.push('v'),
            Type::Maybe(elem) => {
                out.push('m');
                elem.write_signature(out);
            }
            Type::Array(elem) => {
                out.push('a');
                elem.write_signature(out);
            }
            Type::Tuple(members) => {
                out.push('(');
                for m in members {
                    m.write_signature(out);
                }
                out.push(')');
            }
            Type::DictEntry(key, value) => {
                out.push('{');
                key.write_signature(out);
                value.write_signature(out);
                out.push('}');
            }
        }
    }

    /// Returns the alignment requirement of the serialized form, in bytes.
    pub fn alignment(&self) -> usize {
        self.layout().alignment()
    }

    /// Returns the serialized size, or `None` if the type has a variable size.
    ///
    /// The size of a tuple or a dict entry includes the padding at its end to
    /// its alignment, so `(ty)` has the size 16. The empty tuple `()` has the
    /// fixed size 1.
    pub fn fixed_size(&self) -> Option<usize> {
        self.layout().fixed()
    }

    /// Returns the layout of this type.
    ///
    /// A container type holds the layouts of the types in it, so the call
    /// does not walk the type.
    fn layout(&self) -> Layout {
        #[cfg(test)]
        LAYOUT_CALLS.with(|calls| calls.set(calls.get() + 1));
        match self {
            Type::Bool | Type::Byte => Layout::scalar(1),
            Type::I16 | Type::U16 => Layout::scalar(2),
            Type::I32 | Type::U32 | Type::Handle => Layout::scalar(4),
            Type::I64 | Type::U64 | Type::Double => Layout::scalar(8),
            Type::Str | Type::ObjectPath | Type::Signature => Layout::variable(1),
            Type::Variant => Layout::variable(8),
            Type::Maybe(elem) | Type::Array(elem) => Layout::variable(elem.layout.alignment()),
            Type::Tuple(members) => members.layout,
            Type::DictEntry(key, value) => {
                Layout::of_struct([key.layout, value.layout].into_iter())
            }
        }
    }

    /// Returns `true` if this type is a scalar or a string.
    ///
    /// These types are the basic types. The key of a dict entry must be a
    /// basic type.
    pub fn is_basic(&self) -> bool {
        matches!(
            self,
            Type::Bool
                | Type::Byte
                | Type::I16
                | Type::U16
                | Type::I32
                | Type::U32
                | Type::I64
                | Type::U64
                | Type::Handle
                | Type::Double
                | Type::Str
                | Type::ObjectPath
                | Type::Signature
        )
    }
}

pub(crate) const fn align_up(n: usize, alignment: usize) -> usize {
    (n + alignment - 1) & !(alignment - 1)
}

type SigError = (usize, &'static str);

fn parse_one(sig: &[u8], pos: &mut usize, depth: usize) -> std::result::Result<Type, SigError> {
    if depth > MAX_TYPE_DEPTH {
        return Err((*pos, "nesting exceeds the supported depth"));
    }
    let Some(&c) = sig.get(*pos) else {
        return Err((*pos, "unexpected end of signature"));
    };
    *pos += 1;
    match c {
        b'b' => Ok(Type::Bool),
        b'y' => Ok(Type::Byte),
        b'n' => Ok(Type::I16),
        b'q' => Ok(Type::U16),
        b'i' => Ok(Type::I32),
        b'u' => Ok(Type::U32),
        b'x' => Ok(Type::I64),
        b't' => Ok(Type::U64),
        b'h' => Ok(Type::Handle),
        b'd' => Ok(Type::Double),
        b's' => Ok(Type::Str),
        b'o' => Ok(Type::ObjectPath),
        b'g' => Ok(Type::Signature),
        b'v' => Ok(Type::Variant),
        b'm' => Ok(Type::maybe(parse_one(sig, pos, depth + 1)?)),
        b'a' => Ok(Type::array(parse_one(sig, pos, depth + 1)?)),
        b'(' => {
            let mut members = Vec::new();
            while sig.get(*pos) != Some(&b')') {
                members.push(parse_one(sig, pos, depth + 1)?);
            }
            *pos += 1;
            Ok(Type::tuple(members))
        }
        b'{' => {
            let key_offset = *pos;
            let key = parse_one(sig, pos, depth + 1)?;
            if !key.is_basic() {
                return Err((key_offset, "dict-entry key must be a basic type"));
            }
            let value = parse_one(sig, pos, depth + 1)?;
            if sig.get(*pos) != Some(&b'}') {
                return Err((*pos, "expected '}' after the dict-entry value"));
            }
            *pos += 1;
            Ok(Type::dict_entry(key, value))
        }
        _ => Err((*pos - 1, "unsupported type character")),
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    /// The type strings that the ostree on-disk format uses.
    const OSTREE_SIGNATURES: &[&str] = &[
        "(a{sv}aya(say)sstayay)",                                 // commit
        "(a(say)a(sayay))",                                       // dirtree
        "(uuua(ayay))",                                           // dirmeta, user.ostreemeta
        "(uuuusa(ayay))",                                         // uncompressed file header
        "(tuuuusa(ayay))",                                        // archive file header
        "a{sv}",                                                  // commitmeta, summary.sig
        "(a(s(taya{sv}))a{sv})",                                  // summary
        "a{sa(s(taya{sv}))}",                                     // collection map
        "(a(uuu)aa(ayay)ayay)",                                   // delta part payload
        "(uayttay)",                                              // delta meta entry
        "(yaytt)",                                                // delta fallback
        "(a{sv}tayay(a{sv}aya(say)sstayay)aya(uayttay)a(yaytt))", // delta superblock
        "(taya{sv})",                                             // signed delta
        "(yay)",                                                  // delta part framing
        "(su)",                                                   // object name
        "ay",
        "aay",
        "as",
    ];

    /// Type strings that use the type characters outside the on-disk format.
    ///
    /// These types get into a repository through the `ostree commit
    /// --add-metadata` command.
    const METADATA_SIGNATURES: &[&str] = &[
        "n", "q", "i", "x", "h", "d", "o", "g", "ms", "mi", "ami", "a{sd}", "(sid)", "mmy",
    ];

    #[test]
    fn parses_and_round_trips_every_ostree_signature() {
        for sig in OSTREE_SIGNATURES.iter().chain(METADATA_SIGNATURES) {
            let ty = Type::parse(sig).unwrap();
            assert_eq!(ty.signature(), *sig);
        }
    }

    #[test]
    fn alignment_and_fixed_size() {
        let cases: &[(&str, usize, Option<usize>)] = &[
            ("y", 1, Some(1)),
            ("b", 1, Some(1)),
            ("u", 4, Some(4)),
            ("t", 8, Some(8)),
            ("s", 1, None),
            ("v", 8, None),
            ("ay", 1, None),
            ("a(uuu)", 4, None),
            ("(uuu)", 4, Some(12)),
            ("(ty)", 8, Some(16)), // end padding to the tuple alignment
            ("(uuua(ayay))", 4, None),
            ("(tuuuusa(ayay))", 8, None),
            ("(su)", 4, None),
            ("(yaytt)", 8, None),
            ("{sv}", 8, None),
            ("()", 1, Some(1)),
            ("n", 2, Some(2)),
            ("q", 2, Some(2)),
            ("i", 4, Some(4)),
            ("h", 4, Some(4)),
            ("x", 8, Some(8)),
            ("d", 8, Some(8)),
            ("o", 1, None),
            ("g", 1, None),
            ("ms", 1, None),
            ("mi", 4, None),
            ("(id)", 8, Some(16)),
        ];
        for (sig, alignment, fixed) in cases {
            let ty = Type::parse(sig).unwrap();
            assert_eq!(ty.alignment(), *alignment, "alignment of {sig}");
            assert_eq!(ty.fixed_size(), *fixed, "fixed size of {sig}");
        }
    }

    #[test]
    fn rejects_invalid_signatures() {
        for sig in ["", "r", "*", "?", "(s", "{vs}", "{s", "{sv", "ss", "a", "m"] {
            assert!(Type::parse(sig).is_err(), "expected {sig:?} to be rejected");
        }
    }

    #[test]
    fn rejects_overdeep_nesting() {
        // The three cases are the depth limit of the value parser and the
        // serializer, the first depth past that limit, and the depth after that.
        let sig = format!("{}y", "a".repeat(MAX_TYPE_DEPTH));
        assert!(Type::parse(&sig).is_ok());
        let sig = format!("{}y", "a".repeat(MAX_TYPE_DEPTH + 1));
        assert!(Type::parse(&sig).is_err());
        let sig = format!("{}y", "a".repeat(MAX_TYPE_DEPTH + 2));
        assert!(Type::parse(&sig).is_err());
    }
}