Skip to main content

moqtap_codec/draft17/
data_stream.rs

1//! Draft-17 data stream header encoding and decoding.
2//!
3//! Subgroup header type byte: 0b00X1XXXX (bit 4 always set)
4//!   - bit 0 (0x01): PROPERTIES
5//!   - bits 1-2 (0x06): SUBGROUP_ID_MODE (0=zero, 1=first_obj, 2=explicit, 3=reserved)
6//!   - bit 3 (0x08): END_OF_GROUP
7//!   - bit 5 (0x20): DEFAULT_PRIORITY (no priority byte)
8//!
9//! Datagram type byte: 0b00X0XXXX (bit 4 always 0)
10//!   - bit 0 (0x01): PROPERTIES
11//!   - bit 1 (0x02): END_OF_GROUP
12//!   - bit 2 (0x04): ZERO_OBJECT_ID (object_id=0, field omitted)
13//!   - bit 3 (0x08): DEFAULT_PRIORITY (no priority byte)
14//!   - bit 5 (0x20): STATUS (status byte replaces payload)
15//!
16//! Neither range is fully populated. Draft-17 Sections 10.4.2 and 10.3.1 each
17//! close with a list of type values an endpoint "MUST close the session with a
18//! PROTOCOL_VIOLATION" on receiving, and the two figures spell the surviving
19//! values out: `0x10..0x15 / 0x18..0x1D / 0x30..0x35 / 0x38..0x3D` for a
20//! subgroup header, `0x00..0x0F / 0x20..0x21 / 0x24..0x25 / 0x28..0x29 /
21//! 0x2C..0x2D` for a datagram. Both decoders refuse everything else, so a
22//! header this module hands back always describes a framing the draft defines.
23//!
24//! Fetch header: stream type 0x05 + request_id, followed by objects whose
25//! fields are named by a Serialization Flags varint rather than all being
26//! present — see [`FetchObjectHeader`].
27
28use bytes::{Buf, BufMut};
29
30use super::types::ObjectStatus;
31use crate::error::CodecError;
32use crate::varint::{Moqt17 as Wire, VarInt};
33
34/// Advance `buf` past `len` bytes without copying them.
35fn skip(buf: &mut impl Buf, len: u64) -> Result<(), CodecError> {
36    let len = usize::try_from(len).map_err(|_| CodecError::UnexpectedEnd)?;
37    if buf.remaining() < len {
38        return Err(CodecError::UnexpectedEnd);
39    }
40    buf.advance(len);
41    Ok(())
42}
43
44/// Turn a wire Object Status code into an [`ObjectStatus`], refusing one
45/// draft-17 does not assign.
46///
47/// Draft-17 Section 10.2.1.1 lists the codes an object may carry and says any
48/// other value SHOULD be treated as a protocol error and the session closed
49/// with a PROTOCOL_VIOLATION. Every place this module reads a status converts
50/// it here, so a decoded [`SubgroupObject::object_status`] or
51/// [`DatagramHeader::object_status`] is always a status the draft assigns, and
52/// [`SubgroupObjectMeta::status`] — which stays a raw code because a relay may
53/// carry it to a draft that numbers the set differently — holds one because it
54/// comes from the same conversion.
55fn decoded_status(code: u64) -> Result<ObjectStatus, CodecError> {
56    ObjectStatus::from_u64(code).ok_or(CodecError::InvalidField)
57}
58
59/// Whether an object carrying a given status is allowed a non-empty payload.
60///
61/// Draft-17 Section 10.2.1.1 states the rule arithmetically rather than as a
62/// table: "Any object with a status code other than zero MUST have an empty
63/// payload." So the answer is a property of the status code, and every code but
64/// Normal forbids a payload.
65///
66/// Forbidding is the strict half; permitting is not requiring. A Normal object
67/// with no payload is well formed, and this draft's encodings have a way to
68/// spell it — a zero Object Payload Length followed by the status code 0x0.
69#[derive(Debug, Clone, Copy, PartialEq, Eq)]
70pub enum PayloadPermission {
71    /// The status permits a payload but does not require one.
72    Permitted,
73    /// An object with this status has an empty payload, and one carrying bytes
74    /// is malformed.
75    Forbidden,
76}
77
78impl PayloadPermission {
79    /// `true` for [`PayloadPermission::Permitted`].
80    ///
81    /// The permission answers on its own, without a payload length in hand,
82    /// which is the point of reading it off the status.
83    pub fn permits(self) -> bool {
84        matches!(self, PayloadPermission::Permitted)
85    }
86}
87
88// ── Subgroup ──────────────────────────────────────────────────
89
90const SUBGROUP_PROPERTIES_BIT: u8 = 0x01;
91const SUBGROUP_ID_MODE_MASK: u8 = 0x06;
92const SUBGROUP_END_OF_GROUP_BIT: u8 = 0x08;
93const SUBGROUP_BASE_BIT: u8 = 0x10;
94const SUBGROUP_DEFAULT_PRIORITY_BIT: u8 = 0x20;
95/// The bits a subgroup header type must fix: 7 and 6 clear, 4 set. That is the
96/// form `0b00X1XXXX` written as a mask, leaving bit 5 and the low nibble free.
97const SUBGROUP_FORM_MASK: u8 = 0xD0;
98/// SUBGROUP_ID_MODE `0b11`, the value draft-17 reserves.
99const SUBGROUP_ID_MODE_RESERVED: u8 = 0x06;
100
101/// Whether `header_type` is one of the subgroup header types draft-17 defines.
102///
103/// Section 10.4.2 gives the field as
104/// `Type (i) = 0x10..0x15 / 0x18..0x1D / 0x30..0x35 / 0x38..0x3D` and then
105/// names the two ways a byte falls outside it, each of which "MUST close the
106/// session with a PROTOCOL_VIOLATION":
107///
108/// - "Type values with SUBGROUP_ID_MODE set to 0b11: 0x16, 0x17, 0x1E, 0x1F,
109///   0x36, 0x37, 0x3E, 0x3F. This mode is reserved for future use."
110/// - "Type values that do not match the form 0b00X1XXXX (i.e., Type values
111///   outside the ranges 0x10..0x1F and 0x30..0x3F, or values where bit 4 is not
112///   set)."
113///
114/// The two conditions are checked here rather than the eight-value list, and
115/// they enumerate exactly the same bytes: the form fixes bits 7, 6 and 4, and
116/// excluding the reserved mode removes eight of the remaining thirty-two.
117///
118/// The reserved mode is the one worth naming. Its Subgroup ID field is not on
119/// the wire and the draft does not say what the ID would be, so accepting it
120/// means answering with a value nothing in the header stands behind — a zero a
121/// consumer cannot tell from the zero mode `0b00` genuinely means.
122fn subgroup_type_is_valid(raw: u64) -> bool {
123    raw <= 0xFF && {
124        let t = raw as u8;
125        t & SUBGROUP_FORM_MASK == SUBGROUP_BASE_BIT
126            && t & SUBGROUP_ID_MODE_MASK != SUBGROUP_ID_MODE_RESERVED
127    }
128}
129
130/// Whether `raw` sits inside the subgroup form but names the reserved
131/// SUBGROUP_ID_MODE — the first of the two lists quoted above.
132fn subgroup_type_is_reserved_mode(raw: u64) -> bool {
133    raw <= 0xFF && {
134        let t = raw as u8;
135        t & SUBGROUP_FORM_MASK == SUBGROUP_BASE_BIT
136            && t & SUBGROUP_ID_MODE_MASK == SUBGROUP_ID_MODE_RESERVED
137    }
138}
139
140/// The unidirectional stream Type draft-17 Section 9.4 gives the control
141/// stream.
142///
143/// Draft-17 is where the control stream became a pair of unidirectional streams
144/// with a type of their own, which is why Table 3 has an entry a data reader can
145/// be handed and drafts 16 and below do not.
146const SETUP_STREAM_TYPE: u64 = 0x2F00;
147
148/// Refuse a Type field spelled in more than one byte, before anything narrows
149/// it to a byte.
150///
151/// Returns `Ok(None)` when the next Type is a single byte and the caller should
152/// read it itself, `Ok(Some(err))` when it is wider and `refusal` has named the
153/// failure, and `Err` only when the buffer does not hold the whole field yet.
154///
155/// Every Type the subgroup and datagram forms admit is below 0x80 and so
156/// occupies one byte under the MoQT variable-length integer encoding. A wider
157/// spelling is one of three things, and none of them may be read as a header:
158/// an assigned Type that is not a data stream — SETUP, a Type no table
159/// assigns, or a non-minimal spelling of a Type that is valid. The last is the
160/// dangerous one — narrowing a two-byte 0x8001 to its low octet turns it into
161/// an assigned Type, so a peer could name any Type it liked and have it parsed
162/// as another.
163///
164/// The full varint is decoded before `refusal` sees it, which is what lets the
165/// first case be told from the second. Only the second ends the session.
166fn wide_type_refusal(
167    buf: &mut impl Buf,
168    refusal: fn(u64) -> CodecError,
169) -> Result<Option<CodecError>, CodecError> {
170    if !buf.has_remaining() {
171        return Err(CodecError::UnexpectedEnd);
172    }
173    // Under the MoQT encoding the field's length is the number of leading 1
174    // bits in its first byte plus one, so a first byte below 0x80 is the whole
175    // of it.
176    if buf.chunk()[0] < 0x80 {
177        return Ok(None);
178    }
179    let raw = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
180    Ok(Some(refusal(raw)))
181}
182
183/// Which failure a leading unidirectional stream Type that is not the one a
184/// reader wants is.
185///
186/// Draft-17 states two rules about such a Type and answers both with a close,
187/// and telling them apart is the whole job of this function.
188///
189/// Section 3.4 is about the table: "An endpoint that receives an unknown stream
190/// type MUST close the session." A Type Table 3 does not assign is
191/// [`CodecError::UnknownStreamType`].
192///
193/// Section 10.4.2 is about the subgroup form specifically, and the eight Types
194/// inside it that name the reserved SUBGROUP_ID_MODE. Those are not unknown —
195/// the form is assigned and the draft lists the values outright — but they are
196/// unreadable, and they are [`CodecError::InvalidTypeValue`].
197///
198/// Table 3 assigns three things, and two of them are not data streams at all:
199/// FETCH_HEADER, the subgroup form, and SETUP. A subgroup reader handed any of
200/// them refuses it as [`CodecError::InvalidField`] — the value is one this
201/// draft defines, the disagreement is with the reader that was called, and the
202/// session survives it. Reporting SETUP as an unknown stream type would end a
203/// session over the peer's control stream.
204fn stream_type_error(raw: u64) -> CodecError {
205    if raw == FETCH_STREAM_TYPE || raw == SETUP_STREAM_TYPE || subgroup_type_is_valid(raw) {
206        CodecError::InvalidField
207    } else if subgroup_type_is_reserved_mode(raw) {
208        CodecError::InvalidTypeValue {
209            raw,
210            detail: "its SUBGROUP_ID_MODE is 0b11, which this draft reserves",
211        }
212    } else {
213        CodecError::UnknownStreamType(raw)
214    }
215}
216
217#[derive(Debug, Clone)]
218pub struct SubgroupHeader {
219    pub header_type: u8,
220    pub track_alias: VarInt,
221    pub group_id: VarInt,
222    pub subgroup_id: VarInt,
223    pub publisher_priority: Option<u8>,
224}
225
226impl SubgroupHeader {
227    /// Decode a subgroup header, Type field included.
228    ///
229    /// A Type spelled in more than one byte is refused before it is narrowed,
230    /// by `wide_type_refusal`: every Type the subgroup form admits is a
231    /// single byte, and the wider Types Table 3 assigns are not subgroup
232    /// headers.
233    pub fn decode(buf: &mut impl Buf) -> Result<Self, CodecError> {
234        if let Some(err) = wide_type_refusal(buf, stream_type_error)? {
235            return Err(err);
236        }
237        let raw = buf.get_u8() as u64;
238        if !subgroup_type_is_valid(raw) {
239            return Err(stream_type_error(raw));
240        }
241        let header_type = raw as u8;
242
243        let track_alias = VarInt::decode_moqt::<Wire>(buf)?;
244        let group_id = VarInt::decode_moqt::<Wire>(buf)?;
245
246        let subgroup_id_mode = (header_type & SUBGROUP_ID_MODE_MASK) >> 1;
247        let subgroup_id = match subgroup_id_mode {
248            0 => VarInt::from_u64_moqt(0),
249            2 => VarInt::decode_moqt::<Wire>(buf)?,
250            // Mode 1: the Subgroup ID is the first object's Object ID, which is
251            // not in the header. Stored as 0 and resolved by whoever reads the
252            // first object; [`Self::subgroup_id_mode`] is what tells a caller
253            // the stored value is a placeholder. Mode 3 cannot arrive here —
254            // `subgroup_type_is_valid` refused it above.
255            _ => VarInt::from_u64_moqt(0),
256        };
257
258        let publisher_priority = if header_type & SUBGROUP_DEFAULT_PRIORITY_BIT == 0 {
259            if buf.remaining() < 1 {
260                return Err(CodecError::UnexpectedEnd);
261            }
262            Some(buf.get_u8())
263        } else {
264            None
265        };
266
267        Ok(SubgroupHeader { header_type, track_alias, group_id, subgroup_id, publisher_priority })
268    }
269
270    /// Serialize the header exactly as its type byte describes it.
271    ///
272    /// The type byte is taken as the authority on framing and is written
273    /// through unexamined, which is what makes this infallible. A value built
274    /// by hand can therefore name a type draft-17 forbids — the reserved
275    /// SUBGROUP_ID_MODE `0b11` above all — and produce a stream the receiver
276    /// must answer with a PROTOCOL_VIOLATION. Prefer [`Self::encode_checked`],
277    /// which refuses such a header instead of emitting it.
278    pub fn encode(&self, buf: &mut impl BufMut) {
279        buf.put_u8(self.header_type);
280        self.track_alias.encode_moqt::<Wire>(buf);
281        self.group_id.encode_moqt::<Wire>(buf);
282
283        let subgroup_id_mode = (self.header_type & SUBGROUP_ID_MODE_MASK) >> 1;
284        if subgroup_id_mode == 2 {
285            self.subgroup_id.encode_moqt::<Wire>(buf);
286        }
287
288        if self.header_type & SUBGROUP_DEFAULT_PRIORITY_BIT == 0 {
289            buf.put_u8(self.publisher_priority.unwrap_or(128));
290        }
291    }
292
293    /// Serialize the header, refusing a type value draft-17 does not define.
294    ///
295    /// The accepted set is the one [`Self::decode`] accepts, so bytes this
296    /// writes always parse back through this module rather than being refused
297    /// by the peer. Section 10.4.2 lists the excluded values under "The
298    /// following Type values are invalid", and a receiver that follows it
299    /// closes the session rather than reading the stream, so writing one loses
300    /// the whole session and not merely the stream.
301    ///
302    /// Errors with [`CodecError::InvalidField`] before any byte is written, so
303    /// a refused header leaves `buf` untouched rather than half a header the
304    /// next write would run into.
305    pub fn encode_checked(&self, buf: &mut impl BufMut) -> Result<(), CodecError> {
306        if !subgroup_type_is_valid(self.header_type as u64) {
307            return Err(stream_type_error(self.header_type as u64));
308        }
309        self.encode(buf);
310        Ok(())
311    }
312
313    pub fn has_properties(&self) -> bool {
314        self.header_type & SUBGROUP_PROPERTIES_BIT != 0
315    }
316
317    /// The subgroup-ID mode: `(header_type & 0x06) >> 1`.
318    ///
319    /// `0` = no subgroup ID on the wire and it is zero; `1` = the subgroup ID
320    /// is the first object's ID; `2` = an explicit ID follows the Group ID;
321    /// `3` = reserved. Exposed because the mask is module-private and
322    /// `dispatch::AnySubgroupHeader::subgroup_id_mode` cannot read it.
323    ///
324    /// A decoded header never reports `3`: draft-17 Section 10.4.2 lists every
325    /// type value carrying that mode as invalid and [`Self::decode`] refuses
326    /// them. It remains reachable on a header built by hand, which is what
327    /// [`Self::encode_checked`] exists to catch.
328    pub fn subgroup_id_mode(&self) -> u8 {
329        (self.header_type & SUBGROUP_ID_MODE_MASK) >> 1
330    }
331
332    pub fn is_end_of_group(&self) -> bool {
333        self.header_type & SUBGROUP_END_OF_GROUP_BIT != 0
334    }
335}
336
337// ── Subgroup objects (stateful) ───────────────────────────────
338
339/// One object within a draft-17 subgroup stream. Object IDs are
340/// delta-encoded and the presence of a "properties" block (the
341/// draft-17 equivalent of extension headers) is determined by the
342/// PROPERTIES bit on the enclosing [`SubgroupHeader`]. Use
343/// [`SubgroupObjectReader`] to encode/decode.
344#[derive(Debug, Clone)]
345pub struct SubgroupObject {
346    pub object_id: VarInt,
347    /// Raw properties bytes, excluding the byte-length prefix that precedes
348    /// them on the wire. Empty unless the subgroup header sets the
349    /// PROPERTIES bit, or when the block is present but zero-length.
350    /// Opaque: [`SubgroupObjectReader::write_object`] re-emits the prefix
351    /// and these bytes verbatim.
352    pub extension_headers: Vec<u8>,
353    pub payload_length: VarInt,
354    /// The object's status, carried on the wire only when `payload_length` is
355    /// zero: a zero-length object encodes a status code in place of its
356    /// payload. `None` with a zero `payload_length` is written as
357    /// [`ObjectStatus::Normal`], the status draft-17 Section 10.2.1.1 gives an
358    /// empty object.
359    ///
360    /// Typed rather than a raw code. The wire field is a varint with room for
361    /// any value, and draft-17 assigns three of them; the decoder refuses the
362    /// rest, and this type is that same refusal on the encode side — 0x1 and
363    /// 0x2 cannot be named here, so [`SubgroupObjectReader::write_object`]
364    /// cannot emit a status this module's own decoder would reject.
365    pub object_status: Option<ObjectStatus>,
366    pub payload: Vec<u8>,
367}
368
369impl SubgroupObject {
370    /// The object's status, with the one draft-17's encoding elides filled in.
371    ///
372    /// A subgroup object states its status only when its Object Payload Length
373    /// is zero. An object that carries bytes therefore has no status field, and
374    /// its status is [`ObjectStatus::Normal`] — the only status draft-17
375    /// Section 10.2.1.1 permits a payload, so the only one such an object could
376    /// have had.
377    pub fn status(&self) -> ObjectStatus {
378        self.object_status.unwrap_or(ObjectStatus::Normal)
379    }
380
381    /// Whether this object's status is allowed to carry the properties it has.
382    ///
383    /// Draft-17 Section 10.2.1.2: "Any Object with status Normal can have
384    /// properties (Section 2.5). If an endpoint receives properties on an Object with status
385    /// that is not Normal, it MUST close the session with a
386    /// PROTOCOL_VIOLATION."
387    ///
388    /// So this is `false` for exactly one shape: a non-empty properties block
389    /// on an object whose status is not [`ObjectStatus::Normal`]. An object
390    /// with no properties is fine at any status, and an object at Normal may
391    /// carry any properties. A zero-length block is "no properties" here and
392    /// not a violation — Section 10.4.2 requires it of an object on a
393    /// PROPERTIES subgroup stream that has none: "Objects with no properties
394    /// set Properties Length to 0."
395    ///
396    /// Neither [`SubgroupObjectReader::read_object`] nor
397    /// [`SubgroupObjectReader::write_object`] applies this itself, which is a
398    /// deliberate contrast with the payload rule beside it. A status next to a
399    /// payload has no encoding — the two share a position on the wire — so the
400    /// writer refuses it as unrepresentable. Properties next to a status encode
401    /// fine; the frame is well formed and merely non-conforming, and a codec
402    /// that could not read or write it could not reproduce a capture containing
403    /// one. The rule addresses an endpoint receiving such an Object, so the
404    /// endpoint is where it is enforced, and this is what it asks.
405    ///
406    /// The datagram carrier is the exception, and the draft is what makes it
407    /// one: Section 10.3.1 states the same rule again as a per-datagram
408    /// framing rule, so [`DatagramHeader::decode`] refuses it outright.
409    pub fn properties_permitted(&self) -> bool {
410        self.extension_headers.is_empty() || self.status() == ObjectStatus::Normal
411    }
412}
413
414/// The framing of one draft-17 subgroup object, without its payload.
415///
416/// Produced by [`SubgroupObjectReader::read_object_meta`] for callers that
417/// forward an object's bytes verbatim and never inspect the payload.
418#[derive(Debug, Clone, Copy, PartialEq, Eq)]
419pub struct SubgroupObjectMeta {
420    /// Resolved absolute Object ID.
421    pub object_id: u64,
422    /// Byte length of the properties block's contents, excluding its length
423    /// prefix.
424    pub extension_headers_len: u64,
425    /// Declared payload length. Zero when `status` is `Some`.
426    pub payload_length: u64,
427    /// Object status wire code, present only when the payload is empty.
428    pub status: Option<u64>,
429    /// Total bytes this object occupies on the wire, prefix fields included.
430    pub wire_len: u64,
431}
432
433impl SubgroupObjectMeta {
434    /// Whether this object's stated status allows it a non-empty payload.
435    ///
436    /// `None` when the object states no status at all. On a subgroup stream
437    /// that is every object that carries bytes: draft-17 Section 10.4.2 puts
438    /// the status field on the wire only when the Object Payload Length is
439    /// zero, and Section 10.2.1.1 says Normal "is implicit for any non-zero
440    /// length object". An absent status is therefore not an unknown one — it is
441    /// Normal, spelled by the payload's own presence — but it is not a *stated*
442    /// permission, and this method reports only what the object states.
443    ///
444    /// `Some` otherwise, reading draft-17 Section 10.2.1.1's rule off the code:
445    /// "Any object with a status code other than zero MUST have an empty
446    /// payload." Zero permits, everything else forbids, which holds for codes
447    /// beyond the three the draft assigns as well — the rule is arithmetic, not
448    /// a lookup, so it does not go stale if a later draft assigns more.
449    ///
450    /// Worth having even though a stated status here always sits beside a zero
451    /// payload length, because the framing is not the destination. A caller
452    /// forwarding this object onto a datagram, where the payload is whatever
453    /// follows the header rather than a counted field, needs to know the object
454    /// may not be given bytes there either; the length it read on this stream
455    /// says nothing about that.
456    pub fn payload_permission(&self) -> Option<PayloadPermission> {
457        self.status.map(|code| {
458            if code == ObjectStatus::Normal.as_u64() {
459                PayloadPermission::Permitted
460            } else {
461                PayloadPermission::Forbidden
462            }
463        })
464    }
465}
466
467#[derive(Debug, Clone)]
468pub struct SubgroupObjectReader {
469    extensions_present: bool,
470    prev_object_id: Option<u64>,
471}
472
473impl SubgroupObjectReader {
474    pub fn new(header: &SubgroupHeader) -> Self {
475        Self { extensions_present: header.has_properties(), prev_object_id: None }
476    }
477
478    pub fn read_object(&mut self, buf: &mut impl Buf) -> Result<SubgroupObject, CodecError> {
479        let delta = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
480        let object_id_val = match self.prev_object_id {
481            None => delta,
482            Some(prev) => prev
483                .checked_add(1)
484                .and_then(|v| v.checked_add(delta))
485                .ok_or(CodecError::ObjectIdOverflow(prev, delta))?,
486        };
487        self.prev_object_id = Some(object_id_val);
488        let object_id = VarInt::from_u64(object_id_val).map_err(|_| CodecError::InvalidField)?;
489
490        // The properties block is a byte-length-prefixed opaque blob. We
491        // copy the blob verbatim; callers that want structured properties
492        // can parse the returned bytes.
493        let extension_headers = if self.extensions_present {
494            let ext_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
495            crate::types::read_bytes(buf, ext_len)?
496        } else {
497            Vec::new()
498        };
499
500        let payload_length_vi = VarInt::decode_moqt::<Wire>(buf)?;
501        let payload_length_val = payload_length_vi.into_inner() as usize;
502        let (object_status, payload) = if payload_length_val == 0 {
503            let status = VarInt::decode_moqt::<Wire>(buf)?;
504            (Some(decoded_status(status.into_inner())?), Vec::new())
505        } else {
506            let payload = crate::types::read_bytes(buf, payload_length_val)?;
507            (None, payload)
508        };
509
510        Ok(SubgroupObject {
511            object_id,
512            extension_headers,
513            payload_length: payload_length_vi,
514            object_status,
515            payload,
516        })
517    }
518
519    /// Decode the next object's framing without copying its payload.
520    ///
521    /// Consumes exactly the bytes [`Self::read_object`] consumes and leaves
522    /// the same delta state behind, so the two are interchangeable on a
523    /// given stream.
524    pub fn read_object_meta(
525        &mut self,
526        buf: &mut impl Buf,
527    ) -> Result<SubgroupObjectMeta, CodecError> {
528        let start = buf.remaining();
529        let delta = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
530        let object_id_val = match self.prev_object_id {
531            None => delta,
532            Some(prev) => prev
533                .checked_add(1)
534                .and_then(|v| v.checked_add(delta))
535                .ok_or(CodecError::ObjectIdOverflow(prev, delta))?,
536        };
537        self.prev_object_id = Some(object_id_val);
538        let object_id =
539            VarInt::from_u64(object_id_val).map_err(|_| CodecError::InvalidField)?.into_inner();
540
541        let extension_headers_len = if self.extensions_present {
542            let ext_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
543            skip(buf, ext_len)?;
544            ext_len
545        } else {
546            0
547        };
548
549        let payload_length = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
550        let status = if payload_length == 0 {
551            let code = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
552            Some(decoded_status(code)?.as_u64())
553        } else {
554            skip(buf, payload_length)?;
555            None
556        };
557
558        Ok(SubgroupObjectMeta {
559            object_id,
560            extension_headers_len,
561            payload_length,
562            status,
563            wire_len: (start - buf.remaining()) as u64,
564        })
565    }
566
567    /// Serialize an object, producing the correct delta encoding.
568    ///
569    /// A zero `payload_length` writes the object's status, defaulting to
570    /// [`ObjectStatus::Normal`] when it is `None`. The status is typed, so
571    /// every value that can reach this method is one draft-17 assigns and one
572    /// [`Self::read_object`] accepts; there is no status-related error to
573    /// return.
574    ///
575    /// Errors with [`CodecError::InvalidField`] when `object.object_id` is
576    /// not strictly greater than the previously written object's ID, since
577    /// no valid delta exists for that case.
578    ///
579    /// Errors with [`CodecError::InvalidField`] when `payload_length` is not
580    /// exactly `payload.len()`. The declared length is written ahead of the
581    /// payload, so a mismatch is a frame [`Self::read_object`] cannot parse
582    /// and one no caller could fix by appending bytes.
583    pub fn write_object(
584        &mut self,
585        object: &SubgroupObject,
586        buf: &mut impl BufMut,
587    ) -> Result<(), CodecError> {
588        // A declared length that disagrees with the payload framed under it
589        // produces bytes no reader can parse and no caller can repair: the
590        // length is already on the wire ahead of the payload. Checked before
591        // anything is written, so a refused object leaves `buf` untouched
592        // rather than half an object the next read would run into.
593        //
594        // Zero is not "an empty payload" here; it is the marker that puts a
595        // status code where the payload would go, so an object carrying bytes
596        // under it is asking for two framings at once.
597        let declared = object.payload_length.into_inner();
598        if declared != object.payload.len() as u64 {
599            return Err(CodecError::InvalidField);
600        }
601
602        let oid = object.object_id.into_inner();
603        let delta = match self.prev_object_id {
604            None => oid,
605            Some(prev) => oid
606                .checked_sub(prev)
607                .and_then(|v| v.checked_sub(1))
608                .ok_or(CodecError::InvalidField)?,
609        };
610        VarInt::from_u64(delta).map_err(|_| CodecError::InvalidField)?.encode_moqt::<Wire>(buf);
611        if self.extensions_present {
612            VarInt::from_u64(object.extension_headers.len() as u64)
613                .map_err(|_| CodecError::InvalidField)?
614                .encode_moqt::<Wire>(buf);
615            buf.put_slice(&object.extension_headers);
616        }
617        object.payload_length.encode_moqt::<Wire>(buf);
618        if object.payload_length.into_inner() == 0 {
619            let status = object.object_status.unwrap_or(ObjectStatus::Normal);
620            VarInt::from_u64_moqt(status.as_u64()).encode_moqt::<Wire>(buf);
621        } else {
622            buf.put_slice(&object.payload);
623        }
624        self.prev_object_id = Some(oid);
625        Ok(())
626    }
627}
628
629// ── Datagram ──────────────────────────────────────────────────
630
631const DATAGRAM_PROPERTIES_BIT: u8 = 0x01;
632const DATAGRAM_END_OF_GROUP_BIT: u8 = 0x02;
633const DATAGRAM_ZERO_OBJECT_ID_BIT: u8 = 0x04;
634const DATAGRAM_DEFAULT_PRIORITY_BIT: u8 = 0x08;
635const DATAGRAM_STATUS_BIT: u8 = 0x20;
636/// The bits a datagram type must fix: 7, 6 and 4 all clear. That is the form
637/// `0b00X0XXXX` written as a mask, leaving bit 5 and the low nibble free.
638const DATAGRAM_FORM_MASK: u8 = 0xD0;
639
640/// Whether `datagram_type` is one of the datagram types draft-17 defines.
641///
642/// Section 10.3.1 gives the field as
643/// `Type (i) = 0x00..0x0F / 0x20..0x21 / 0x24..0x25 / 0x28..0x29 / 0x2C..0x2D`
644/// and then names the two ways a byte falls outside it, each of which "MUST
645/// close the session with a PROTOCOL_VIOLATION":
646///
647/// - "Type values with both the STATUS bit (0x20) and END_OF_GROUP bit (0x02)
648///   set: 0x22, 0x23, 0x26, 0x27, 0x2A, 0x2B, 0x2E, 0x2F. An object status
649///   message cannot signal end of group."
650/// - "Type values that do not match the form 0b00X0XXXX (i.e., Type values
651///   outside the ranges 0x00..0x0F and 0x20..0x2F)."
652///
653/// The two conditions are checked here rather than the eight-value list, and
654/// they enumerate exactly the same bytes.
655///
656/// Bit 4 is what separates a datagram from a subgroup header: the subgroup form
657/// requires it set and this one requires it clear, so the same octet can never
658/// be read as both.
659fn datagram_type_is_valid(raw: u64) -> bool {
660    raw <= 0xFF && {
661        let t = raw as u8;
662        t & DATAGRAM_FORM_MASK == 0
663            && t & (DATAGRAM_STATUS_BIT | DATAGRAM_END_OF_GROUP_BIT)
664                != (DATAGRAM_STATUS_BIT | DATAGRAM_END_OF_GROUP_BIT)
665    }
666}
667
668/// Which failure a leading datagram Type that is not one a reader wants is.
669///
670/// The same two-rule split as `stream_type_error`, read against the datagram
671/// table. A Type outside the datagram form is one no table assigns, so it is
672/// [`CodecError::UnknownDatagramType`]. A Type inside the form that sets both
673/// STATUS and END_OF_GROUP is named by Section 10.3.1 and forbidden there — an
674/// object status message cannot also mark the end of a group — so it is
675/// [`CodecError::InvalidTypeValue`].
676///
677/// Nothing reaches the [`CodecError::InvalidField`] arm from a decoder: the
678/// stream Types all set bit 4 or exceed a byte, so they fail the form rather
679/// than passing it, and draft-17 defines no padding datagram for the datagram
680/// table to share.
681fn datagram_type_error(raw: u64) -> CodecError {
682    if datagram_type_is_valid(raw) {
683        CodecError::InvalidField
684    } else if raw <= 0xFF
685        && raw as u8 & DATAGRAM_FORM_MASK == 0
686        && raw as u8 & (DATAGRAM_STATUS_BIT | DATAGRAM_END_OF_GROUP_BIT)
687            == (DATAGRAM_STATUS_BIT | DATAGRAM_END_OF_GROUP_BIT)
688    {
689        CodecError::InvalidTypeValue {
690            raw,
691            detail: "it sets both the STATUS bit and the END_OF_GROUP bit",
692        }
693    } else {
694        CodecError::UnknownDatagramType(raw)
695    }
696}
697
698#[derive(Debug, Clone)]
699pub struct DatagramHeader {
700    pub datagram_type: u8,
701    pub track_alias: VarInt,
702    pub group_id: VarInt,
703    pub object_id: VarInt,
704    pub publisher_priority: Option<u8>,
705    /// Raw properties bytes, excluding the byte-length prefix that precedes
706    /// them on the wire. Present only when `datagram_type` sets the PROPERTIES
707    /// bit (0x01), and empty otherwise — the bit is what puts the block on the
708    /// wire, so contents held here with the bit clear are not written.
709    ///
710    /// Opaque: [`Self::encode`] re-emits the prefix and these bytes verbatim,
711    /// and [`Self::decode`] copies them out the same way, so a datagram can be
712    /// decoded and re-encoded without understanding what its properties mean.
713    /// The block sits between the publisher priority and the status field, so
714    /// leaving it out of the struct would put the status where the decoder
715    /// looks for the properties length.
716    pub properties: Vec<u8>,
717    /// The object's status, carried on the wire only when `datagram_type` sets
718    /// the STATUS bit (0x20): such a datagram holds a one-byte status code in
719    /// place of a payload. `None` with the bit set is written as
720    /// [`ObjectStatus::Normal`]; a status with the bit clear is not written at
721    /// all, because the bit is what puts the field on the wire.
722    ///
723    /// Typed rather than a bare byte. The wire field is one octet with 256
724    /// values, and draft-17 Section 10.2.1.1 assigns three of them; the
725    /// decoder refuses the other 253, and this type is that same refusal on
726    /// the encode side — [`Self::encode`] is infallible precisely because a
727    /// status it could not legally write cannot be built.
728    pub object_status: Option<ObjectStatus>,
729}
730
731impl DatagramHeader {
732    /// Decode the header and stop, leaving whatever follows it in `buf`.
733    ///
734    /// A datagram's payload has no length field — draft-17 Section 10.3.1:
735    /// "There is no explicit length field for the Object Payload; the entirety
736    /// of the transport datagram following the Object header contains the
737    /// payload." So the header alone cannot say how many bytes belong to the
738    /// object, and this method deliberately does not try: the caller holds the
739    /// transport datagram and the tail is theirs.
740    ///
741    /// That makes it the wrong entry point for validating the object as a
742    /// whole. Use [`Self::decode_object`] when `buf` holds exactly one
743    /// datagram; it consumes the tail and can therefore refuse a payload the
744    /// framing forbids.
745    pub fn decode(buf: &mut impl Buf) -> Result<Self, CodecError> {
746        if let Some(err) = wide_type_refusal(buf, datagram_type_error)? {
747            return Err(err);
748        }
749        let raw = buf.get_u8() as u64;
750        if !datagram_type_is_valid(raw) {
751            return Err(datagram_type_error(raw));
752        }
753        let datagram_type = raw as u8;
754
755        let track_alias = VarInt::decode_moqt::<Wire>(buf)?;
756        let group_id = VarInt::decode_moqt::<Wire>(buf)?;
757
758        let object_id = if datagram_type & DATAGRAM_ZERO_OBJECT_ID_BIT != 0 {
759            VarInt::from_usize(0)
760        } else {
761            VarInt::decode_moqt::<Wire>(buf)?
762        };
763
764        let publisher_priority = if datagram_type & DATAGRAM_DEFAULT_PRIORITY_BIT == 0 {
765            if buf.remaining() < 1 {
766                return Err(CodecError::UnexpectedEnd);
767            }
768            Some(buf.get_u8())
769        } else {
770            None
771        };
772
773        let properties = if datagram_type & DATAGRAM_PROPERTIES_BIT != 0 {
774            let props_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
775            crate::types::read_bytes(buf, props_len)?
776        } else {
777            Vec::new()
778        };
779
780        let object_status = if datagram_type & DATAGRAM_STATUS_BIT != 0 {
781            if buf.remaining() < 1 {
782                return Err(CodecError::UnexpectedEnd);
783            }
784            let status = buf.get_u8();
785            Some(decoded_status(status as u64)?)
786        } else {
787            None
788        };
789
790        // Two rules of draft-17 Section 10.3.1 reach the properties block just
791        // read, and neither is applied here — [`Self::properties_permitted`]
792        // and [`Self::properties_block_well_formed`] report them instead, and
793        // [`Self::encode_checked`] refuses to write either shape:
794        //
795        //   - "If an endpoint receives a datagram with the PROPERTIES bit set
796        //     and an Properties Length of 0, it MUST close the session with a
797        //     PROTOCOL_VIOLATION."
798        //   - "If an Object Datagram includes both the STATUS bit and
799        //     PROPERTIES bit, and the Object Status is not Normal (0x0), the
800        //     endpoint MUST close the session with a PROTOCOL_VIOLATION,
801        //     because only Normal Objects can have Properties."
802        //
803        // Both describe a datagram that is well framed and non-conforming: the
804        // fields are all where the layout puts them and every one of them
805        // parses, so a decoder can read the datagram back exactly as it
806        // arrived. Refusing here would leave this module unable to reproduce a
807        // capture containing one, and both rules address an endpoint receiving
808        // such a datagram, so the endpoint is where they are enforced.
809        //
810        // The Type rules above are the contrast, and the contrast is what
811        // decides it: an invalid Type names no layout at all, so reading on
812        // invents the fields behind it rather than reporting them.
813
814        Ok(DatagramHeader {
815            datagram_type,
816            track_alias,
817            group_id,
818            object_id,
819            publisher_priority,
820            properties,
821            object_status,
822        })
823    }
824
825    /// Decode one whole datagram: the header, then the payload that runs to the
826    /// end of `buf`.
827    ///
828    /// `buf` must hold exactly one transport datagram and nothing else, since
829    /// that boundary is the only thing that delimits the payload — draft-17
830    /// Section 10.3.1: "There is no explicit length field for the Object
831    /// Payload; the entirety of the transport datagram following the Object
832    /// header contains the payload."
833    ///
834    /// Which is why the refusal lives here and not in [`Self::decode`]. A
835    /// datagram whose type sets the STATUS bit has no payload at all — the same
836    /// section: "When set to 1, the Object Status field is present and there is
837    /// no Object Payload" — so trailing bytes after its status are not a short
838    /// payload or an odd one, they are bytes the frame does not define. A
839    /// decoder that stops at the header cannot see them, and a caller that
840    /// treats whatever is left as the payload hands the application content the
841    /// publisher never framed as content. That is the case this refuses.
842    ///
843    /// The same refusal covers a status the draft forbids a payload to: an
844    /// object marked End of Group or End of Track may not carry one, per
845    /// Section 10.2.1.1's "Any object with a status code other than zero MUST
846    /// have an empty payload".
847    ///
848    /// Errors with [`CodecError::PayloadNotPermitted`] when bytes remain and
849    /// the header forbids them, naming which of the two rules refused them.
850    pub fn decode_object(buf: &mut impl Buf) -> Result<(Self, Vec<u8>), CodecError> {
851        let header = Self::decode(buf)?;
852        let payload = crate::types::read_bytes(buf, buf.remaining())?;
853        if !payload.is_empty() && !header.permits_payload() {
854            return Err(CodecError::PayloadNotPermitted {
855                status: header.status().as_u64(),
856                len: payload.len(),
857                detail: if header.has_status() {
858                    "its type states a status in place of a payload"
859                } else {
860                    "its status is registered as forbidding one"
861                },
862            });
863        }
864        Ok((header, payload))
865    }
866
867    /// Serialize the header, refusing a status the framing cannot carry.
868    ///
869    /// A datagram states a status only when its type byte sets the STATUS bit
870    /// (0x20). With the bit clear there is no status field on the wire, so an
871    /// `object_status` of anything but [`ObjectStatus::Normal`] has nowhere to
872    /// go: [`Self::encode`] drops it, and the datagram parses back as an
873    /// ordinary payload object. An End of Group marker written that way does
874    /// not arrive late or malformed — it does not arrive at all, and the
875    /// receiver sees a normal object in its place.
876    ///
877    /// Draft-17 Section 10.3.1 puts the framing side plainly — "The STATUS bit
878    /// (0x20) indicates whether the datagram contains an Object Status or
879    /// Object Payload" — and Section 10.2.1.1 the conformance side: "Any object
880    /// with a status code other than zero MUST have an empty payload." Between
881    /// them there is no datagram that carries a non-zero status and a payload,
882    /// so the pair being refused here is not one this encoder merely declines
883    /// to spell.
884    ///
885    /// [`ObjectStatus::Normal`] with the bit clear is not that case and is
886    /// accepted. It is the status the encoding elides for every datagram that
887    /// carries a payload, so stating it asks for exactly the bytes leaving it
888    /// out asks for, and nothing is lost.
889    ///
890    /// A type value Section 10.3.1 lists as invalid is refused here too, on the
891    /// same grounds: a receiver that follows the draft answers one with a
892    /// PROTOCOL_VIOLATION, so writing it costs the session and not merely the
893    /// datagram. The accepted set is the one [`Self::decode`] accepts.
894    ///
895    /// Errors with [`CodecError::InvalidField`] on either, before any byte is
896    /// written, so a refused header leaves `buf` untouched. The status half is
897    /// the datagram counterpart of the rule
898    /// [`SubgroupObjectReader::write_object`] applies on a subgroup stream,
899    /// where the status and the payload share a wire position.
900    pub fn encode_checked(&self, buf: &mut impl BufMut) -> Result<(), CodecError> {
901        if !datagram_type_is_valid(self.datagram_type as u64) {
902            return Err(datagram_type_error(self.datagram_type as u64));
903        }
904        if !self.has_status() && matches!(self.object_status, Some(s) if s != ObjectStatus::Normal)
905        {
906            return Err(CodecError::InvalidField);
907        }
908        // The two properties rules of Section 10.3.1. [`Self::decode`] reports
909        // both rather than refusing them, because the datagrams they describe
910        // are well framed and a codec that could not read one could not
911        // reproduce a capture containing it. Writing one is the other
912        // direction and has no such excuse: a conforming peer answers either
913        // with a PROTOCOL_VIOLATION, so emitting one costs the session and not
914        // merely the datagram.
915        if !self.properties_block_well_formed() || !self.properties_permitted() {
916            return Err(CodecError::InvalidField);
917        }
918        self.encode(buf);
919        Ok(())
920    }
921
922    /// Serialize the header exactly as its type byte describes it.
923    ///
924    /// Every field the type byte announces is written, in the order
925    /// [`Self::decode`] reads them, so the bytes this produces always parse
926    /// back. The properties block in particular has to be written here: it
927    /// sits ahead of the status field, and a datagram that skipped it would
928    /// offer the status byte where the decoder reads the block's length.
929    ///
930    /// The type byte is taken as the authority on framing, which is what makes
931    /// this infallible — and what makes it lossy when the struct disagrees with
932    /// itself. An `object_status` set while the type byte leaves the STATUS bit
933    /// clear is discarded here without a word. Prefer [`Self::encode_checked`],
934    /// which refuses that combination instead of resolving it.
935    pub fn encode(&self, buf: &mut impl BufMut) {
936        buf.put_u8(self.datagram_type);
937        self.track_alias.encode_moqt::<Wire>(buf);
938        self.group_id.encode_moqt::<Wire>(buf);
939
940        if self.datagram_type & DATAGRAM_ZERO_OBJECT_ID_BIT == 0 {
941            self.object_id.encode_moqt::<Wire>(buf);
942        }
943
944        if self.datagram_type & DATAGRAM_DEFAULT_PRIORITY_BIT == 0 {
945            buf.put_u8(self.publisher_priority.unwrap_or(128));
946        }
947
948        if self.datagram_type & DATAGRAM_PROPERTIES_BIT != 0 {
949            VarInt::from_usize(self.properties.len()).encode_moqt::<Wire>(buf);
950            buf.put_slice(&self.properties);
951        }
952
953        if self.datagram_type & DATAGRAM_STATUS_BIT != 0 {
954            buf.put_u8(self.object_status.unwrap_or(ObjectStatus::Normal).as_u8());
955        }
956    }
957
958    pub fn is_end_of_group(&self) -> bool {
959        self.datagram_type & DATAGRAM_END_OF_GROUP_BIT != 0
960    }
961
962    pub fn has_status(&self) -> bool {
963        self.datagram_type & DATAGRAM_STATUS_BIT != 0
964    }
965
966    /// `true` when the type byte sets the PROPERTIES bit (0x01), which is what
967    /// puts the properties block on the wire.
968    ///
969    /// Reports the framing, not the contents. A decoded datagram with this set
970    /// always has a non-empty [`Self::properties`], because
971    /// [`Self::decode`] refuses a zero-length block; a header built by hand can
972    /// hold the two apart, and [`Self::encode_checked`] is what refuses that.
973    pub fn has_properties(&self) -> bool {
974        self.datagram_type & DATAGRAM_PROPERTIES_BIT != 0
975    }
976
977    /// The object's status, with the one the encoding elides filled in.
978    ///
979    /// A datagram states a status only when its type sets the STATUS bit, and
980    /// such a datagram has no payload. One without the bit is all payload, and
981    /// the status of an object that carries a payload is
982    /// [`ObjectStatus::Normal`] — draft-17 Section 10.2.1.1: "Any object with a
983    /// status code other than zero MUST have an empty payload."
984    pub fn status(&self) -> ObjectStatus {
985        self.object_status.unwrap_or(ObjectStatus::Normal)
986    }
987
988    /// Whether this datagram's status is allowed to carry the properties it
989    /// has.
990    ///
991    /// The same rule the subgroup form obeys. Draft-17 Section 10.3.1 builds
992    /// the datagram's Properties field out of "the Object Properties structure
993    /// defined in Section 10.2.1.2", and that section is where the general rule
994    /// sits: "If an endpoint receives properties on an Object with status that
995    /// is not Normal, it MUST close the session with a PROTOCOL_VIOLATION."
996    /// Section 10.3.1 then states it again for this carrier in terms of the two
997    /// bits, which is why [`Self::decode`] refuses the shape rather than merely
998    /// reporting it — see [`SubgroupObject::properties_permitted`] for why the
999    /// subgroup carrier is the other way round.
1000    pub fn properties_permitted(&self) -> bool {
1001        self.properties.is_empty() || self.status() == ObjectStatus::Normal
1002    }
1003
1004    /// Whether the properties block is framed the way a datagram may frame it.
1005    ///
1006    /// Draft-17 Section 10.3.1: "If an endpoint receives a datagram with the
1007    /// PROPERTIES bit set and an Properties Length of 0, it MUST close the
1008    /// session with a PROTOCOL_VIOLATION."
1009    ///
1010    /// The bit and a zero length are two ways to spell "no properties", and on
1011    /// a datagram they are not interchangeable: a datagram with none has a type
1012    /// byte that says so, and the block costs bytes the type byte already
1013    /// saved. This rule is the datagram's alone. A subgroup stream says the
1014    /// opposite in Section 10.4.2 — "Objects with no properties set Properties
1015    /// Length to 0" — because there the PROPERTIES bit is fixed for the whole
1016    /// stream, so an object with no properties has nowhere else to say so and a
1017    /// zero-length block is the required spelling rather than a violation.
1018    ///
1019    /// The mirror case is not a wire state but is a state this struct can hold:
1020    /// properties with the bit clear. [`Self::encode`] drops them without a
1021    /// word, so this reports that too, and [`Self::encode_checked`] refuses
1022    /// both.
1023    pub fn properties_block_well_formed(&self) -> bool {
1024        self.has_properties() != self.properties.is_empty()
1025    }
1026
1027    /// Whether the bytes after this datagram's header are allowed to exist.
1028    ///
1029    /// Two independent rules forbid them, and this reports both:
1030    ///
1031    /// - The framing. Draft-17 Section 10.3.1: "The STATUS bit (0x20) indicates
1032    ///   whether the datagram contains an Object Status or Object Payload. When
1033    ///   set to 1, the Object Status field is present and there is no Object
1034    ///   Payload." A datagram that states a status has no payload field at all,
1035    ///   whichever status it states — so a STATUS datagram carrying the Normal
1036    ///   code 0x0 has no more room for bytes than one carrying End of Group.
1037    /// - The status. Section 10.2.1.1: "Any object with a status code other than
1038    ///   zero MUST have an empty payload." This one reaches a datagram whose
1039    ///   type byte leaves the STATUS bit clear while the value claims a
1040    ///   non-Normal status — a disagreement [`Self::encode_checked`] refuses to
1041    ///   write, and one a decoded header never shows.
1042    ///
1043    /// The first is the rule a decoded datagram can actually trip, and reading
1044    /// the status alone misses it: `Some(ObjectStatus::Normal)` under a type
1045    /// byte with the STATUS bit set is exactly the case where the payload the
1046    /// draft says does not exist would otherwise be handed to the application
1047    /// as the object's content.
1048    ///
1049    /// Distinct from [`Self::has_status`], which reports how the datagram is
1050    /// framed rather than whether a payload may follow. A caller holding the
1051    /// bytes after the header wants this one; [`Self::decode_object`] applies it
1052    /// for a caller who would rather the decode simply fail.
1053    pub fn permits_payload(&self) -> bool {
1054        if self.has_status() {
1055            return false;
1056        }
1057        match self.object_status {
1058            None => true,
1059            Some(status) => status == ObjectStatus::Normal,
1060        }
1061    }
1062}
1063
1064// ── Fetch Header ──────────────────────────────────────────────
1065
1066const FETCH_STREAM_TYPE: u64 = 0x05;
1067
1068#[derive(Debug, Clone)]
1069pub struct FetchHeader {
1070    pub request_id: VarInt,
1071}
1072
1073impl FetchHeader {
1074    pub fn decode(buf: &mut impl Buf) -> Result<Self, CodecError> {
1075        let stream_type = VarInt::decode_moqt::<Wire>(buf)?.into_inner();
1076        if stream_type != FETCH_STREAM_TYPE {
1077            return Err(stream_type_error(stream_type));
1078        }
1079        let request_id = VarInt::decode_moqt::<Wire>(buf)?;
1080        Ok(FetchHeader { request_id })
1081    }
1082
1083    pub fn encode(&self, buf: &mut impl BufMut) {
1084        VarInt::from_usize(FETCH_STREAM_TYPE as usize).encode_moqt::<Wire>(buf);
1085        self.request_id.encode_moqt::<Wire>(buf);
1086    }
1087}
1088
1089// ── Fetch objects ─────────────────────────────────────────────
1090
1091/// SUBGROUP mode, the two least significant Serialization Flags bits
1092/// (draft-17 Section 10.4.4.1, Table 7).
1093const FETCH_SUBGROUP_MODE_MASK: u64 = 0x03;
1094/// SUBGROUP mode `0x01`: the Subgroup ID is the prior object's. Mode `0x00`,
1095/// the remaining value, fixes the Subgroup ID at zero and needs no constant —
1096/// nothing tests for it.
1097const FETCH_SUBGROUP_MODE_PRIOR: u64 = 0x01;
1098/// SUBGROUP mode `0x02`: the Subgroup ID is the prior object's plus one.
1099const FETCH_SUBGROUP_MODE_PRIOR_PLUS_ONE: u64 = 0x02;
1100/// SUBGROUP mode `0x03`: an explicit Subgroup ID field is present.
1101const FETCH_SUBGROUP_MODE_EXPLICIT: u64 = 0x03;
1102/// Object ID field present; clear means the prior object's ID plus one.
1103const FETCH_OBJECT_ID_BIT: u64 = 0x04;
1104/// Group ID field present; clear means the prior object's Group ID.
1105const FETCH_GROUP_ID_BIT: u64 = 0x08;
1106/// Priority field present; clear means the prior object's priority.
1107const FETCH_PRIORITY_BIT: u64 = 0x10;
1108/// Properties field present.
1109const FETCH_PROPERTIES_BIT: u64 = 0x20;
1110/// The object was forwarded as a datagram and has no Subgroup ID; the two
1111/// least significant bits are to be ignored.
1112const FETCH_DATAGRAM_BIT: u64 = 0x40;
1113/// The largest Serialization Flags value read as a set of bits. Draft-17
1114/// Section 10.4.4: "When less than 128, the bits represent flags described
1115/// below."
1116const FETCH_FLAGS_BIT_FORM_MAX: u64 = 0x7f;
1117/// Serialization Flags `0x8C`, End of Non-Existent Range.
1118const FETCH_END_OF_NON_EXISTENT_RANGE: u64 = 0x8c;
1119/// Serialization Flags `0x10C`, End of Unknown Range.
1120const FETCH_END_OF_UNKNOWN_RANGE: u64 = 0x10c;
1121
1122/// The two Serialization Flags values that mark a range of Objects rather than
1123/// carrying one, from draft-17 Section 10.4.4 Table 6 and Section 10.4.4.2.
1124///
1125/// Both state a Group ID and an Object ID and nothing else, and both mean the
1126/// same thing about the span from the last serialized Object to that Location
1127/// inclusive: it will not be serialized. They differ only in what the publisher
1128/// claims to know about it.
1129#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1130pub enum EndOfRange {
1131    /// `0x8C`. The Objects in the span "do not exist".
1132    NonExistent,
1133    /// `0x10C`. The Objects in the span "are unknown".
1134    Unknown,
1135}
1136
1137/// One object on a draft-17 fetch stream, without its payload.
1138///
1139/// Draft-17 Section 10.4.4, Figure 27:
1140///
1141/// ```text
1142/// {
1143///   Serialization Flags (vi64),
1144///   [Group ID (vi64),]
1145///   [Subgroup ID (vi64),]
1146///   [Object ID (vi64),]
1147///   [Publisher Priority (8),]
1148///   [Properties (..),]
1149///   Object Payload Length (vi64),
1150///   [Object Payload (..),]
1151/// }
1152/// ```
1153///
1154/// # Why the fields are optional
1155///
1156/// Every bracketed field above is one the Serialization Flags may leave off the
1157/// wire, and leaving it off does not mean the object lacks it — Table 8 gives
1158/// each absent field a meaning drawn from the object before it on the stream
1159/// ("Object ID is the prior Object's ID plus one", "Group ID is the prior
1160/// Object's Group ID", "Priority is the prior Object's Priority"), and Table 7
1161/// does the same for the Subgroup ID. A single object's bytes therefore do not
1162/// determine its Location; only the run of objects before it does.
1163///
1164/// So this type reports presence rather than inventing a value: `None` means
1165/// *the wire did not say*, and resolving it is the job of a caller that has
1166/// been following the stream. [`Self::references_prior_object`] is how such a
1167/// caller learns whether resolution is even needed, and it is what makes the
1168/// draft's rule about the first object checkable: "If the first Object in the
1169/// FETCH response uses a flag that references fields in the prior Object, the
1170/// Subscriber MUST close the session with a PROTOCOL_VIOLATION."
1171///
1172/// # What draft-17 changed
1173///
1174/// Through draft-13 a fetch object spelled out Group ID, Subgroup ID, Object ID
1175/// and Publisher Priority on every object and carried an Object Status beside a
1176/// zero-length payload. Draft-17 has neither habit: the flags replace the four
1177/// unconditional fields, and there is no status field at all — Section 10.2.1.1
1178/// says the Object Status "is only present in objects that are delivered via a
1179/// SUBSCRIPTION, and is absent in Objects delivered via a FETCH". A zero
1180/// `payload_length` here is simply an object with no bytes.
1181#[derive(Debug, Clone, PartialEq, Eq)]
1182pub struct FetchObjectHeader {
1183    /// The Serialization Flags varint, verbatim.
1184    ///
1185    /// Kept whole rather than split into the fields below because it says more
1186    /// than which fields are present: the two low bits pick between four
1187    /// Subgroup ID meanings that share one absent field, and the values `0x8C`
1188    /// and `0x10C` are not bit patterns at all. It is also the authority
1189    /// [`Self::encode`] writes from.
1190    pub serialization_flags: VarInt,
1191    /// Group ID, when the flags put it on the wire.
1192    pub group_id: Option<VarInt>,
1193    /// Subgroup ID, present only under SUBGROUP mode `0x03`. The other three
1194    /// modes leave it off the wire with a meaning of their own, which
1195    /// [`Self::subgroup_id_mode`] reports.
1196    pub subgroup_id: Option<VarInt>,
1197    /// Object ID, when the flags put it on the wire.
1198    pub object_id: Option<VarInt>,
1199    /// Publisher priority, when the flags put it on the wire.
1200    pub publisher_priority: Option<u8>,
1201    /// Raw properties bytes, excluding the byte-length prefix that precedes
1202    /// them on the wire. Present only when the flags set the PROPERTIES bit
1203    /// (0x20), and empty otherwise — the bit is what puts the block on the
1204    /// wire, so contents held here with the bit clear are not written.
1205    ///
1206    /// Opaque, exactly as [`DatagramHeader::properties`] is: the prefix and
1207    /// these bytes are re-emitted verbatim.
1208    pub properties: Vec<u8>,
1209    /// Declared byte length of the payload that follows this header.
1210    pub payload_length: VarInt,
1211}
1212
1213impl FetchObjectHeader {
1214    /// Decode one fetch object's framing, stopping after the Object Payload
1215    /// Length.
1216    ///
1217    /// The payload itself is left in `buf` — `payload_length` says how many
1218    /// bytes of it there are, and a caller streaming objects usually wants to
1219    /// forward or skip them rather than copy them.
1220    ///
1221    /// Errors with [`CodecError::InvalidField`] on a Serialization Flags value
1222    /// draft-17 does not define. Section 10.4.4 reads the value as a bit set
1223    /// only "when less than 128", names `0x8C` and `0x10C` as the two larger
1224    /// values that mean anything, and then says of the rest: "Any other value is
1225    /// a PROTOCOL_VIOLATION."
1226    pub fn decode(buf: &mut impl Buf) -> Result<Self, CodecError> {
1227        let serialization_flags = VarInt::decode_moqt::<Wire>(buf)?;
1228        let flags = serialization_flags.into_inner();
1229        if !fetch_flags_are_defined(flags) {
1230            return Err(CodecError::InvalidField);
1231        }
1232
1233        // Read in the order Figure 27 lists them. The presence tests are the
1234        // ones the accessors below use, applied to the flags just read rather
1235        // than to a half-built value.
1236        let group_id =
1237            if fetch_has_group_id(flags) { Some(VarInt::decode_moqt::<Wire>(buf)?) } else { None };
1238        let subgroup_id = if fetch_has_subgroup_id(flags) {
1239            Some(VarInt::decode_moqt::<Wire>(buf)?)
1240        } else {
1241            None
1242        };
1243        let object_id =
1244            if fetch_has_object_id(flags) { Some(VarInt::decode_moqt::<Wire>(buf)?) } else { None };
1245        let publisher_priority = if fetch_has_priority(flags) {
1246            if buf.remaining() < 1 {
1247                return Err(CodecError::UnexpectedEnd);
1248            }
1249            Some(buf.get_u8())
1250        } else {
1251            None
1252        };
1253        let properties = if fetch_has_properties(flags) {
1254            let props_len = VarInt::decode_moqt::<Wire>(buf)?.into_inner() as usize;
1255            crate::types::read_bytes(buf, props_len)?
1256        } else {
1257            Vec::new()
1258        };
1259        let payload_length = VarInt::decode_moqt::<Wire>(buf)?;
1260
1261        Ok(FetchObjectHeader {
1262            serialization_flags,
1263            group_id,
1264            subgroup_id,
1265            object_id,
1266            publisher_priority,
1267            properties,
1268            payload_length,
1269        })
1270    }
1271
1272    /// Serialize the framing, stopping after the Object Payload Length.
1273    ///
1274    /// The payload is the caller's to append, matching [`Self::decode`] leaving
1275    /// it in the buffer.
1276    ///
1277    /// Fallible, unlike the other encoders here, because the flags and the
1278    /// fields can disagree in a way no default resolves. [`DatagramHeader`] can
1279    /// write a priority the type byte demands and the value omits, because
1280    /// draft-17 has a default priority to write; a Group ID the flags demand and
1281    /// the value omits has no such stand-in — every candidate is a Location this
1282    /// object does not have. Writing nothing there instead would slide the next
1283    /// field into its place and desynchronize the whole stream, which no reader
1284    /// downstream could detect, let alone repair.
1285    ///
1286    /// Errors with [`CodecError::InvalidField`], before any byte is written, on:
1287    ///
1288    /// - a Serialization Flags value draft-17 does not define, the set
1289    ///   [`Self::decode`] refuses;
1290    /// - a field the flags announce and the value leaves `None`;
1291    /// - a field the value supplies and the flags do not announce, including
1292    ///   non-empty `properties` with the PROPERTIES bit clear — silently
1293    ///   dropping it would emit an object stripped of metadata that the caller
1294    ///   believes it sent.
1295    pub fn encode(&self, buf: &mut impl BufMut) -> Result<(), CodecError> {
1296        let flags = self.serialization_flags.into_inner();
1297        if !fetch_flags_are_defined(flags) {
1298            return Err(CodecError::InvalidField);
1299        }
1300        if fetch_has_group_id(flags) != self.group_id.is_some()
1301            || fetch_has_subgroup_id(flags) != self.subgroup_id.is_some()
1302            || fetch_has_object_id(flags) != self.object_id.is_some()
1303            || fetch_has_priority(flags) != self.publisher_priority.is_some()
1304            || (!fetch_has_properties(flags) && !self.properties.is_empty())
1305        {
1306            return Err(CodecError::InvalidField);
1307        }
1308
1309        self.serialization_flags.encode_moqt::<Wire>(buf);
1310        if let Some(group_id) = self.group_id {
1311            group_id.encode_moqt::<Wire>(buf);
1312        }
1313        if let Some(subgroup_id) = self.subgroup_id {
1314            subgroup_id.encode_moqt::<Wire>(buf);
1315        }
1316        if let Some(object_id) = self.object_id {
1317            object_id.encode_moqt::<Wire>(buf);
1318        }
1319        if let Some(priority) = self.publisher_priority {
1320            buf.put_u8(priority);
1321        }
1322        if fetch_has_properties(flags) {
1323            VarInt::from_usize(self.properties.len()).encode_moqt::<Wire>(buf);
1324            buf.put_slice(&self.properties);
1325        }
1326        self.payload_length.encode_moqt::<Wire>(buf);
1327        Ok(())
1328    }
1329
1330    /// The end-of-range marker this object is, if it is one.
1331    ///
1332    /// `None` for every flags value below 128, which is every object that
1333    /// carries content.
1334    pub fn end_of_range(&self) -> Option<EndOfRange> {
1335        match self.serialization_flags.into_inner() {
1336            FETCH_END_OF_NON_EXISTENT_RANGE => Some(EndOfRange::NonExistent),
1337            FETCH_END_OF_UNKNOWN_RANGE => Some(EndOfRange::Unknown),
1338            _ => None,
1339        }
1340    }
1341
1342    /// The SUBGROUP mode: `serialization_flags & 0x03`, per draft-17
1343    /// Section 10.4.4.1 Table 7.
1344    ///
1345    /// `0x00` = the Subgroup ID is zero; `0x01` = it is the prior object's;
1346    /// `0x02` = it is the prior object's plus one; `0x03` = it is present in
1347    /// [`Self::subgroup_id`].
1348    ///
1349    /// Meaningless when [`Self::is_datagram`] holds — Section 10.4.4.1 says of
1350    /// the DATAGRAM bit that the subscriber "MUST ignore the bits" — and this
1351    /// reports the raw two bits regardless, so check that first.
1352    pub fn subgroup_id_mode(&self) -> u64 {
1353        self.serialization_flags.into_inner() & FETCH_SUBGROUP_MODE_MASK
1354    }
1355
1356    /// Whether the DATAGRAM bit (0x40) is set: the object was forwarded with an
1357    /// Object Forwarding Preference of Datagram and so has no Subgroup ID at
1358    /// all.
1359    pub fn is_datagram(&self) -> bool {
1360        self.serialization_flags.into_inner() & FETCH_DATAGRAM_BIT != 0
1361    }
1362
1363    /// Whether the flags set the PROPERTIES bit (0x20), which is what puts
1364    /// [`Self::properties`] on the wire.
1365    pub fn has_properties(&self) -> bool {
1366        fetch_has_properties(self.serialization_flags.into_inner())
1367    }
1368
1369    /// Whether resolving this object's fields requires the object before it on
1370    /// the stream.
1371    ///
1372    /// True when any of the Group ID, Object ID or Priority fields is absent —
1373    /// draft-17 Section 10.4.4.1 Table 8 defines each absent field in terms of
1374    /// "the prior Object" — or when the SUBGROUP mode names the prior object's
1375    /// Subgroup ID or that ID plus one. Mode `0x00` is not such a case: it fixes
1376    /// the Subgroup ID at zero without consulting anything.
1377    ///
1378    /// This is the predicate Section 10.4.4 makes load-bearing: "If the first
1379    /// Object in the FETCH response uses a flag that references fields in the
1380    /// prior Object, the Subscriber MUST close the session with a
1381    /// PROTOCOL_VIOLATION." A single object's bytes cannot tell whether it is
1382    /// the first, so the decoder cannot enforce that; a caller reading the
1383    /// stream can, and this is what it asks.
1384    ///
1385    /// False for both end-of-range markers. Section 10.4.4.2 fixes their fields
1386    /// outright — "the Group ID and Object ID fields are present. Subgroup ID,
1387    /// Priority and Properties are not present" — so a marker inherits nothing,
1388    /// and the section's own phrase "the last serialized Object, if any" allows
1389    /// one to open a response.
1390    pub fn references_prior_object(&self) -> bool {
1391        if self.end_of_range().is_some() {
1392            return false;
1393        }
1394        let flags = self.serialization_flags.into_inner();
1395        let inherits_subgroup = !self.is_datagram()
1396            && matches!(
1397                flags & FETCH_SUBGROUP_MODE_MASK,
1398                FETCH_SUBGROUP_MODE_PRIOR | FETCH_SUBGROUP_MODE_PRIOR_PLUS_ONE
1399            );
1400        !fetch_has_group_id(flags)
1401            || !fetch_has_object_id(flags)
1402            || !fetch_has_priority(flags)
1403            || inherits_subgroup
1404    }
1405}
1406
1407/// Whether draft-17 defines this Serialization Flags value.
1408///
1409/// Section 10.4.4: the value is a bit set "when less than 128"; `0x8C` and
1410/// `0x10C` are the two larger values Table 6 defines; "Any other value is a
1411/// PROTOCOL_VIOLATION."
1412fn fetch_flags_are_defined(flags: u64) -> bool {
1413    flags <= FETCH_FLAGS_BIT_FORM_MAX
1414        || flags == FETCH_END_OF_NON_EXISTENT_RANGE
1415        || flags == FETCH_END_OF_UNKNOWN_RANGE
1416}
1417
1418fn fetch_has_group_id(flags: u64) -> bool {
1419    flags & FETCH_GROUP_ID_BIT != 0
1420}
1421
1422/// Whether an explicit Subgroup ID field follows the Group ID.
1423///
1424/// The DATAGRAM bit wins over the mode bits. Section 10.4.4.1: "When 0x40 is
1425/// set, it SHOULD set the two least significant bits to zero and the subscriber
1426/// MUST ignore the bits." A publisher that sets the bit and leaves the mode at
1427/// `0x03` anyway has written no Subgroup ID field, so reading one would consume
1428/// the Object ID in its place.
1429///
1430/// Both end-of-range values carry mode `0x00`, which is also what
1431/// Section 10.4.4.2 requires of them, so they need no case of their own here.
1432fn fetch_has_subgroup_id(flags: u64) -> bool {
1433    flags & FETCH_DATAGRAM_BIT == 0
1434        && flags & FETCH_SUBGROUP_MODE_MASK == FETCH_SUBGROUP_MODE_EXPLICIT
1435}
1436
1437fn fetch_has_object_id(flags: u64) -> bool {
1438    flags & FETCH_OBJECT_ID_BIT != 0
1439}
1440
1441fn fetch_has_priority(flags: u64) -> bool {
1442    flags & FETCH_PRIORITY_BIT != 0
1443}
1444
1445fn fetch_has_properties(flags: u64) -> bool {
1446    flags & FETCH_PROPERTIES_BIT != 0
1447}
1448
1449/// One frame from a FETCH stream with the fields its Serialization Flags left
1450/// off the wire filled in from the frames before it.
1451///
1452/// The header is kept alongside the resolved values so that a caller can
1453/// forward the frame's bytes unchanged while acting on what they mean.
1454#[derive(Debug, Clone, PartialEq, Eq)]
1455pub struct FetchObject {
1456    /// The frame as it appeared on the wire.
1457    pub header: FetchObjectHeader,
1458    /// Resolved absolute Group ID. On an End of Range marker, the Group ID of
1459    /// the Location the marker names.
1460    pub group_id: u64,
1461    /// Resolved Subgroup ID. `None` for an End of Range marker, which has
1462    /// none, and for an Object whose forwarding preference is Datagram.
1463    pub subgroup_id: Option<u64>,
1464    /// Resolved absolute Object ID. On an End of Range marker, the Object ID of
1465    /// the Location the marker names.
1466    pub object_id: u64,
1467    /// The Publisher Priority in force for this frame, whether this frame wrote
1468    /// it or an earlier one did, and `None` while no frame has written one.
1469    ///
1470    /// An End of Range marker carries no Priority field of its own, so what it
1471    /// reports is the one still in force from the last Object before it —
1472    /// Section 10.4.4.2: "Prior Priority: The Priority from the last actual
1473    /// Object before the End of Range indicator."
1474    ///
1475    /// The fallback for a subscription that never stated a priority is left to
1476    /// the caller rather than substituted here, so that "no frame has said"
1477    /// stays distinguishable from "a frame said 128".
1478    pub publisher_priority: Option<u8>,
1479}
1480
1481/// Resolves the elided fields of the frames on one FETCH stream.
1482///
1483/// Draft-17 Section 10.4.4.1, Table 8 defines every field a frame omits as the
1484/// prior Object's — a Group ID repeated, an Object ID stepped by one, a
1485/// Priority carried over — and Table 7 does the same for the Subgroup ID, so no
1486/// frame after the first can be understood on its own. This holds what the
1487/// frames so far established, in the two parts the draft keeps separate:
1488/// Section 10.4.4.2 says that after an End of Range marker the prior Group ID
1489/// and Object ID are the marker's, while the prior Subgroup ID and Priority are
1490/// still "from the last actual Object before the End of Range indicator".
1491///
1492/// Nothing here is a delta. The fields that *are* on the wire hold values
1493/// rather than differences, which is what separates this from draft-18's reader
1494/// of the same name: draft-18 renamed both ID fields to deltas and gave them
1495/// arithmetic, which is also why this reader needs no Group Order and
1496/// draft-18's does.
1497#[derive(Debug, Clone, Default)]
1498pub struct FetchObjectReader {
1499    /// Group ID and Object ID of the last frame, marker or Object.
1500    prior_location: Option<(u64, u64)>,
1501    /// Subgroup ID of the last actual Object that had one.
1502    prior_subgroup_id: Option<u64>,
1503    /// Publisher Priority of the last actual Object.
1504    prior_publisher_priority: Option<u8>,
1505}
1506
1507impl FetchObjectReader {
1508    /// A reader positioned before the first frame of a fetch stream, with no
1509    /// prior Object to inherit from.
1510    pub fn new() -> Self {
1511        Self::default()
1512    }
1513
1514    /// Decode the next frame's header and resolve its fields.
1515    ///
1516    /// Consumes the header only. The Object Payload is
1517    /// `header.payload_length` bytes and stays in `buf`, so a caller that
1518    /// forwards payloads never copies them and one that ignores them can skip.
1519    ///
1520    /// Errors with [`CodecError::InvalidField`] when a frame names a field of a
1521    /// prior Object that does not exist — Section 10.4.4.1: "If the first
1522    /// Object in the FETCH response uses a flag that references fields in the
1523    /// prior Object, the Subscriber MUST close the session with a
1524    /// PROTOCOL_VIOLATION" — and when a Subgroup ID or Object ID one past the
1525    /// prior one would leave the 64-bit range.
1526    pub fn read_object_header(&mut self, buf: &mut impl Buf) -> Result<FetchObject, CodecError> {
1527        let header = FetchObjectHeader::decode(buf)?;
1528
1529        // An End of Range marker states a Location outright and inherits
1530        // nothing, so it is resolved before any of the prior-Object rules.
1531        if header.end_of_range().is_some() {
1532            let group_id = header.group_id.ok_or(CodecError::InvalidField)?.into_inner();
1533            let object_id = header.object_id.ok_or(CodecError::InvalidField)?.into_inner();
1534            self.prior_location = Some((group_id, object_id));
1535            let publisher_priority = self.prior_publisher_priority;
1536            return Ok(FetchObject {
1537                header,
1538                group_id,
1539                subgroup_id: None,
1540                object_id,
1541                publisher_priority,
1542            });
1543        }
1544
1545        let group_id = match header.group_id {
1546            Some(v) => v.into_inner(),
1547            None => self.prior_location.ok_or(CodecError::InvalidField)?.0,
1548        };
1549        let object_id = match header.object_id {
1550            Some(v) => v.into_inner(),
1551            None => self
1552                .prior_location
1553                .ok_or(CodecError::InvalidField)?
1554                .1
1555                .checked_add(1)
1556                .ok_or(CodecError::InvalidField)?,
1557        };
1558        let subgroup_id = if header.is_datagram() {
1559            None
1560        } else {
1561            Some(match header.subgroup_id_mode() {
1562                0x00 => 0,
1563                0x01 => self.prior_subgroup_id.ok_or(CodecError::InvalidField)?,
1564                0x02 => self
1565                    .prior_subgroup_id
1566                    .ok_or(CodecError::InvalidField)?
1567                    .checked_add(1)
1568                    .ok_or(CodecError::InvalidField)?,
1569                // Mode 0x03, the only value left: the field is on the wire.
1570                _ => header.subgroup_id.ok_or(CodecError::InvalidField)?.into_inner(),
1571            })
1572        };
1573        let publisher_priority = match header.publisher_priority {
1574            Some(p) => p,
1575            None => self.prior_publisher_priority.ok_or(CodecError::InvalidField)?,
1576        };
1577
1578        self.prior_location = Some((group_id, object_id));
1579        // A Datagram-forwarded object has no Subgroup ID to leave behind, so it
1580        // does not clear the running one: the object after it inherits from the
1581        // last object that had one.
1582        if let Some(subgroup_id) = subgroup_id {
1583            self.prior_subgroup_id = Some(subgroup_id);
1584        }
1585        self.prior_publisher_priority = Some(publisher_priority);
1586
1587        Ok(FetchObject {
1588            header,
1589            group_id,
1590            subgroup_id,
1591            object_id,
1592            publisher_priority: Some(publisher_priority),
1593        })
1594    }
1595}
1596
1597/// Re-encodes resolved fetch frames onto one FETCH stream.
1598///
1599/// The exact inverse of [`FetchObjectReader`], and it exists for one caller:
1600/// something that has read a stream and is writing a different stream from the
1601/// same frames. Removing a frame changes what the frames after it are read
1602/// against, and draft-17 Section 10.4.4.1 lets an Object leave out its Group
1603/// ID, Object ID, Subgroup ID and Priority and take the prior Object's, so the
1604/// survivor that follows a removed run cannot keep its original bytes: a field
1605/// it left off has to appear, and a flag bit with it.
1606///
1607/// # Draft-17 states these fields, it does not delta them
1608///
1609/// A Group ID or Object ID that is on the wire here is the absolute value, not
1610/// a difference — the deltas arrive at draft-18. What is stateful is the
1611/// *omission*: no Group ID means the prior Object's, and no Object ID means the
1612/// prior Object's plus one. That is enough to make removal a re-encode, and it
1613/// is why this writer refuses nothing an Object can be: every identity has an
1614/// encoding here, however the predecessor moved.
1615///
1616/// # Why this is not a general encoder
1617///
1618/// Every frame it writes came off a stream, so the caller holds the frame's own
1619/// [`FetchObjectHeader`] alongside the resolved values, and that header is used
1620/// as the preference: wherever the original shape still says the same thing
1621/// against the new predecessor it is kept, so a stream with nothing removed is
1622/// reproduced byte for byte.
1623#[derive(Debug, Clone, Default)]
1624pub struct FetchObjectWriter {
1625    /// Group ID and Object ID of the last frame written, marker or Object.
1626    prior_location: Option<(u64, u64)>,
1627    /// Subgroup ID of the last actual Object written that had one.
1628    prior_subgroup_id: Option<u64>,
1629    /// Publisher Priority of the last actual Object written.
1630    prior_publisher_priority: Option<u8>,
1631}
1632
1633impl FetchObjectWriter {
1634    /// A writer positioned before the first Object of a fetch stream, with no
1635    /// prior Object for anything to be encoded against.
1636    pub fn new() -> Self {
1637        Self::default()
1638    }
1639
1640    /// The header that encodes `frame` against everything written so far.
1641    ///
1642    /// Does not advance the writer — [`Self::write_object_header`] is the call
1643    /// that does both.
1644    ///
1645    /// # Errors
1646    ///
1647    /// [`CodecError::InvalidField`] for an Object with neither a Subgroup ID
1648    /// nor the Datagram bit, and for one with no Priority: both are frames no
1649    /// draft-17 stream could carry, and inventing a value would put a different
1650    /// Object on the wire than the one this was handed.
1651    pub fn header_for(&self, frame: &FetchObject) -> Result<FetchObjectHeader, CodecError> {
1652        let original = &frame.header;
1653
1654        // An End of Range marker states its Location outright and inherits
1655        // nothing, so its two fields are the same whatever precedes it.
1656        if original.end_of_range().is_some() {
1657            return Ok(FetchObjectHeader {
1658                serialization_flags: original.serialization_flags,
1659                group_id: Some(VarInt::from_u64(frame.group_id)?),
1660                subgroup_id: None,
1661                object_id: Some(VarInt::from_u64(frame.object_id)?),
1662                publisher_priority: None,
1663                properties: Vec::new(),
1664                payload_length: original.payload_length,
1665            });
1666        }
1667
1668        let (group_id, object_id) = self.identity_fields(frame, original)?;
1669        let (subgroup_mode, subgroup_id) = self.subgroup_field(frame, original)?;
1670        let publisher_priority = self.priority_field(frame, original)?;
1671
1672        let flags = original.serialization_flags.into_inner();
1673        let mut new_flags = subgroup_mode;
1674        if flags & FETCH_DATAGRAM_BIT != 0 {
1675            new_flags |= FETCH_DATAGRAM_BIT;
1676        }
1677        if group_id.is_some() {
1678            new_flags |= FETCH_GROUP_ID_BIT;
1679        }
1680        if object_id.is_some() {
1681            new_flags |= FETCH_OBJECT_ID_BIT;
1682        }
1683        if publisher_priority.is_some() {
1684            new_flags |= FETCH_PRIORITY_BIT;
1685        }
1686        if flags & FETCH_PROPERTIES_BIT != 0 {
1687            new_flags |= FETCH_PROPERTIES_BIT;
1688        }
1689
1690        Ok(FetchObjectHeader {
1691            serialization_flags: VarInt::from_u64(new_flags)?,
1692            group_id,
1693            subgroup_id,
1694            object_id,
1695            publisher_priority,
1696            properties: original.properties.clone(),
1697            payload_length: original.payload_length,
1698        })
1699    }
1700
1701    /// The Group ID and Object ID fields, present only where leaving them off
1702    /// would say something else.
1703    ///
1704    /// Both are absolute when written, so the choice is only whether to write
1705    /// them, and it is made in favour of the shape the frame arrived in: an
1706    /// Object that stated its Group ID keeps stating it even where the
1707    /// predecessor now shares it, which costs the same bytes it already cost.
1708    fn identity_fields(
1709        &self,
1710        frame: &FetchObject,
1711        original: &FetchObjectHeader,
1712    ) -> Result<(Option<VarInt>, Option<VarInt>), CodecError> {
1713        let group_id = match self.prior_location {
1714            Some((prior_group, _))
1715                if original.group_id.is_none() && prior_group == frame.group_id =>
1716            {
1717                None
1718            }
1719            _ => Some(VarInt::from_u64(frame.group_id)?),
1720        };
1721        let object_id = match self.prior_location {
1722            Some((_, prior_object))
1723                if original.object_id.is_none()
1724                    && prior_object.checked_add(1) == Some(frame.object_id) =>
1725            {
1726                None
1727            }
1728            _ => Some(VarInt::from_u64(frame.object_id)?),
1729        };
1730        Ok((group_id, object_id))
1731    }
1732
1733    /// The Subgroup ID mode bits and the explicit field, if one is needed.
1734    ///
1735    /// The frame's own mode is tried first, so a run of Objects that inherited
1736    /// their Subgroup ID keeps inheriting it and its bytes do not move.
1737    fn subgroup_field(
1738        &self,
1739        frame: &FetchObject,
1740        original: &FetchObjectHeader,
1741    ) -> Result<(u64, Option<VarInt>), CodecError> {
1742        // With the Datagram bit set the two low bits say nothing and no field
1743        // is on the wire, so the frame's own bits are carried across untouched.
1744        if original.is_datagram() {
1745            return Ok((
1746                original.serialization_flags.into_inner() & FETCH_SUBGROUP_MODE_MASK,
1747                None,
1748            ));
1749        }
1750
1751        let subgroup_id = frame.subgroup_id.ok_or(CodecError::InvalidField)?;
1752        let inherits = self.prior_subgroup_id == Some(subgroup_id);
1753        let successor =
1754            self.prior_subgroup_id.is_some_and(|p| p.checked_add(1) == Some(subgroup_id));
1755
1756        // Mode 0x00 is *the Subgroup ID is zero*; the reader reads it that way
1757        // and there is no named constant for it beside the other three.
1758        let kept = match original.subgroup_id_mode() {
1759            0x00 if subgroup_id == 0 => Some((0x00, None)),
1760            FETCH_SUBGROUP_MODE_PRIOR if inherits => Some((FETCH_SUBGROUP_MODE_PRIOR, None)),
1761            FETCH_SUBGROUP_MODE_PRIOR_PLUS_ONE if successor => {
1762                Some((FETCH_SUBGROUP_MODE_PRIOR_PLUS_ONE, None))
1763            }
1764            FETCH_SUBGROUP_MODE_EXPLICIT => Some((FETCH_SUBGROUP_MODE_EXPLICIT, Some(subgroup_id))),
1765            _ => None,
1766        };
1767        let (mode, explicit) = match kept {
1768            Some(pair) => pair,
1769            None if subgroup_id == 0 => (0x00, None),
1770            None if inherits => (FETCH_SUBGROUP_MODE_PRIOR, None),
1771            None if successor => (FETCH_SUBGROUP_MODE_PRIOR_PLUS_ONE, None),
1772            None => (FETCH_SUBGROUP_MODE_EXPLICIT, Some(subgroup_id)),
1773        };
1774        Ok((mode, explicit.map(VarInt::from_u64).transpose()?))
1775    }
1776
1777    /// The Publisher Priority field, or `None` when the predecessor already
1778    /// carries it.
1779    fn priority_field(
1780        &self,
1781        frame: &FetchObject,
1782        original: &FetchObjectHeader,
1783    ) -> Result<Option<u8>, CodecError> {
1784        let priority = frame.publisher_priority.ok_or(CodecError::InvalidField)?;
1785        if original.publisher_priority.is_some() || self.prior_publisher_priority != Some(priority)
1786        {
1787            return Ok(Some(priority));
1788        }
1789        Ok(None)
1790    }
1791
1792    /// Encode `frame` against everything written so far and advance.
1793    ///
1794    /// Writes the header only. The payload is `frame.header.payload_length`
1795    /// bytes and is the caller's to copy, unchanged.
1796    ///
1797    /// # Errors
1798    ///
1799    /// [`CodecError::InvalidField`] for a frame with no encoding at all; the
1800    /// writer is left untouched when this happens.
1801    pub fn write_object_header(
1802        &mut self,
1803        frame: &FetchObject,
1804        out: &mut impl BufMut,
1805    ) -> Result<FetchObjectHeader, CodecError> {
1806        let header = self.header_for(frame)?;
1807        header.encode(out)?;
1808        self.advance(frame);
1809        Ok(header)
1810    }
1811
1812    /// Record `frame` as the predecessor of whatever is written next.
1813    ///
1814    /// Public because a re-emitting caller has a second way of putting a frame
1815    /// on the wire: when the framing it arrived in still encodes the same
1816    /// meaning against the frame before it, its own bytes are forwarded
1817    /// untouched — no header is produced and nothing is copied. The writer
1818    /// still has to move, or the frame after it is encoded against a
1819    /// predecessor one frame stale.
1820    pub fn advance(&mut self, frame: &FetchObject) {
1821        self.prior_location = Some((frame.group_id, frame.object_id));
1822        // Mirrors the reader: a Datagram-forwarded Object leaves no Subgroup ID
1823        // behind, so the running one survives it.
1824        if let Some(subgroup_id) = frame.subgroup_id {
1825            self.prior_subgroup_id = Some(subgroup_id);
1826        }
1827        if frame.header.end_of_range().is_none() {
1828            if let Some(priority) = frame.publisher_priority {
1829                self.prior_publisher_priority = Some(priority);
1830            }
1831        }
1832    }
1833}
1834
1835#[cfg(test)]
1836mod tests {
1837    use super::*;
1838
1839    /// Canonically encoded subgroup stream vectors from
1840    /// `test-vectors/transport/draft17/codec/data-streams/subgroup.json`.
1841    /// `subgroup-explicit-subgroup-id` is omitted: it encodes group_id 100 as a
1842    /// two-byte varint, which does not survive a minimal-width re-encode.
1843    const VECTORS: &[&str] = &[
1844        // subgroup-single-object
1845        "100100800004deadbeef",
1846        // subgroup-two-objects
1847        "100100800004deadbeef0002cafe",
1848        // subgroup-no-priority
1849        "3001000004deadbeef",
1850        // subgroup-with-extensions
1851        "11010080000004deadbeef",
1852        // subgroup-end-of-group
1853        "180105800004deadbeef",
1854        // subgroup-id-mode-01
1855        "120100800504deadbeef",
1856        // subgroup-with-object-properties
1857        "1101008000043c02020104deadbeef",
1858        // subgroup-object-status-end-of-group
1859        "100100800004deadbeef000003",
1860        // subgroup-object-status-end-of-track
1861        "10010080000004",
1862        // subgroup-properties-two-objects-empty
1863        "11010080000004deadbeef000002cafe",
1864        // subgroup-properties-two-objects-nonempty
1865        "1101008000023c0204deadbeef00023c0302cafe",
1866        // subgroup-properties-status-object
1867        "1101008000023c010003",
1868    ];
1869
1870    fn vi(v: u64) -> VarInt {
1871        VarInt::from_u64_moqt(v)
1872    }
1873
1874    fn hex(s: &str) -> Vec<u8> {
1875        (0..s.len()).step_by(2).map(|i| u8::from_str_radix(&s[i..i + 2], 16).unwrap()).collect()
1876    }
1877
1878    /// Decode a whole subgroup stream: the header, then every object up to
1879    /// the end of the buffer.
1880    fn decode_all(bytes: &[u8]) -> (SubgroupHeader, Vec<SubgroupObject>) {
1881        let mut cursor = bytes;
1882        let header = SubgroupHeader::decode(&mut cursor)
1883            .unwrap_or_else(|e| panic!("header decode failed: {e:?}"));
1884        let mut reader = SubgroupObjectReader::new(&header);
1885        let mut objects = Vec::new();
1886        while cursor.has_remaining() {
1887            objects.push(
1888                reader
1889                    .read_object(&mut cursor)
1890                    .unwrap_or_else(|e| panic!("object {} decode failed: {e:?}", objects.len())),
1891            );
1892        }
1893        (header, objects)
1894    }
1895
1896    fn encode_all(header: &SubgroupHeader, objects: &[SubgroupObject]) -> Vec<u8> {
1897        let mut buf = Vec::new();
1898        header.encode(&mut buf);
1899        let mut writer = SubgroupObjectReader::new(header);
1900        for o in objects {
1901            writer.write_object(o, &mut buf).unwrap_or_else(|e| panic!("write failed: {e:?}"));
1902        }
1903        buf
1904    }
1905
1906    fn object(id: u64, extensions: Vec<u8>, payload: Vec<u8>) -> SubgroupObject {
1907        SubgroupObject {
1908            object_id: vi(id),
1909            extension_headers: extensions,
1910            payload_length: vi(payload.len() as u64),
1911            object_status: None,
1912            payload,
1913        }
1914    }
1915
1916    // ── Object ID deltas ────────────────────────────────────
1917
1918    #[test]
1919    fn two_objects_with_properties_have_distinct_ids() {
1920        // Vector `subgroup-properties-two-objects-empty`: two objects, each
1921        // carrying an empty properties block and a delta of 0. The delta is
1922        // biased by one whether or not the properties bit is set, so the IDs
1923        // are 0 and 1 — not 0 and 0.
1924        let bytes = hex("11010080000004deadbeef000002cafe");
1925        let (header, objects) = decode_all(&bytes);
1926        assert!(header.has_properties());
1927        assert_eq!(objects.len(), 2);
1928        assert_eq!(objects[0].object_id.into_inner(), 0);
1929        assert_eq!(objects[1].object_id.into_inner(), 1);
1930        assert_eq!(objects[0].payload, hex("deadbeef"));
1931        assert_eq!(objects[1].payload, hex("cafe"));
1932        assert!(objects.iter().all(|o| o.extension_headers.is_empty()));
1933    }
1934
1935    #[test]
1936    fn deltas_resolve_sparse_ids() {
1937        let header = SubgroupHeader::decode(&mut &hex("100100800004deadbeef")[..]).unwrap();
1938        let objects: Vec<_> =
1939            [3u64, 4, 40].iter().map(|&id| object(id, vec![], vec![0xAA, id as u8])).collect();
1940        let (_, decoded) = decode_all(&encode_all(&header, &objects));
1941        let ids: Vec<u64> = decoded.iter().map(|o| o.object_id.into_inner()).collect();
1942        assert_eq!(ids, vec![3, 4, 40]);
1943    }
1944
1945    #[test]
1946    fn write_rejects_non_increasing_ids() {
1947        let header = SubgroupHeader::decode(&mut &hex("100100800004deadbeef")[..]).unwrap();
1948        let mut writer = SubgroupObjectReader::new(&header);
1949        let mut buf = Vec::new();
1950        writer.write_object(&object(7, vec![], vec![0x01]), &mut buf).unwrap();
1951        for id in [7u64, 6, 0] {
1952            let err = writer.write_object(&object(id, vec![], vec![0x01]), &mut buf).unwrap_err();
1953            assert!(matches!(err, CodecError::InvalidField), "id {id} gave {err:?}");
1954        }
1955    }
1956
1957    #[test]
1958    fn eliding_an_object_renumbers_its_successor() {
1959        let header = SubgroupHeader::decode(&mut &hex("100100800004deadbeef")[..]).unwrap();
1960        let all: Vec<_> = (0..5u64).map(|id| object(id, vec![], vec![id as u8])).collect();
1961        for elided in 0..5u64 {
1962            let kept: Vec<_> =
1963                all.iter().filter(|o| o.object_id.into_inner() != elided).cloned().collect();
1964            let (_, decoded) = decode_all(&encode_all(&header, &kept));
1965            let ids: Vec<u64> = decoded.iter().map(|o| o.object_id.into_inner()).collect();
1966            let expected: Vec<u64> = (0..5u64).filter(|&i| i != elided).collect();
1967            assert_eq!(ids, expected, "eliding object {elided}");
1968        }
1969    }
1970
1971    // ── Properties blocks ──────────────────────────────
1972
1973    #[test]
1974    fn properties_blob_excludes_its_length_prefix() {
1975        // Vector `subgroup-properties-two-objects-nonempty`: each
1976        // object carries a two-byte block, so the blob is those two bytes
1977        // with the `02` length prefix stripped.
1978        let bytes = hex("1101008000023c0204deadbeef00023c0302cafe");
1979        let (_, objects) = decode_all(&bytes);
1980        assert_eq!(objects.len(), 2);
1981        assert_eq!(objects[0].object_id.into_inner(), 0);
1982        assert_eq!(objects[1].object_id.into_inner(), 1);
1983        assert_eq!(objects[0].extension_headers, hex("3c02"));
1984        assert_eq!(objects[1].extension_headers, hex("3c03"));
1985        assert_eq!(objects[0].payload, hex("deadbeef"));
1986        assert_eq!(objects[1].payload, hex("cafe"));
1987    }
1988
1989    #[test]
1990    fn status_object_carries_its_properties_block() {
1991        let (_, objects) = decode_all(&hex("1101008000023c010003"));
1992        assert_eq!(objects.len(), 1);
1993        assert_eq!(objects[0].extension_headers, hex("3c01"));
1994        assert_eq!(objects[0].payload_length.into_inner(), 0);
1995        assert_eq!(objects[0].object_status.map(ObjectStatus::as_u64), Some(3));
1996        assert!(objects[0].payload.is_empty());
1997    }
1998
1999    // ── Re-encoding ─────────────────────────────────────────
2000
2001    #[test]
2002    fn vectors_re_encode_byte_identically() {
2003        for vector in VECTORS {
2004            let bytes = hex(vector);
2005            let (header, objects) = decode_all(&bytes);
2006            assert_eq!(encode_all(&header, &objects), bytes, "[{vector}] re-encode");
2007        }
2008    }
2009
2010    // ── Payload-free framing ────────────────────────────────
2011
2012    #[test]
2013    fn meta_matches_read_object() {
2014        for vector in VECTORS {
2015            let bytes = hex(vector);
2016            let mut cursor = &bytes[..];
2017            let header = SubgroupHeader::decode(&mut cursor).unwrap();
2018            let mut full_reader = SubgroupObjectReader::new(&header);
2019            let mut meta_reader = SubgroupObjectReader::new(&header);
2020            let mut full_cursor = cursor;
2021            let mut meta_cursor = cursor;
2022            while meta_cursor.has_remaining() {
2023                let before = meta_cursor.remaining();
2024                let object = full_reader.read_object(&mut full_cursor).unwrap();
2025                let meta = meta_reader.read_object_meta(&mut meta_cursor).unwrap();
2026                assert_eq!(meta.object_id, object.object_id.into_inner(), "[{vector}]");
2027                assert_eq!(
2028                    meta.extension_headers_len,
2029                    object.extension_headers.len() as u64,
2030                    "[{vector}]"
2031                );
2032                assert_eq!(meta.payload_length, object.payload_length.into_inner(), "[{vector}]");
2033                assert_eq!(
2034                    meta.status,
2035                    object.object_status.map(ObjectStatus::as_u64),
2036                    "[{vector}]"
2037                );
2038                assert_eq!(meta.wire_len, (before - meta_cursor.remaining()) as u64, "[{vector}]");
2039                assert_eq!(full_cursor.remaining(), meta_cursor.remaining(), "[{vector}]");
2040            }
2041        }
2042    }
2043
2044    #[test]
2045    fn short_buffers_report_unexpected_end() {
2046        let bytes = hex("1101008000023c0204deadbeef00023c0302cafe");
2047        let mut cursor = &bytes[..];
2048        let header = SubgroupHeader::decode(&mut cursor).unwrap();
2049        let objects_start = bytes.len() - cursor.len();
2050        for cut in objects_start..bytes.len() {
2051            let mut reader = SubgroupObjectReader::new(&header);
2052            let mut meta_reader = SubgroupObjectReader::new(&header);
2053            let mut cursor = &bytes[objects_start..cut];
2054            let mut meta_cursor = cursor;
2055            while cursor.has_remaining() {
2056                if let Err(err) = reader.read_object(&mut cursor) {
2057                    assert!(
2058                        matches!(err, CodecError::UnexpectedEnd | CodecError::VarInt(_)),
2059                        "cut {cut} gave {err:?}"
2060                    );
2061                    break;
2062                }
2063            }
2064            while meta_cursor.has_remaining() {
2065                if let Err(err) = meta_reader.read_object_meta(&mut meta_cursor) {
2066                    assert!(
2067                        matches!(err, CodecError::UnexpectedEnd | CodecError::VarInt(_)),
2068                        "cut {cut} gave {err:?}"
2069                    );
2070                    break;
2071                }
2072            }
2073        }
2074    }
2075
2076    // ── Object status ───────────────────────────────────────
2077
2078    /// A one-object subgroup stream whose object carries `status` in place of
2079    /// a payload: header type 0x10 (no properties, subgroup-ID mode 0), track
2080    /// alias 1, group 0, publisher priority 128; then an Object ID delta of 0,
2081    /// a payload length of 0, and the status code.
2082    fn subgroup_status_stream(status: u64) -> Vec<u8> {
2083        vec![0x10, 0x01, 0x00, 0x80, 0x00, 0x00, status as u8]
2084    }
2085
2086    /// A status datagram carrying `status`: type 0x20 (STATUS bit set,
2087    /// explicit Object ID, explicit priority), track alias 1, group 0, object
2088    /// 0, priority 128, then the status byte.
2089    fn status_datagram(status: u64) -> Vec<u8> {
2090        vec![0x20, 0x01, 0x00, 0x00, 0x80, status as u8]
2091    }
2092
2093    /// The object [`subgroup_status_stream`] describes, as a value.
2094    fn status_object(status: Option<ObjectStatus>) -> SubgroupObject {
2095        SubgroupObject {
2096            object_id: vi(0),
2097            extension_headers: Vec::new(),
2098            payload_length: vi(0),
2099            object_status: status,
2100            payload: Vec::new(),
2101        }
2102    }
2103
2104    /// The datagram [`status_datagram`] describes, as a value.
2105    fn status_datagram_header(status: Option<ObjectStatus>) -> DatagramHeader {
2106        DatagramHeader {
2107            datagram_type: 0x20,
2108            track_alias: vi(1),
2109            group_id: vi(0),
2110            object_id: vi(0),
2111            publisher_priority: Some(128),
2112            properties: Vec::new(),
2113            object_status: status,
2114        }
2115    }
2116
2117    /// Every status draft-17 assigns can be written and read back as the same
2118    /// status, on both a subgroup stream and a status datagram.
2119    ///
2120    /// The set is read from `ObjectStatus::ALL` rather than restated here, so
2121    /// this moves with the draft if a code is ever reassigned. It is the gate
2122    /// on typing the two `object_status` fields: a typed field that silently
2123    /// narrowed or renumbered the set would fail here even though it still
2124    /// compiled.
2125    ///
2126    /// Writing `ObjectStatus::Normal` when a zero-length object's status is
2127    /// `None` is checked too — without it the encoder emits an object whose
2128    /// declared payload length promises a status field that never arrives.
2129    ///
2130    /// Made `write_object` encode a constant `ObjectStatus::Normal` instead of
2131    /// the object's own status, ran it, and got:
2132    ///
2133    /// ```text
2134    /// assertion `left == right` failed: subgroup object status
2135    ///   left: Some(Normal)
2136    ///  right: Some(EndOfGroup)
2137    /// ```
2138    ///
2139    /// The same change to `DatagramHeader::encode` gives:
2140    ///
2141    /// ```text
2142    /// assertion `left == right` failed: datagram object status
2143    ///   left: Some(Normal)
2144    ///  right: Some(EndOfGroup)
2145    /// ```
2146    #[test]
2147    fn every_assigned_status_survives_a_round_trip() {
2148        let header = SubgroupHeader::decode(&mut &hex("100100800004deadbeef")[..]).unwrap();
2149        for &status in ObjectStatus::ALL {
2150            let mut buf = Vec::new();
2151            SubgroupObjectReader::new(&header)
2152                .write_object(&status_object(Some(status)), &mut buf)
2153                .unwrap_or_else(|e| panic!("write_object refused {status:?}: {e:?}"));
2154
2155            let mut cursor = &buf[..];
2156            let object =
2157                SubgroupObjectReader::new(&header).read_object(&mut cursor).unwrap_or_else(|e| {
2158                    panic!("read_object refused the bytes written for {status:?}: {e:?}")
2159                });
2160            assert_eq!(object.object_status, Some(status), "subgroup object status");
2161            assert!(!cursor.has_remaining(), "{status:?}: bytes left over after read_object");
2162
2163            let meta =
2164                SubgroupObjectReader::new(&header).read_object_meta(&mut &buf[..]).unwrap_or_else(
2165                    |e| panic!("read_object_meta refused the bytes written for {status:?}: {e:?}"),
2166                );
2167            assert_eq!(meta.status, Some(status.as_u64()), "subgroup meta status");
2168
2169            let mut datagram = Vec::new();
2170            status_datagram_header(Some(status)).encode(&mut datagram);
2171            let decoded = DatagramHeader::decode(&mut &datagram[..]).unwrap_or_else(|e| {
2172                panic!("datagram decode refused the bytes written for {status:?}: {e:?}")
2173            });
2174            assert_eq!(decoded.object_status, Some(status), "datagram object status");
2175        }
2176
2177        let mut buf = Vec::new();
2178        SubgroupObjectReader::new(&header).write_object(&status_object(None), &mut buf).unwrap();
2179        let object = SubgroupObjectReader::new(&header)
2180            .read_object(&mut &buf[..])
2181            .expect("a zero-length object with no status must still decode");
2182        assert_eq!(object.object_status, Some(ObjectStatus::Normal));
2183
2184        let mut datagram = Vec::new();
2185        status_datagram_header(None).encode(&mut datagram);
2186        let decoded = DatagramHeader::decode(&mut &datagram[..])
2187            .expect("a status datagram with no status must still decode");
2188        assert_eq!(decoded.object_status, Some(ObjectStatus::Normal));
2189    }
2190
2191    /// The encoder writes exactly the frames the decoder accepts.
2192    ///
2193    /// Sweeps every status code `0x00..=0x3f` — one wire byte under both the
2194    /// varint on a subgroup stream and the bare byte on a datagram, and wide
2195    /// enough to contain the gap at `0x2` and the `0x1` draft-16 dropped. For
2196    /// a code the draft assigns, the hand-built frame must decode *and* the
2197    /// encoder handed that status must reproduce those exact bytes. For a code
2198    /// it does not assign, the same frame must be refused at all three decode
2199    /// sites — and no `ObjectStatus` exists to hand the encoder, so the frame
2200    /// has no way to be produced in the first place.
2201    ///
2202    /// # What this catches, observed by making each change and running it
2203    ///
2204    /// Encoding a constant `ObjectStatus::Normal` in `write_object` instead of
2205    /// the object's own status:
2206    ///
2207    /// ```text
2208    /// assertion `left == right` failed: the encoder must produce the frame the decoder accepted for status 0x3
2209    ///   left: [16, 1, 0, 128, 0, 0, 0]
2210    ///  right: [16, 1, 0, 128, 0, 0, 3]
2211    /// ```
2212    ///
2213    /// The same change in `DatagramHeader::encode`:
2214    ///
2215    /// ```text
2216    /// assertion `left == right` failed: the encoder must produce the datagram the decoder accepted for status 0x3
2217    ///   left: [32, 1, 0, 0, 128, 0]
2218    ///  right: [32, 1, 0, 0, 128, 3]
2219    /// ```
2220    ///
2221    /// The decoder drifting away from `ALL` — adding `0x2` to
2222    /// `ObjectStatus::from_u64`, so a code the draft does not assign starts
2223    /// decoding:
2224    ///
2225    /// ```text
2226    /// subgroup read_object accepted status 0x2, which the draft does not assign
2227    /// ```
2228    ///
2229    /// # The encode-side refusal is a type, not an assertion
2230    ///
2231    /// Once `object_status` is typed there is no runtime path that offers the
2232    /// encoder a `0x2`, so no test here can watch one be refused. Reverting
2233    /// `DatagramHeader::object_status` to `Option<u8>` with an `unwrap_or(0)`
2234    /// encoder does not make this test fail — it makes it stop compiling,
2235    /// which is the guarantee:
2236    ///
2237    /// ```text
2238    /// error[E0308]: mismatched types
2239    ///     = note: expected enum `Option<u8>`
2240    ///                found enum `Option<draft17::types::ObjectStatus>`
2241    /// ```
2242    #[test]
2243    fn the_encoder_writes_exactly_the_frames_the_decoder_accepts() {
2244        for code in 0x00u64..=0x3f {
2245            let assigned = ObjectStatus::ALL.iter().copied().find(|s| s.as_u64() == code);
2246
2247            let stream = subgroup_status_stream(code);
2248            let mut cursor: &[u8] = &stream;
2249            let header = SubgroupHeader::decode(&mut cursor).unwrap();
2250            let objects = cursor;
2251            let read = SubgroupObjectReader::new(&header).read_object(&mut { objects });
2252            let meta = SubgroupObjectReader::new(&header).read_object_meta(&mut { objects });
2253
2254            let datagram = status_datagram(code);
2255            let decoded = DatagramHeader::decode(&mut &datagram[..]);
2256
2257            match assigned {
2258                Some(status) => {
2259                    let object = read.unwrap_or_else(|e| {
2260                        panic!(
2261                            "read_object refused status {code:#x}, which the draft assigns: {e:?}"
2262                        )
2263                    });
2264                    assert_eq!(object.object_status, Some(status));
2265                    assert_eq!(meta.unwrap().status, Some(code));
2266                    assert_eq!(decoded.unwrap().object_status, Some(status));
2267
2268                    let mut written = Vec::new();
2269                    header.encode(&mut written);
2270                    SubgroupObjectReader::new(&header)
2271                        .write_object(&status_object(Some(status)), &mut written)
2272                        .unwrap();
2273                    assert_eq!(
2274                        written, stream,
2275                        "the encoder must produce the frame the decoder accepted for status {code:#x}"
2276                    );
2277
2278                    let mut written = Vec::new();
2279                    status_datagram_header(Some(status)).encode(&mut written);
2280                    assert_eq!(
2281                        written, datagram,
2282                        "the encoder must produce the datagram the decoder accepted for status {code:#x}"
2283                    );
2284                }
2285                None => {
2286                    for (site, result) in [
2287                        ("subgroup read_object", read.map(|_| ())),
2288                        ("subgroup read_object_meta", meta.map(|_| ())),
2289                        ("status datagram", decoded.map(|_| ())),
2290                    ] {
2291                        match result {
2292                            Ok(()) => panic!(
2293                                "{site} accepted status {code:#x}, which the draft does not assign"
2294                            ),
2295                            Err(error) => assert!(
2296                                matches!(error, CodecError::InvalidField),
2297                                "{site} refused status {code:#x} with {error:?}, not InvalidField"
2298                            ),
2299                        }
2300                    }
2301                }
2302            }
2303        }
2304    }
2305}