Skip to main content

ostrya_remote/proto/
message.rs

1//! The messages of the protocol and their GVariant bodies.
2
3use std::sync::LazyLock;
4
5use ostrya_core::{Checksum, ObjectName, ObjectType};
6use ostrya_gvariant::{
7    ArrayIter, DictBuilder, GvDecode, GvEncode, GvType, Slice, Type, Value, encode_to_vec, to_bytes,
8};
9
10use super::{
11    Encoding, Expected, Kind, MAX_FRAME_LIMIT, MIN_FRAME_LIMIT, RefOutcome, RefState, RefUpdate,
12    checksum, have_type, header_type, maybe_value, object_name, object_name_value, protocol,
13};
14use crate::error::{Error, ErrorCode, Result};
15
16/// The type of the `server-commit` value of a `Commit`.
17const SERVER_COMMIT_SIGNATURE: &str = "(sasas(ayay)ssa{sv}a{sv})";
18
19fn parse(signature: &str) -> Type {
20    Type::parse(signature).expect("valid signature")
21}
22
23static HELLO: LazyLock<Type> = LazyLock::new(|| parse("(ua{sv}as)"));
24static HELLO_REPLY: LazyLock<Type> = LazyLock::new(|| parse("(ua{sv}a(smay))"));
25static OBJECT_NAMES: LazyLock<Type> = LazyLock::new(|| parse("a(yay)"));
26static BYTES: LazyLock<Type> = LazyLock::new(|| parse("ay"));
27static OBJECT_HEADER: LazyLock<Type> = LazyLock::new(|| parse("(yayy)"));
28static OBJECTS_REPLY: LazyLock<Type> = LazyLock::new(|| parse("(ut)"));
29static UPDATES: LazyLock<Type> = LazyLock::new(|| parse("a(symaymay)"));
30static SERVER_COMMIT: LazyLock<Type> = LazyLock::new(|| parse(SERVER_COMMIT_SIGNATURE));
31static COMMIT_REPLY: LazyLock<Type> = LazyLock::new(|| parse("a(smaymay)"));
32static ERROR: LazyLock<Type> = LazyLock::new(|| parse("(ssa{sv})"));
33static STRV: LazyLock<Type> = LazyLock::new(|| parse("as"));
34static MAYBE_CHECKSUM: LazyLock<Type> = LazyLock::new(|| parse("may"));
35static PULL_HELLO: LazyLock<Type> = LazyLock::new(|| parse("(ua{sv})"));
36static GET_REPLY: LazyLock<Type> = LazyLock::new(|| parse("(bmt)"));
37static LIST_REFS: LazyLock<Type> = LazyLock::new(|| parse("(asa{sv})"));
38static VALUE_IN_COMMIT: LazyLock<Type> = LazyLock::new(|| parse("((v))"));
39
40/// The first message of a push client.
41#[derive(Debug, Clone, PartialEq, Eq)]
42pub struct Hello {
43    /// The protocol version that the client requests.
44    pub version: u32,
45    /// The name and version of the client, under the key `agent`.
46    pub agent: Option<String>,
47    /// The refs that the client intends to update, each `NAME` or
48    /// `REMOTE:NAME`.
49    pub refs: Vec<String>,
50    /// The collection id of the namespace that the session targets, under
51    /// the key `collection`.
52    ///
53    /// `None` targets the local refs. The collection id of the server also
54    /// targets the local refs. The encoder writes the key only if the value
55    /// is `Some`.
56    pub collection: Option<String>,
57    /// The flag that is `true` if the `Hello` opens a
58    /// [one-way stream](super#one-way-stream).
59    ///
60    /// In a one-way stream, the receiver sends no message. The key is
61    /// `one-way`. The encoder writes the key only if the value is `true`, and
62    /// the decoder reads an absent key as `false`.
63    pub one_way: bool,
64}
65
66/// The reply to a `Hello`, with the facts and limits of the server.
67///
68/// It also gives the state of each ref that the `Hello` names.
69#[derive(Debug, Clone, PartialEq, Eq)]
70pub struct HelloReply {
71    /// The protocol version that the server speaks for the session.
72    pub version: u32,
73    /// The repository mode, under the key `mode`.
74    pub mode: String,
75    /// The collection id of the repository, under the key `collection-id`.
76    pub collection_id: Option<String>,
77    /// The collection of the namespace that the server selected for the
78    /// session, under the key `collection`.
79    ///
80    /// `None` is the local refs. The encoder writes the key only if the value
81    /// is `Some`.
82    pub collection: Option<String>,
83    /// The frame limit that the server announces, under the key `max-frame`.
84    ///
85    /// Encode and decode return [`Error::Protocol`] for a value outside
86    /// [`MIN_FRAME_LIMIT`](super::MIN_FRAME_LIMIT)`..=`[`MAX_FRAME_LIMIT`](super::MAX_FRAME_LIMIT).
87    pub max_frame: u32,
88    /// The maximum number of entries in one `Have`, under the key `max-have`.
89    ///
90    /// The value is at least 1. For the value 0, encode and decode return
91    /// [`Error::Protocol`].
92    pub max_have: u32,
93    /// The content encodings that the server accepts, under the key
94    /// `encodings`.
95    ///
96    /// The decoder drops a name that is not an encoding.
97    pub encodings: Vec<Encoding>,
98    /// The most object streams at a time, under the key `parallel-uploads`.
99    ///
100    /// The server serves at most this number of object streams at the same
101    /// time in one session. The value is at least 1. For the value 0, encode and
102    /// decode return [`Error::Protocol`].
103    pub parallel_uploads: u32,
104    /// The state of each ref that the `Hello` names, one entry for each ref.
105    pub refs: Vec<RefState>,
106}
107
108/// The reply to a `Have`, with one bit for each entry.
109///
110/// Bit `i` is bit `i % 8` of byte `i / 8`, counted from the least significant
111/// bit. If a bit is set, the server does not hold the object, and the client
112/// must send it.
113#[derive(Debug, Clone, PartialEq, Eq)]
114pub struct HaveReply {
115    /// The bitmap of the entries.
116    pub bitmap: Vec<u8>,
117}
118
119impl HaveReply {
120    /// Creates a reply from one `bool` for each entry of the `Have`.
121    ///
122    /// Bit `i` is set if entry `i` of `missing` is `true`. For `n` entries,
123    /// the bitmap has `n.div_ceil(8)` bytes.
124    pub fn from_missing(missing: impl IntoIterator<Item = bool>) -> HaveReply {
125        let mut bitmap = Vec::new();
126        for (i, set) in missing.into_iter().enumerate() {
127            if i % 8 == 0 {
128                bitmap.push(0);
129            }
130            if set {
131                bitmap[i / 8] |= 1 << (i % 8);
132            }
133        }
134        HaveReply { bitmap }
135    }
136
137    /// Returns `true` if the server does not hold entry `index`.
138    ///
139    /// For an `index` after the end of the bitmap, it returns `false`.
140    pub fn is_missing(&self, index: usize) -> bool {
141        self.bitmap
142            .get(index / 8)
143            .is_some_and(|b| b & (1 << (index % 8)) != 0)
144    }
145
146    /// Checks the reply against a `Have` of `entries` entries.
147    ///
148    /// The bitmap must be `entries.div_ceil(8)` bytes long, and the bits
149    /// after the last entry must be zero.
150    ///
151    /// # Errors
152    ///
153    /// - [`Error::Protocol`] if the bitmap has a different length.
154    /// - [`Error::Protocol`] if the bitmap sets a bit after the last entry.
155    pub fn check_len(&self, entries: usize) -> Result<()> {
156        if self.bitmap.len() != entries.div_ceil(8) {
157            return Err(protocol(format!(
158                "HaveReply of {} bytes for {entries} entries",
159                self.bitmap.len()
160            )));
161        }
162        let tail = entries % 8;
163        if tail != 0 && self.bitmap[entries / 8] >> tail != 0 {
164            return Err(protocol("HaveReply sets a bit after the last entry"));
165        }
166        Ok(())
167    }
168}
169
170/// The message that starts one object in the
171/// [object stream](super#object-stream).
172#[derive(Debug, Clone, PartialEq, Eq)]
173pub struct ObjectHeader {
174    /// The type and the checksum of the object.
175    ///
176    /// For a `CommitMeta` object, the checksum is the checksum of its commit.
177    pub name: ObjectName,
178    /// The encoding of the object bytes.
179    ///
180    /// [`Encoding::Deflate`] is allowed for a file object alone.
181    pub encoding: Encoding,
182}
183
184/// The reply of the server at the end of one object stream.
185///
186/// The counts are those of one stream. If two streams of one session send the
187/// same content, dirtree, dirmeta, or commit object at the same time, both
188/// can count it. A second detached metadata object for one commit is
189/// [`Error::Protocol`], also from another stream, and the session ends.
190#[derive(Debug, Clone, PartialEq, Eq)]
191pub struct ObjectsReply {
192    /// The number of objects that the server stored.
193    pub objects: u32,
194    /// The number of payload bytes that the server wrote.
195    pub payload_bytes: u64,
196}
197
198/// The `Commit` message, with the ref updates of the transaction.
199#[derive(Debug, Clone, PartialEq, Eq)]
200pub struct CommitRequest {
201    /// The ref updates.
202    ///
203    /// A `Commit` with a [`server_commit`](Self::server_commit) holds no
204    /// update.
205    pub updates: Vec<RefUpdate>,
206    /// The flag that allows a ref update that is not a fast-forward.
207    ///
208    /// The key is `force`. The encoder writes the key only if the value is
209    /// `true`, and the decoder reads an absent key as `false`.
210    pub force: bool,
211    /// The commit that the server makes, under the key `server-commit`.
212    ///
213    /// The encoder writes the key only if the value is `Some`, and the
214    /// decoder reads an absent key as `None`. The value is boxed, so a
215    /// [`Message`] of another kind stays small.
216    pub server_commit: Option<Box<ServerCommit>>,
217}
218
219/// A commit that the server makes from a tree and the fields that the client
220/// sends, the value of the `server-commit` key of a `Commit`.
221///
222/// The value has the type `(sasas(ayay)ssa{sv}a{sv})`. Its members hold the
223/// fields in the order of this struct. The root dirtree and the root dirmeta
224/// make one `(ayay)` member. [`timestamp`](Self::timestamp) and
225/// [`orphan`](Self::orphan) are keys of the last member, a dict of options.
226///
227/// The server reads the tip of the branch under its update lock, and writes
228/// the commit with that tip as its parent. It moves the branch and creates
229/// each tag at the new commit. The `CommitReply` of a server commit holds
230/// one entry for the branch, then one entry for each tag. The `new` commit of
231/// each entry is the commit that the server wrote.
232#[derive(Debug, Clone, PartialEq, Eq)]
233pub struct ServerCommit {
234    /// The branch that the server moves to the new commit.
235    pub branch: String,
236    /// The tags that the server creates at the new commit, in order.
237    pub tags: Vec<String>,
238    /// The names that the commit binds and that get no ref, in order.
239    ///
240    /// The `ostree.ref-binding` of the commit holds the branch, each tag, and
241    /// each of these names.
242    pub bind_refs: Vec<String>,
243    /// The checksum of the root dirtree of the commit.
244    pub root_dirtree: Checksum,
245    /// The checksum of the root dirmeta of the commit.
246    pub root_dirmeta: Checksum,
247    /// The subject of the commit.
248    pub subject: String,
249    /// The body of the commit.
250    pub body: String,
251    /// The metadata entries of the client, in order.
252    ///
253    /// Each entry is a key and the bytes of a `v` in normal form: the bytes
254    /// of the value, a zero byte, and the type signature of the value.
255    /// [`to_bytes`](ostrya_gvariant::to_bytes) with [`Type::Variant`] gives
256    /// these bytes. The dict is data, and the rules of a protocol dict do not
257    /// apply to it: the decoder keeps each entry in order, also a key that
258    /// occurs two times. The decoder and the encoder check the bytes of each
259    /// entry and build no value tree.
260    pub metadata: Vec<(String, Vec<u8>)>,
261    /// The commit time in seconds since the Unix epoch, UTC, under the key
262    /// `timestamp`.
263    ///
264    /// `None` gives the clock of the server. The encoder writes the key only
265    /// if the value is `Some`.
266    pub timestamp: Option<u64>,
267    /// The flag that makes a commit with no parent, under the key `orphan`.
268    ///
269    /// The encoder writes the key only if the value is `true`, and the
270    /// decoder reads an absent key as `false`.
271    pub orphan: bool,
272}
273
274/// The `Error` message, which the server sends to report a failure.
275///
276/// The session ends after this message. The `Error` message converts to the
277/// [`Error`] variant of its code, and [`Error::to_message`] converts back.
278#[derive(Debug, Clone, PartialEq, Eq)]
279pub struct ErrorMessage {
280    /// The code of the failure.
281    pub code: ErrorCode,
282    /// The text of the failure for a human reader.
283    pub message: String,
284    /// The missing objects, for the code `missing-objects`.
285    ///
286    /// The key is `missing`. The encoder writes the key only if the list is
287    /// not empty. Each object is of type 1 to 4. For another type, encode and
288    /// decode return [`Error::Protocol`].
289    pub missing: Vec<ObjectName>,
290    /// The current state of the ref, for the code `ref-mismatch`.
291    ///
292    /// The keys are `ref` and `current`. If the code is `ref-mismatch` and
293    /// this field is `None`, encode and decode return [`Error::Protocol`]. The
294    /// decode of a body with one of the two keys alone also returns
295    /// [`Error::Protocol`].
296    pub current: Option<RefState>,
297}
298
299/// The first message of a pull client.
300#[derive(Debug, Clone, PartialEq, Eq)]
301pub struct PullHello {
302    /// The highest pull protocol version that the client speaks.
303    pub version: u32,
304    /// The name and version of the client, under the key `agent`.
305    pub agent: Option<String>,
306}
307
308/// The reply to a `PullHello`, with the pull version of the session.
309///
310/// The dict of the reply is empty in version 1. A decoder ignores a key that
311/// it does not know.
312#[derive(Debug, Clone, PartialEq, Eq)]
313pub struct PullHelloReply {
314    /// The pull protocol version of the session.
315    ///
316    /// It is the lower of the version of the `PullHello` and the highest
317    /// version of the server.
318    pub version: u32,
319}
320
321/// The reply to one `Get` or one `ListRefs`.
322#[derive(Debug, Clone, PartialEq, Eq)]
323pub struct GetReply {
324    /// The flag that is `true` if the server serves the path or the listing.
325    ///
326    /// If `found` is `true`, a body of chunks follows the reply, as
327    /// [Object stream](super#object-stream) states.
328    pub found: bool,
329    /// The length of the body, if the server knows it.
330    ///
331    /// A reply to a `ListRefs` must hold it, as the specification of
332    /// [`ListRefs`](https://github.com/growler/ostrya/blob/main/docs/format-reference.md#listrefs) states. If `found` is `false` and the length
333    /// is present, encode and decode return [`Error::Protocol`].
334    pub len: Option<u64>,
335}
336
337/// The `ListRefs` message: the entries of a ref listing request.
338///
339/// Each entry is a ref pattern of a
340/// [`RefSelector`](ostrya_core::RefSelector), with an optional leading `!`.
341/// The codec does not check the entries.
342/// [`MAX_REF_PATTERNS`](super::MAX_REF_PATTERNS),
343/// [`MAX_REF_ENTRY_PARTS`](super::MAX_REF_ENTRY_PARTS), and
344/// [`MAX_REF_ENTRY_LEN`](super::MAX_REF_ENTRY_LEN) are the limits of a
345/// request. The two lists share the limit of entries. The specification of
346/// [`ListRefs`](https://github.com/growler/ostrya/blob/main/docs/format-reference.md#listrefs)
347/// states the reply.
348#[derive(Debug, Clone, PartialEq, Eq, Default)]
349pub struct ListRefsRequest {
350    /// The entries that the server matches against the names of the local
351    /// refs.
352    pub refs: Vec<String>,
353    /// The entries that the server matches against `ID/NAME` of the
354    /// collection refs, under the key `collections`.
355    ///
356    /// `None` asks for no collection ref. The encoder writes the key only if
357    /// the value is `Some`, also for an empty list. An empty list selects
358    /// each collection ref.
359    pub collections: Option<Vec<String>>,
360}
361
362/// A message of the push or the pull protocol.
363///
364/// A later protocol version can add messages.
365#[derive(Debug, Clone, PartialEq, Eq)]
366#[non_exhaustive]
367pub enum Message {
368    /// The `Hello` message.
369    Hello(Hello),
370    /// The `HelloReply` message.
371    HelloReply(HelloReply),
372    /// The `Have` message, with the objects that the client offers.
373    ///
374    /// Each object is of type 1 to 4.
375    Have(Vec<ObjectName>),
376    /// The `HaveReply` message.
377    HaveReply(HaveReply),
378    /// The `ObjectHeader` message.
379    ObjectHeader(ObjectHeader),
380    /// The `ObjectsEnd` message.
381    ObjectsEnd,
382    /// The `ObjectsReply` message.
383    ObjectsReply(ObjectsReply),
384    /// The `Commit` message.
385    Commit(CommitRequest),
386    /// The `CommitReply` message, with one outcome for each ref update, or
387    /// for each ref of a [`ServerCommit`].
388    CommitReply(Vec<RefOutcome>),
389    /// The `Error` message.
390    Error(ErrorMessage),
391    /// The `Abort` message.
392    Abort,
393    /// The `PullHello` message.
394    PullHello(PullHello),
395    /// The `PullHelloReply` message.
396    PullHelloReply(PullHelloReply),
397    /// The `Get` message, with the path of one file.
398    ///
399    /// The path is relative to the repository root.
400    Get(String),
401    /// The `GetReply` message.
402    GetReply(GetReply),
403    /// The `ListRefs` message, with the entries of a ref listing request.
404    ListRefs(ListRefsRequest),
405}
406
407impl Message {
408    /// Returns the kind of the message.
409    pub fn kind(&self) -> Kind {
410        match self {
411            Message::Hello(_) => Kind::Hello,
412            Message::HelloReply(_) => Kind::HelloReply,
413            Message::Have(_) => Kind::Have,
414            Message::HaveReply(_) => Kind::HaveReply,
415            Message::ObjectHeader(_) => Kind::ObjectHeader,
416            Message::ObjectsEnd => Kind::ObjectsEnd,
417            Message::ObjectsReply(_) => Kind::ObjectsReply,
418            Message::Commit(_) => Kind::Commit,
419            Message::CommitReply(_) => Kind::CommitReply,
420            Message::Error(_) => Kind::Error,
421            Message::Abort => Kind::Abort,
422            Message::PullHello(_) => Kind::PullHello,
423            Message::PullHelloReply(_) => Kind::PullHelloReply,
424            Message::Get(_) => Kind::Get,
425            Message::GetReply(_) => Kind::GetReply,
426            Message::ListRefs(_) => Kind::ListRefs,
427        }
428    }
429
430    /// Encodes the body of the message, with no frame length and no kind byte.
431    ///
432    /// # Errors
433    ///
434    /// [`Error::Protocol`] if the message holds a value that it cannot carry:
435    ///
436    /// - a `HelloReply` whose `max_frame`, `max_have`, or `parallel_uploads`
437    ///   is out of range
438    /// - a `Have` entry or a `missing` object of a type other than 1 to 4, for
439    ///   example type 6
440    /// - an `ObjectHeader` of a type other than 1 to 4 or 6, or with
441    ///   [`Encoding::Deflate`] for an object that is not a file
442    /// - an `Error` message with the code `ref-mismatch` and no `current`
443    ///   state
444    /// - a `GetReply` whose `found` is `false` and that has a length
445    /// - a metadata entry of a [`ServerCommit`] whose bytes are not a `v` in
446    ///   normal form
447    /// - a string with an interior NUL byte, which the GVariant serializer
448    ///   refuses
449    pub fn encode_body(&self) -> Result<Vec<u8>> {
450        let (ty, value): (&Type, Value) = match self {
451            Message::Commit(c) => return encode_commit(c),
452            Message::ObjectsEnd => return Ok(Vec::new()),
453            Message::Abort => return Ok(vec![0]),
454            Message::Hello(h) => {
455                let mut opts = DictBuilder::new();
456                if let Some(agent) = &h.agent {
457                    opts.insert_str("agent", agent);
458                }
459                if let Some(collection) = &h.collection {
460                    opts.insert_str("collection", collection);
461                }
462                if h.one_way {
463                    opts.insert_bool("one-way", true);
464                }
465                let refs = h.refs.iter().cloned().map(Value::Str).collect();
466                let v = Value::Tuple(vec![
467                    Value::U32(h.version),
468                    opts.build(),
469                    Value::Array(refs),
470                ]);
471                (&HELLO, v)
472            }
473            Message::HelloReply(r) => {
474                check_limits(r.max_frame, r.max_have, r.parallel_uploads)?;
475                let mut opts = DictBuilder::new();
476                opts.insert_str("mode", &r.mode);
477                if let Some(id) = &r.collection_id {
478                    opts.insert_str("collection-id", id);
479                }
480                if let Some(collection) = &r.collection {
481                    opts.insert_str("collection", collection);
482                }
483                let encodings: Vec<String> =
484                    r.encodings.iter().map(|e| e.as_str().to_owned()).collect();
485                opts.insert("max-frame", Type::U32, Value::U32(r.max_frame))
486                    .insert("max-have", Type::U32, Value::U32(r.max_have))
487                    .insert_strv("encodings", &encodings)
488                    .insert(
489                        "parallel-uploads",
490                        Type::U32,
491                        Value::U32(r.parallel_uploads),
492                    );
493                let refs = r
494                    .refs
495                    .iter()
496                    .map(|s| Value::Tuple(vec![Value::Str(s.name.clone()), maybe_value(s.commit)]))
497                    .collect();
498                let v = Value::Tuple(vec![
499                    Value::U32(r.version),
500                    opts.build(),
501                    Value::Array(refs),
502                ]);
503                (&HELLO_REPLY, v)
504            }
505            Message::Have(names) => (&OBJECT_NAMES, object_names_value(names)?),
506            Message::HaveReply(r) => (&BYTES, Value::Bytes(r.bitmap.clone())),
507            Message::ObjectHeader(h) => {
508                check_header(&h.name, h.encoding)?;
509                let v = Value::Tuple(vec![
510                    Value::Byte(h.name.ty.as_u32() as u8),
511                    Value::Bytes(h.name.checksum.as_bytes().to_vec()),
512                    Value::Byte(h.encoding.as_u8()),
513                ]);
514                (&OBJECT_HEADER, v)
515            }
516            Message::ObjectsReply(r) => {
517                let v = Value::Tuple(vec![Value::U32(r.objects), Value::U64(r.payload_bytes)]);
518                (&OBJECTS_REPLY, v)
519            }
520            Message::CommitReply(outcomes) => {
521                let v = outcomes
522                    .iter()
523                    .map(|o| {
524                        Value::Tuple(vec![
525                            Value::Str(o.name.clone()),
526                            maybe_value(o.old),
527                            maybe_value(o.new),
528                        ])
529                    })
530                    .collect();
531                (&COMMIT_REPLY, Value::Array(v))
532            }
533            Message::Error(e) => {
534                check_error(e)?;
535                let mut detail = DictBuilder::new();
536                if !e.missing.is_empty() {
537                    detail.insert(
538                        "missing",
539                        OBJECT_NAMES.clone(),
540                        object_names_value(&e.missing)?,
541                    );
542                }
543                if let Some(state) = &e.current {
544                    detail.insert_str("ref", &state.name).insert(
545                        "current",
546                        MAYBE_CHECKSUM.clone(),
547                        maybe_value(state.commit),
548                    );
549                }
550                let v = Value::Tuple(vec![
551                    Value::Str(e.code.as_str().to_owned()),
552                    Value::Str(e.message.clone()),
553                    detail.build(),
554                ]);
555                (&ERROR, v)
556            }
557            Message::PullHello(h) => {
558                let mut opts = DictBuilder::new();
559                if let Some(agent) = &h.agent {
560                    opts.insert_str("agent", agent);
561                }
562                let v = Value::Tuple(vec![Value::U32(h.version), opts.build()]);
563                (&PULL_HELLO, v)
564            }
565            Message::PullHelloReply(r) => {
566                let v = Value::Tuple(vec![Value::U32(r.version), DictBuilder::new().build()]);
567                (&PULL_HELLO, v)
568            }
569            Message::Get(path) => (&Type::Str, Value::Str(path.clone())),
570            Message::GetReply(r) => {
571                check_get_reply(r)?;
572                let len = Value::Maybe(r.len.map(|n| Box::new(Value::U64(n))));
573                (&GET_REPLY, Value::Tuple(vec![Value::Bool(r.found), len]))
574            }
575            Message::ListRefs(r) => {
576                let mut opts = DictBuilder::new();
577                if let Some(collections) = &r.collections {
578                    opts.insert_strv("collections", collections);
579                }
580                let refs = r.refs.iter().cloned().map(Value::Str).collect();
581                (
582                    &LIST_REFS,
583                    Value::Tuple(vec![Value::Array(refs), opts.build()]),
584                )
585            }
586        };
587        to_bytes(ty, &value).map_err(encode_error)
588    }
589
590    /// Decodes the body of a message of `kind`.
591    ///
592    /// The decoder borrows strings and byte arrays from `body` and reads each
593    /// array one entry at a time. It allocates the decoded message. It checks
594    /// a dict value under a key that it does not know for normal form in
595    /// place, with no value tree, and then drops it. If a dict holds a key
596    /// two times, the first value counts, and the decoder checks each later
597    /// value for normal form alone. It checks each metadata entry of a
598    /// server commit in place and copies its bytes, with no value tree.
599    /// [`MAX_FRAME`](super::MAX_FRAME) states the measured peaks.
600    ///
601    /// # Errors
602    ///
603    /// [`Error::Protocol`] if the body is malformed:
604    ///
605    /// - the body is not in normal form for the type of `kind`
606    /// - an `ObjectsEnd` body is not empty, or an `Abort` body is not the one
607    ///   byte `0x00`
608    /// - a known dict key holds a value of the wrong type
609    /// - a `HelloReply` has no `mode`, `max-frame`, `max-have`, `encodings`,
610    ///   or `parallel-uploads` key, or a limit is out of range
611    /// - a checksum is not 32 bytes long
612    /// - an object type or an encoding byte is not allowed in the message
613    /// - a ref update of a `Commit` has an unknown expected state, or a state
614    ///   that does not match its expected commit
615    /// - the value under `server-commit` of a `Commit`, or under `timestamp`
616    ///   or `orphan` of its options, has the wrong type
617    /// - an `Error` message has an unknown code, has one of the keys `ref`
618    ///   and `current` alone, or has the code `ref-mismatch` with neither
619    /// - a `GetReply` whose `found` is `false` has a length
620    pub fn decode(kind: Kind, body: &[u8]) -> Result<Message> {
621        Ok(match kind {
622            Kind::ObjectsEnd => {
623                if !body.is_empty() {
624                    return Err(protocol("ObjectsEnd body is not empty"));
625                }
626                Message::ObjectsEnd
627            }
628            Kind::Abort => {
629                if body != [0] {
630                    return Err(protocol("Abort body is not the unit tuple"));
631                }
632                Message::Abort
633            }
634            Kind::Hello => {
635                let (version, opts, refs): (u32, Dict, ArrayIter<&str>) = parse_body(body)?;
636                let [agent, collection, one_way] = dict(opts, ["agent", "collection", "one-way"])?;
637                let agent: Option<&str> = field(agent, "agent", &Type::Str)?;
638                let collection: Option<&str> = field(collection, "collection", &Type::Str)?;
639                let one_way = field(one_way, "one-way", &Type::Bool)?.unwrap_or(false);
640                Message::Hello(Hello {
641                    version,
642                    agent: agent.map(str::to_owned),
643                    refs: collect(refs, |r| Ok(r.to_owned()))?,
644                    collection: collection.map(str::to_owned),
645                    one_way,
646                })
647            }
648            Kind::HelloReply => Message::HelloReply(decode_hello_reply(body)?),
649            Kind::Have => Message::Have(object_names(parse_body(body)?)?),
650            Kind::HaveReply => {
651                let bitmap: &[u8] = parse_body(body)?;
652                Message::HaveReply(HaveReply {
653                    bitmap: bitmap.to_vec(),
654                })
655            }
656            Kind::ObjectHeader => {
657                let (ty, sum, enc): (u8, &[u8], u8) = parse_body(body)?;
658                let name = object_name((ty, sum), header_type)?;
659                let encoding = Encoding::from_u8(enc)?;
660                check_header(&name, encoding)?;
661                Message::ObjectHeader(ObjectHeader { name, encoding })
662            }
663            Kind::ObjectsReply => {
664                let (objects, payload_bytes) = parse_body(body)?;
665                Message::ObjectsReply(ObjectsReply {
666                    objects,
667                    payload_bytes,
668                })
669            }
670            Kind::Commit => {
671                let (updates, opts): (ArrayIter<UpdateView>, Dict) = parse_body(body)?;
672                let updates = collect(updates, decode_update)?;
673                let [force, server_commit] = dict(opts, ["force", "server-commit"])?;
674                let force = field(force, "force", &Type::Bool)?.unwrap_or(false);
675                let server_commit = field(server_commit, "server-commit", &SERVER_COMMIT)?
676                    .map(decode_server_commit)
677                    .transpose()?
678                    .map(Box::new);
679                Message::Commit(CommitRequest {
680                    updates,
681                    force,
682                    server_commit,
683                })
684            }
685            Kind::CommitReply => {
686                let outcomes: ArrayIter<(&str, MaybeBytes, MaybeBytes)> = parse_body(body)?;
687                Message::CommitReply(collect(outcomes, |(name, old, new)| {
688                    Ok(RefOutcome {
689                        name: name.to_owned(),
690                        old: maybe_checksum(old)?,
691                        new: maybe_checksum(new)?,
692                    })
693                })?)
694            }
695            Kind::Error => Message::Error(decode_error(body)?),
696            Kind::PullHello => {
697                let (version, opts): (u32, Dict) = parse_body(body)?;
698                let [agent] = dict(opts, ["agent"])?;
699                let agent: Option<&str> = field(agent, "agent", &Type::Str)?;
700                Message::PullHello(PullHello {
701                    version,
702                    agent: agent.map(str::to_owned),
703                })
704            }
705            Kind::PullHelloReply => {
706                let (version, opts): (u32, Dict) = parse_body(body)?;
707                let [] = dict(opts, [])?;
708                Message::PullHelloReply(PullHelloReply { version })
709            }
710            Kind::Get => {
711                let path: &str = parse_body(body)?;
712                Message::Get(path.to_owned())
713            }
714            Kind::GetReply => {
715                let (found, len): (bool, MaybeU64) = parse_body(body)?;
716                let r = GetReply { found, len: len.0 };
717                check_get_reply(&r)?;
718                Message::GetReply(r)
719            }
720            Kind::ListRefs => {
721                let (refs, opts): (ArrayIter<&str>, Dict) = parse_body(body)?;
722                let [collections] = dict(opts, ["collections"])?;
723                let collections: Option<ArrayIter<&str>> =
724                    field(collections, "collections", &STRV)?;
725                Message::ListRefs(ListRefsRequest {
726                    refs: collect(refs, |e| Ok(e.to_owned()))?,
727                    collections: collections
728                        .map(|entries| collect(entries, |e| Ok(e.to_owned())))
729                        .transpose()?,
730                })
731            }
732        })
733    }
734}
735
736/// Checks the limits of a `HelloReply`.
737///
738/// `max-frame` must be in `MIN_FRAME_LIMIT..=MAX_FRAME_LIMIT`, and `max-have`
739/// and `parallel-uploads` must be at least 1. Otherwise the function returns
740/// `Error::Protocol`.
741fn check_limits(max_frame: u32, max_have: u32, parallel_uploads: u32) -> Result<()> {
742    if !(MIN_FRAME_LIMIT..=MAX_FRAME_LIMIT).contains(&max_frame) {
743        return Err(protocol(format!("max-frame {max_frame} is out of range")));
744    }
745    if max_have == 0 || parallel_uploads == 0 {
746        return Err(protocol("max-have and parallel-uploads must be at least 1"));
747    }
748    Ok(())
749}
750
751/// Checks that a `ref-mismatch` message carries the ref and its current
752/// state.
753fn check_error(e: &ErrorMessage) -> Result<()> {
754    if e.code == ErrorCode::RefMismatch && e.current.is_none() {
755        return Err(protocol("ref-mismatch lacks ref and current"));
756    }
757    Ok(())
758}
759
760fn decode_hello_reply(body: &[u8]) -> Result<HelloReply> {
761    let (version, opts, refs): (u32, Dict, ArrayIter<(&str, MaybeBytes)>) = parse_body(body)?;
762    let [
763        mode,
764        collection_id,
765        collection,
766        max_frame,
767        max_have,
768        encodings,
769        parallel_uploads,
770    ] = dict(
771        opts,
772        [
773            "mode",
774            "collection-id",
775            "collection",
776            "max-frame",
777            "max-have",
778            "encodings",
779            "parallel-uploads",
780        ],
781    )?;
782    let mode: &str = required(mode, "mode", &Type::Str)?;
783    let collection_id: Option<&str> = field(collection_id, "collection-id", &Type::Str)?;
784    let collection: Option<&str> = field(collection, "collection", &Type::Str)?;
785    let max_frame = required(max_frame, "max-frame", &Type::U32)?;
786    let max_have = required(max_have, "max-have", &Type::U32)?;
787    let parallel_uploads = required(parallel_uploads, "parallel-uploads", &Type::U32)?;
788    check_limits(max_frame, max_have, parallel_uploads)?;
789    let names: ArrayIter<&str> = required(encodings, "encodings", &STRV)?;
790    let mut encodings = Vec::new();
791    for name in names {
792        encodings.extend(Encoding::from_name(name.map_err(malformed)?));
793    }
794    let refs = collect(refs, |(name, commit)| {
795        Ok(RefState {
796            name: name.to_owned(),
797            commit: maybe_checksum(commit)?,
798        })
799    })?;
800    Ok(HelloReply {
801        version,
802        mode: mode.to_owned(),
803        collection_id: collection_id.map(str::to_owned),
804        collection: collection.map(str::to_owned),
805        max_frame,
806        max_have,
807        encodings,
808        parallel_uploads,
809        refs,
810    })
811}
812
813/// A `(symaymay)` ref update, as the body holds it.
814type UpdateView<'a> = (&'a str, u8, MaybeBytes<'a>, MaybeBytes<'a>);
815
816fn decode_update((name, state, expected, new): UpdateView) -> Result<RefUpdate> {
817    let expected = match (state, maybe_checksum(expected)?) {
818        (0, None) => Expected::Absent,
819        (1, Some(c)) => Expected::Commit(c),
820        (2, None) => Expected::Any,
821        (s @ 0..=2, _) => {
822            return Err(protocol(format!(
823                "expected state {s} does not match its commit"
824            )));
825        }
826        (s, _) => return Err(protocol(format!("unknown expected state {s}"))),
827    };
828    Ok(RefUpdate {
829        name: name.to_owned(),
830        expected,
831        new: maybe_checksum(new)?,
832    })
833}
834
835/// Returns the [`Error::Protocol`] of an encode that fails.
836fn encode_error(e: ostrya_gvariant::Error) -> Error {
837    protocol(format!("encode: {e}"))
838}
839
840/// Returns the bytes of a `v` that holds `value` of the type `ty`.
841fn variant_bytes(ty: Type, value: Value) -> Result<Vec<u8>> {
842    to_bytes(&Type::Variant, &Value::variant(ty, value)).map_err(encode_error)
843}
844
845/// Returns the `a{sv}` entries of `entries`, each a key and the bytes of a
846/// `v`, in the form that the typed encoder writes.
847fn dict_entries<'a>(
848    entries: &'a [(&'static str, Vec<u8>)],
849) -> Vec<(&'static str, VariantSlice<'a>)> {
850    entries
851        .iter()
852        .map(|(key, value)| (*key, VariantSlice { inner: value }))
853        .collect()
854}
855
856/// Encodes the body of a `Commit` message.
857///
858/// The typed encoder writes the metadata of a server commit from its bytes,
859/// so the encode builds no value tree for it, and the depth of a metadata
860/// value inside the message does not count against the depth limit of the
861/// serializer.
862fn encode_commit(c: &CommitRequest) -> Result<Vec<u8>> {
863    encode_commit_parts(&c.updates, c.force, c.server_commit.as_deref())
864}
865
866/// Returns the length of the frame of a `Commit` that holds the server
867/// commit `sc` and no ref update: the kind byte and the body.
868///
869/// The bytes of each metadata entry of `sc` must be a `v` in normal form,
870/// else the call returns [`Error::Protocol`].
871pub(crate) fn server_commit_frame_len(sc: &ServerCommit) -> Result<u64> {
872    Ok(encode_commit_parts(&[], false, Some(sc))?.len() as u64 + 1)
873}
874
875/// Checks that a commit can hold each metadata value of the server commit
876/// `sc`.
877///
878/// A commit holds the depth limit of 128 levels of containers, counted from
879/// its metadata dict. In that dict, the `v` of each value is under two
880/// containers, the dict and its entry. A tuple with one member of variable
881/// size holds the bytes of the member and no framing, so the bytes of a `v`
882/// are also the bytes of `((v))`. The check reads the bytes as that type and
883/// builds no value tree.
884///
885/// Bytes that are not a `v` in normal form are [`Error::Protocol`], as the
886/// encode of the message gives. A `v` that a commit cannot hold is
887/// [`Error::InvalidInput`].
888pub(crate) fn check_server_commit_metadata(sc: &ServerCommit) -> Result<()> {
889    for (key, value) in &sc.metadata {
890        let Err(deep) = ostrya_gvariant::validate(&VALUE_IN_COMMIT, value) else {
891            continue;
892        };
893        if let Err(e) = ostrya_gvariant::validate(&Type::Variant, value) {
894            return Err(protocol(format!("encode: metadata entry '{key}': {e}")));
895        }
896        return Err(Error::InvalidInput(format!(
897            "a commit cannot hold the metadata value under '{key}': {deep}"
898        )));
899    }
900    Ok(())
901}
902
903/// Returns the length of the frame of the longest `CommitReply` to the
904/// server commit `sc`: the kind byte and the body.
905///
906/// The reply holds the branch with an old commit and each tag with no old
907/// commit, each with a new commit.
908pub(crate) fn server_commit_reply_frame_len(sc: &ServerCommit) -> Result<u64> {
909    let any_commit = Some(Checksum::from_bytes([0; 32]));
910    let refs = std::iter::once(RefOutcome {
911        name: sc.branch.clone(),
912        old: any_commit,
913        new: any_commit,
914    })
915    .chain(sc.tags.iter().map(|tag| RefOutcome {
916        name: tag.clone(),
917        old: None,
918        new: any_commit,
919    }))
920    .collect();
921    Ok(Message::CommitReply(refs).encode_body()?.len() as u64 + 1)
922}
923
924/// Encodes the body of a `Commit` message from its parts.
925fn encode_commit_parts(
926    updates: &[RefUpdate],
927    force: bool,
928    server_commit: Option<&ServerCommit>,
929) -> Result<Vec<u8>> {
930    let updates = updates
931        .iter()
932        .map(|u| {
933            let (state, expected) = match u.expected {
934                Expected::Absent => (0, None),
935                Expected::Commit(c) => (1, Some(c)),
936                Expected::Any => (2, None),
937            };
938            Value::Tuple(vec![
939                Value::Str(u.name.clone()),
940                Value::Byte(state),
941                maybe_value(expected),
942                maybe_value(u.new),
943            ])
944        })
945        .collect();
946    let updates = to_bytes(&UPDATES, &Value::Array(updates)).map_err(encode_error)?;
947    let mut opts = Vec::new();
948    if force {
949        opts.push(("force", variant_bytes(Type::Bool, Value::Bool(true))?));
950    }
951    if let Some(sc) = server_commit {
952        let mut value = server_commit_bytes(sc)?;
953        value.push(0);
954        value.extend_from_slice(SERVER_COMMIT_SIGNATURE.as_bytes());
955        opts.push(("server-commit", value));
956    }
957    encode_to_vec(&(updates.as_slice(), Slice(&dict_entries(&opts)))).map_err(encode_error)
958}
959
960/// Returns the bytes of the `server-commit` value of a `Commit`.
961///
962/// The bytes of each metadata entry must be a `v` in normal form, else the
963/// call returns [`Error::Protocol`].
964fn server_commit_bytes(sc: &ServerCommit) -> Result<Vec<u8>> {
965    let tags: Vec<&str> = sc.tags.iter().map(String::as_str).collect();
966    let bind_refs: Vec<&str> = sc.bind_refs.iter().map(String::as_str).collect();
967    let metadata = sc
968        .metadata
969        .iter()
970        .map(|(key, value)| {
971            ostrya_gvariant::validate(&Type::Variant, value)
972                .map_err(|e| protocol(format!("encode: metadata entry '{key}': {e}")))?;
973            Ok((key.as_str(), VariantSlice { inner: value }))
974        })
975        .collect::<Result<Vec<_>>>()?;
976    let mut opts = Vec::new();
977    if let Some(timestamp) = sc.timestamp {
978        opts.push((
979            "timestamp",
980            variant_bytes(Type::U64, Value::U64(timestamp))?,
981        ));
982    }
983    if sc.orphan {
984        opts.push(("orphan", variant_bytes(Type::Bool, Value::Bool(true))?));
985    }
986    encode_to_vec(&(
987        sc.branch.as_str(),
988        Slice(&tags),
989        Slice(&bind_refs),
990        (sc.root_dirtree, sc.root_dirmeta),
991        sc.subject.as_str(),
992        sc.body.as_str(),
993        Slice(&metadata),
994        Slice(&dict_entries(&opts)),
995    ))
996    .map_err(encode_error)
997}
998
999/// A `(sasas(ayay)ssa{sv}a{sv})` server commit, as the body holds it.
1000type ServerCommitView<'a> = (
1001    &'a str,
1002    ArrayIter<'a, &'a str>,
1003    ArrayIter<'a, &'a str>,
1004    (&'a [u8], &'a [u8]),
1005    &'a str,
1006    &'a str,
1007    ArrayIter<'a, (&'a str, VariantSlice<'a>)>,
1008    Dict<'a>,
1009);
1010
1011/// Decodes the `server-commit` value of a `Commit`.
1012///
1013/// The decoder checks that the bytes of each entry of the metadata dict are
1014/// a `v` in normal form, and keeps the bytes, in order, also a key that occurs
1015/// two times. It builds no value tree.
1016fn decode_server_commit(
1017    (branch, tags, bind_refs, (dirtree, dirmeta), subject, body, metadata, opts): ServerCommitView,
1018) -> Result<ServerCommit> {
1019    let [timestamp, orphan] = dict(opts, ["timestamp", "orphan"])?;
1020    let timestamp = field(timestamp, "timestamp", &Type::U64)?;
1021    let orphan = field(orphan, "orphan", &Type::Bool)?.unwrap_or(false);
1022    let metadata = collect(metadata, |(key, value)| {
1023        ostrya_gvariant::validate(&Type::Variant, value.inner).map_err(malformed)?;
1024        Ok((key.to_owned(), value.inner.to_vec()))
1025    })?;
1026    Ok(ServerCommit {
1027        branch: branch.to_owned(),
1028        tags: collect(tags, |t| Ok(t.to_owned()))?,
1029        bind_refs: collect(bind_refs, |n| Ok(n.to_owned()))?,
1030        root_dirtree: checksum(dirtree)?,
1031        root_dirmeta: checksum(dirmeta)?,
1032        subject: subject.to_owned(),
1033        body: body.to_owned(),
1034        metadata,
1035        timestamp,
1036        orphan,
1037    })
1038}
1039
1040fn decode_error(body: &[u8]) -> Result<ErrorMessage> {
1041    let (name, message, detail): (&str, &str, Dict) = parse_body(body)?;
1042    let code =
1043        ErrorCode::from_name(name).ok_or_else(|| protocol(format!("unknown error code {name}")))?;
1044    let [missing, ref_name, current] = dict(detail, ["missing", "ref", "current"])?;
1045    let missing = match field(missing, "missing", &OBJECT_NAMES)? {
1046        Some(names) => object_names(names)?,
1047        None => Vec::new(),
1048    };
1049    let ref_name: Option<&str> = field(ref_name, "ref", &Type::Str)?;
1050    let current = match (ref_name, field(current, "current", &MAYBE_CHECKSUM)?) {
1051        (Some(name), Some(commit)) => Some(RefState {
1052            name: name.to_owned(),
1053            commit: maybe_checksum(commit)?,
1054        }),
1055        (None, None) => None,
1056        _ => return Err(protocol("Error carries one of ref and current alone")),
1057    };
1058    let e = ErrorMessage {
1059        code,
1060        message: message.to_owned(),
1061        missing,
1062        current,
1063    };
1064    check_error(&e)?;
1065    Ok(e)
1066}
1067
1068/// Checks that a reply whose `found` is `false` carries no length.
1069fn check_get_reply(r: &GetReply) -> Result<()> {
1070    if !r.found && r.len.is_some() {
1071        return Err(protocol("GetReply with found false carries a length"));
1072    }
1073    Ok(())
1074}
1075
1076/// Checks the object type of an `ObjectHeader`, and that `deflate` occurs
1077/// for a file object alone.
1078fn check_header(name: &ObjectName, encoding: Encoding) -> Result<()> {
1079    if !header_type(name.ty) {
1080        return Err(protocol(format!(
1081            "object type {} is not allowed in ObjectHeader",
1082            name.ty.as_u32()
1083        )));
1084    }
1085    if encoding == Encoding::Deflate && name.ty != ObjectType::File {
1086        return Err(protocol("deflate is allowed for a file object alone"));
1087    }
1088    Ok(())
1089}
1090
1091/// The length of an `ObjectHeader` frame: the 4 length bytes, the kind, and
1092/// the 35 bytes of the body.
1093pub(super) const OBJECT_HEADER_FRAME: usize = 40;
1094
1095/// Builds the frame of an `ObjectHeader` with no allocation.
1096///
1097/// The body `(yayy)` is the type, the 32 checksum bytes, the encoding, and
1098/// one framing offset: the end of the checksum array, 33. The bytes equal the
1099/// length, the kind, and the bytes of [`Message::encode_body`].
1100pub(super) fn object_header_frame(h: &ObjectHeader) -> Result<[u8; OBJECT_HEADER_FRAME]> {
1101    check_header(&h.name, h.encoding)?;
1102    let mut frame = [0u8; OBJECT_HEADER_FRAME];
1103    frame[..4].copy_from_slice(&(OBJECT_HEADER_FRAME as u32 - 4).to_be_bytes());
1104    frame[4] = Kind::ObjectHeader.as_u8();
1105    frame[5] = h.name.ty.as_u32() as u8;
1106    frame[6..38].copy_from_slice(h.name.checksum.as_bytes());
1107    frame[38] = h.encoding.as_u8();
1108    frame[39] = 33;
1109    Ok(frame)
1110}
1111
1112/// The length of the longest `GetReply` frame: the 4 length bytes, the
1113/// kind, and the 16 bytes of a body with a length.
1114pub(super) const GET_REPLY_FRAME: usize = 21;
1115
1116/// Builds the frame of a `GetReply` with no allocation.
1117///
1118/// The function also returns the number of bytes in use: 13 with no length,
1119/// 21 with one.
1120///
1121/// The body `(bmt)` is the found byte, 7 bytes of padding to the alignment
1122/// of the `mt`, and, if there is a length, its 8 bytes in little-endian
1123/// order. A fixed-size first member and a last member take no framing
1124/// offset. The bytes equal the length, the kind, and the bytes of
1125/// [`Message::encode_body`].
1126pub(super) fn get_reply_frame(r: &GetReply) -> Result<([u8; GET_REPLY_FRAME], usize)> {
1127    check_get_reply(r)?;
1128    let mut frame = [0u8; GET_REPLY_FRAME];
1129    let used = match r.len {
1130        Some(len) => {
1131            frame[13..].copy_from_slice(&len.to_le_bytes());
1132            GET_REPLY_FRAME
1133        }
1134        None => 13,
1135    };
1136    frame[..4].copy_from_slice(&(used as u32 - 4).to_be_bytes());
1137    frame[4] = Kind::GetReply.as_u8();
1138    frame[5] = u8::from(r.found);
1139    Ok((frame, used))
1140}
1141
1142fn object_names_value(names: &[ObjectName]) -> Result<Value> {
1143    if let Some(bad) = names.iter().find(|n| !have_type(n.ty)) {
1144        return Err(protocol(format!(
1145            "object type {} is not allowed in an object list",
1146            bad.ty.as_u32()
1147        )));
1148    }
1149    Ok(Value::Array(names.iter().map(object_name_value).collect()))
1150}
1151
1152fn object_names(names: ArrayIter<(u8, &[u8])>) -> Result<Vec<ObjectName>> {
1153    collect(names, |e| object_name(e, have_type))
1154}
1155
1156fn malformed(e: ostrya_gvariant::Error) -> Error {
1157    protocol(format!("malformed body: {e}"))
1158}
1159
1160fn parse_body<'a, T: GvDecode<'a>>(body: &'a [u8]) -> Result<T> {
1161    T::decode(body).map_err(malformed)
1162}
1163
1164/// Decodes every entry of `items` and maps it with `f`.
1165///
1166/// A first pass counts the entries, so the function allocates the result
1167/// once, at its final size.
1168fn collect<'a, E: GvDecode<'a> + Copy, T>(
1169    items: ArrayIter<'a, E>,
1170    mut f: impl FnMut(E) -> Result<T>,
1171) -> Result<Vec<T>> {
1172    let mut out = Vec::with_capacity(items.count());
1173    for e in items {
1174        out.push(f(e.map_err(malformed)?)?);
1175    }
1176    Ok(out)
1177}
1178
1179fn maybe_checksum(m: MaybeBytes) -> Result<Option<Checksum>> {
1180    m.0.map(checksum).transpose()
1181}
1182
1183/// A `may` in the body: no bytes for `None`, or the bytes of the array and a
1184/// zero byte.
1185#[derive(Clone, Copy)]
1186struct MaybeBytes<'a>(Option<&'a [u8]>);
1187
1188impl GvType for MaybeBytes<'_> {
1189    const ALIGNMENT: usize = 1;
1190    const FIXED_SIZE: Option<usize> = None;
1191}
1192
1193impl<'a> GvDecode<'a> for MaybeBytes<'a> {
1194    fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1195        match data.split_last() {
1196            None => Ok(MaybeBytes(None)),
1197            Some((0, rest)) => Ok(MaybeBytes(Some(rest))),
1198            Some(_) => Err(ostrya_gvariant::Error::NotNormal(
1199                "maybe lacks its terminating zero byte",
1200            )),
1201        }
1202    }
1203}
1204
1205/// An `mt` in the body: no bytes for `None`, or the 8 bytes of the `t`.
1206///
1207/// A maybe of a fixed-size type has no terminating zero byte.
1208struct MaybeU64(Option<u64>);
1209
1210impl GvType for MaybeU64 {
1211    const ALIGNMENT: usize = 8;
1212    const FIXED_SIZE: Option<usize> = None;
1213}
1214
1215impl<'a> GvDecode<'a> for MaybeU64 {
1216    fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1217        match data.len() {
1218            0 => Ok(MaybeU64(None)),
1219            8 => u64::decode(data).map(|n| MaybeU64(Some(n))),
1220            _ => Err(ostrya_gvariant::Error::NotNormal(
1221                "maybe of a u64 is not 0 or 8 bytes",
1222            )),
1223        }
1224    }
1225}
1226
1227/// A `v` in the body: the type of the child and the child bytes, not yet
1228/// decoded.
1229struct RawVariant<'a> {
1230    ty: Type,
1231    child: &'a [u8],
1232}
1233
1234impl GvType for RawVariant<'_> {
1235    const ALIGNMENT: usize = 8;
1236    const FIXED_SIZE: Option<usize> = None;
1237}
1238
1239impl<'a> GvDecode<'a> for RawVariant<'a> {
1240    fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1241        let not_normal = ostrya_gvariant::Error::NotNormal;
1242        let sep = data
1243            .iter()
1244            .rposition(|&b| b == 0)
1245            .ok_or(not_normal("variant lacks a type separator"))?;
1246        let signature = std::str::from_utf8(&data[sep + 1..])
1247            .map_err(|_| not_normal("variant type signature is not UTF-8"))?;
1248        let ty =
1249            Type::parse(signature).map_err(|_| not_normal("variant type signature is invalid"))?;
1250        Ok(RawVariant {
1251            ty,
1252            child: &data[..sep],
1253        })
1254    }
1255}
1256
1257/// An `a{sv}` in the body.
1258type Dict<'a> = ArrayIter<'a, (&'a str, RawVariant<'a>)>;
1259
1260/// A `v` in the body as its bytes, not yet checked.
1261#[derive(Clone, Copy)]
1262struct VariantSlice<'a> {
1263    inner: &'a [u8],
1264}
1265
1266impl GvType for VariantSlice<'_> {
1267    const ALIGNMENT: usize = 8;
1268    const FIXED_SIZE: Option<usize> = None;
1269}
1270
1271impl<'a> GvDecode<'a> for VariantSlice<'a> {
1272    fn decode(data: &'a [u8]) -> ostrya_gvariant::Result<Self> {
1273        Ok(VariantSlice { inner: data })
1274    }
1275}
1276
1277impl GvEncode for VariantSlice<'_> {
1278    fn encode(&self, out: &mut Vec<u8>) -> ostrya_gvariant::Result<()> {
1279        out.extend_from_slice(self.inner);
1280        Ok(())
1281    }
1282}
1283
1284/// Returns the first entry of each of `keys` in `entries`.
1285///
1286/// The function checks every other entry for normal form and then drops it.
1287/// The caller decodes each returned entry with [`field`].
1288fn dict<'a, const N: usize>(
1289    entries: Dict<'a>,
1290    keys: [&str; N],
1291) -> Result<[Option<RawVariant<'a>>; N]> {
1292    let mut found = [const { None }; N];
1293    for entry in entries {
1294        let (key, value) = entry.map_err(malformed)?;
1295        match keys.iter().position(|k| *k == key) {
1296            Some(i) if found[i].is_none() => found[i] = Some(value),
1297            _ => {
1298                ostrya_gvariant::validate(&value.ty, value.child).map_err(malformed)?;
1299            }
1300        }
1301    }
1302    Ok(found)
1303}
1304
1305/// Returns the value of the dict entry `key`.
1306///
1307/// If the key is absent, the function returns `Ok(None)`. If the variant
1308/// does not hold `ty`, it returns `Error::Protocol`.
1309fn field<'a, T: GvDecode<'a>>(
1310    entry: Option<RawVariant<'a>>,
1311    key: &str,
1312    ty: &Type,
1313) -> Result<Option<T>> {
1314    let Some(v) = entry else {
1315        return Ok(None);
1316    };
1317    if v.ty != *ty {
1318        return Err(protocol(format!("key {key} has the wrong type")));
1319    }
1320    T::decode(v.child).map(Some).map_err(malformed)
1321}
1322
1323/// Returns the value of the `HelloReply` key `key`, which must be present.
1324///
1325/// If the key is absent, the function returns `Error::Protocol`.
1326fn required<'a, T: GvDecode<'a>>(entry: Option<RawVariant<'a>>, key: &str, ty: &Type) -> Result<T> {
1327    field(entry, key, ty)?.ok_or_else(|| protocol(format!("HelloReply lacks {key}")))
1328}