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