Skip to main content

srt_runtime/packet/
control.rs

1//! SRT control packet dispatch — `draft-sharabayko-srt-01` §3.2, Figure 4,
2//! Table 1.
3//!
4//! ```text
5//! word0  1|         Control Type (15)   |          Subtype (16)         |
6//! word1                   Type-specific Information (32)
7//! word2                          Timestamp (32)
8//! word3                    Destination Socket ID (32)
9//! rest                              CIF (variable, per Control Type)
10//! ```
11//!
12//! `Subtype` is `0x0` for every Control Type in Table 1 except
13//! `User-Defined Type` (`0x7FFF`), where it carries `SRT_CMD_KMREQ` /
14//! `SRT_CMD_KMRSP` (Table 5) when the CIF is a Key Material message (§3.2.2).
15//! `Subtype` and the `Type-specific Information` word (where a given packet
16//! type does not use it) are validated as reserved-must-be-zero and are not
17//! stored in the typed per-type structs — see the crate root's reserved-bit
18//! policy.
19
20use super::ack::AckPacket;
21use super::handshake::HandshakePacket;
22use super::misc::{
23    AckAckPacket, CongestionWarningPacket, DropReqPacket, KeepAlivePacket, PeerErrorPacket,
24    ShutdownPacket,
25};
26use super::nak::NakPacket;
27use super::number::{AckNumber, SocketId, SrtTimestamp};
28use super::{Error, Result, SRT_HEADER_LEN, put_be32};
29use broadcast_core::error::ReservedBits;
30use broadcast_core::len::{need_in, need_out};
31
32/// `Control Type` wire values (`draft-sharabayko-srt-01` §3.2, Table 1).
33/// Crate-private: they back [`ControlType::from_bits`]/[`ControlType::to_bits`],
34/// and [`ControlType`] is how a caller names a control type.
35pub(crate) const CONTROL_TYPE_HANDSHAKE: u16 = 0x0000;
36/// Keep-Alive (§3.2.3).
37pub(crate) const CONTROL_TYPE_KEEPALIVE: u16 = 0x0001;
38/// ACK (§3.2.4).
39pub(crate) const CONTROL_TYPE_ACK: u16 = 0x0002;
40/// NAK / Loss Report (§3.2.5).
41pub(crate) const CONTROL_TYPE_NAK: u16 = 0x0003;
42/// Congestion Warning (§3.2.6).
43pub(crate) const CONTROL_TYPE_CONGESTION_WARNING: u16 = 0x0004;
44/// Shutdown (§3.2.7).
45pub(crate) const CONTROL_TYPE_SHUTDOWN: u16 = 0x0005;
46/// ACKACK (§3.2.8).
47pub(crate) const CONTROL_TYPE_ACKACK: u16 = 0x0006;
48/// Message Drop Request (§3.2.9).
49pub(crate) const CONTROL_TYPE_DROPREQ: u16 = 0x0007;
50/// Peer Error (§3.2.10).
51pub(crate) const CONTROL_TYPE_PEERERROR: u16 = 0x0008;
52/// User-Defined Type (reserved value; also carries the Key Material message
53/// per §3.2.2 via `Subtype` `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP`).
54pub(crate) const CONTROL_TYPE_USER_DEFINED: u16 = 0x7FFF;
55
56/// The `Control Type` field (`draft-sharabayko-srt-01` §3.2, Table 1) — 15
57/// bits.
58#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
59#[cfg_attr(feature = "serde", derive(serde::Serialize))]
60#[non_exhaustive]
61pub enum ControlType {
62    /// `0x0000` — Handshake (§3.2.1).
63    Handshake,
64    /// `0x0001` — Keep-Alive (§3.2.3).
65    KeepAlive,
66    /// `0x0002` — ACK (§3.2.4).
67    Ack,
68    /// `0x0003` — NAK / Loss Report (§3.2.5).
69    Nak,
70    /// `0x0004` — Congestion Warning (§3.2.6).
71    CongestionWarning,
72    /// `0x0005` — Shutdown (§3.2.7).
73    Shutdown,
74    /// `0x0006` — ACKACK (§3.2.8).
75    AckAck,
76    /// `0x0007` — Message Drop Request (§3.2.9).
77    DropReq,
78    /// `0x0008` — Peer Error (§3.2.10).
79    PeerError,
80    /// `0x7FFF` — User-Defined Type (also the Key Material control-packet
81    /// delivery form, §3.2.2).
82    UserDefined,
83    /// A Control Type value Table 1 does not define.
84    Reserved(u16),
85}
86
87impl ControlType {
88    /// Decode a 15-bit `Control Type` value.
89    pub fn from_bits(v: u16) -> Self {
90        match v {
91            CONTROL_TYPE_HANDSHAKE => ControlType::Handshake,
92            CONTROL_TYPE_KEEPALIVE => ControlType::KeepAlive,
93            CONTROL_TYPE_ACK => ControlType::Ack,
94            CONTROL_TYPE_NAK => ControlType::Nak,
95            CONTROL_TYPE_CONGESTION_WARNING => ControlType::CongestionWarning,
96            CONTROL_TYPE_SHUTDOWN => ControlType::Shutdown,
97            CONTROL_TYPE_ACKACK => ControlType::AckAck,
98            CONTROL_TYPE_DROPREQ => ControlType::DropReq,
99            CONTROL_TYPE_PEERERROR => ControlType::PeerError,
100            CONTROL_TYPE_USER_DEFINED => ControlType::UserDefined,
101            other => ControlType::Reserved(other),
102        }
103    }
104
105    /// The wire value.
106    pub fn to_bits(self) -> u16 {
107        match self {
108            ControlType::Handshake => CONTROL_TYPE_HANDSHAKE,
109            ControlType::KeepAlive => CONTROL_TYPE_KEEPALIVE,
110            ControlType::Ack => CONTROL_TYPE_ACK,
111            ControlType::Nak => CONTROL_TYPE_NAK,
112            ControlType::CongestionWarning => CONTROL_TYPE_CONGESTION_WARNING,
113            ControlType::Shutdown => CONTROL_TYPE_SHUTDOWN,
114            ControlType::AckAck => CONTROL_TYPE_ACKACK,
115            ControlType::DropReq => CONTROL_TYPE_DROPREQ,
116            ControlType::PeerError => CONTROL_TYPE_PEERERROR,
117            ControlType::UserDefined => CONTROL_TYPE_USER_DEFINED,
118            ControlType::Reserved(v) => v,
119        }
120    }
121
122    /// Spec label.
123    pub fn name(&self) -> &'static str {
124        match self {
125            ControlType::Handshake => "handshake",
126            ControlType::KeepAlive => "keep-alive",
127            ControlType::Ack => "ACK",
128            ControlType::Nak => "NAK",
129            ControlType::CongestionWarning => "congestion warning",
130            ControlType::Shutdown => "shutdown",
131            ControlType::AckAck => "ACKACK",
132            ControlType::DropReq => "message drop request",
133            ControlType::PeerError => "peer error",
134            ControlType::UserDefined => "user-defined",
135            ControlType::Reserved(_) => "reserved",
136        }
137    }
138}
139
140broadcast_core::impl_spec_display!(ControlType, Reserved);
141
142/// A Control Type = User-Defined (`0x7FFF`) packet, or a Control Type not
143/// defined by Table 1. The CIF is genuinely opaque here — the only defined
144/// use is the Key Material message (§3.2.2) via `Subtype`
145/// `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP` — see [`Self::as_key_material`].
146#[derive(Debug, Clone, PartialEq)]
147#[cfg_attr(feature = "serde", derive(serde::Serialize))]
148pub struct UserDefinedPacket<'a> {
149    /// The raw 15-bit Control Type value.
150    pub control_type: u16,
151    /// The 16-bit Subtype — `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP` when the CIF is
152    /// Key Material (Table 5), otherwise vendor-defined.
153    pub subtype: u16,
154    /// The header `Type-specific Information` word.
155    pub type_specific_info: u32,
156    /// Timestamp (§3).
157    pub timestamp: SrtTimestamp,
158    /// Destination Socket ID (§3).
159    pub dest_socket_id: SocketId,
160    /// The raw CIF bytes.
161    pub cif: &'a [u8],
162}
163
164impl<'a> UserDefinedPacket<'a> {
165    /// Attempt to decode [`Self::cif`] as a Key Material message (§3.2.2).
166    /// Valid regardless of [`Self::subtype`] — callers that care should check
167    /// `subtype` against `SRT_CMD_KMREQ`/`SRT_CMD_KMRSP` (Table 5) first.
168    pub fn as_key_material(&self) -> Result<super::KeyMaterial<'a>> {
169        super::KeyMaterial::parse(self.cif)
170    }
171}
172
173/// An SRT control packet (`draft-sharabayko-srt-01` §3.2).
174#[derive(Debug, Clone, PartialEq)]
175#[cfg_attr(feature = "serde", derive(serde::Serialize))]
176#[non_exhaustive]
177pub enum ControlPacket<'a> {
178    /// Handshake (§3.2.1).
179    Handshake(HandshakePacket<'a>),
180    /// Keep-Alive (§3.2.3).
181    KeepAlive(KeepAlivePacket),
182    /// ACK (§3.2.4).
183    Ack(AckPacket),
184    /// NAK / Loss Report (§3.2.5).
185    Nak(NakPacket),
186    /// Congestion Warning (§3.2.6).
187    CongestionWarning(CongestionWarningPacket),
188    /// Shutdown (§3.2.7).
189    Shutdown(ShutdownPacket),
190    /// ACKACK (§3.2.8).
191    AckAck(AckAckPacket),
192    /// Message Drop Request (§3.2.9).
193    DropReq(DropReqPacket),
194    /// Peer Error (§3.2.10).
195    PeerError(PeerErrorPacket),
196    /// User-Defined Type, or a Control Type Table 1 does not define.
197    UserDefined(UserDefinedPacket<'a>),
198}
199
200fn check_reserved_u16(what: &'static str, v: u16) -> Result<()> {
201    if v != 0 {
202        return Err(Error::ReservedBits(ReservedBits::new(
203            what,
204            0,
205            u64::from(v),
206        )));
207    }
208    Ok(())
209}
210
211fn check_reserved_u32(what: &'static str, v: u32) -> Result<()> {
212    if v != 0 {
213        return Err(Error::ReservedBits(ReservedBits::new(
214            what,
215            0,
216            u64::from(v),
217        )));
218    }
219    Ok(())
220}
221
222/// Bytes a real SRT peer appends to a control packet type whose CIF the spec
223/// documents as absent (Keep-Alive §3.2.3, Congestion Warning §3.2.6, Shutdown
224/// §3.2.7, ACKACK §3.2.8, Peer Error §3.2.10): four zero bytes. Confirmed
225/// against a real `srt-live-transmit` 1.5.5 KEEPALIVE/ACKACK capture
226/// (`../fixtures/srt/libsrt-*.bin`); the other types of the family were not
227/// captured and are read the same way without a recorded observation.
228const LIBSRT_CIF_PAD_LEN: usize = 4;
229
230/// Shift, mask and bit width of the `Control Type` field of the first header
231/// word, and the mask of the `Subtype` field below it (§3.2, Figure 2).
232const CONTROL_TYPE_SHIFT: u32 = 16;
233const CONTROL_TYPE_MASK: u32 = 0x7FFF;
234const CONTROL_TYPE_BITS: u32 = 15;
235const SUBTYPE_MASK: u32 = 0xFFFF;
236
237/// Accept either the pure-spec empty CIF or libsrt's 4-byte zero pad (see
238/// [`LIBSRT_CIF_PAD_LEN`]); reject anything else. A non-zero 4-byte value is
239/// rejected the same way a defined reserved field is (`ReservedFieldNotZero`)
240/// — nothing defines those bits, so a peer setting them to something else is
241/// not a shape this crate recognizes. Returns `true` if the 4-byte pad was
242/// present, `false` for the empty CIF.
243fn check_no_cif_or_libsrt_pad(what: &'static str, cif: &[u8]) -> Result<bool> {
244    match cif.len() {
245        0 => Ok(false),
246        LIBSRT_CIF_PAD_LEN => {
247            let value = broadcast_core::wire::Reader::at(cif, 0).u32("value")?;
248            if value != 0 {
249                return Err(Error::ReservedBits(ReservedBits::new(
250                    what,
251                    0,
252                    u64::from(value),
253                )));
254            }
255            Ok(true)
256        }
257        extra => Err(Error::UnexpectedTrailingBytes { what, extra }),
258    }
259}
260
261impl<'a> ControlPacket<'a> {
262    /// Parse a control packet from `bytes` (the full SRT packet).
263    ///
264    /// # Errors
265    /// [`Error::BufferTooShort`] if shorter than the 16-byte header;
266    /// [`Error::WrongPacketKind`] if the `F` bit is clear (this is a data
267    /// packet); type-specific errors from the dispatched CIF parser.
268    pub fn parse(bytes: &'a [u8]) -> Result<Self> {
269        need_in(bytes, SRT_HEADER_LEN, "SRT control packet header")?;
270        let word0 = broadcast_core::wire::Reader::at(bytes, 0).u32("word0")?;
271        if word0 & super::F_BIT == 0 {
272            return Err(Error::WrongPacketKind {
273                expected: "control packet (F=1)",
274            });
275        }
276        let control_type_bits = ((word0 >> CONTROL_TYPE_SHIFT) & CONTROL_TYPE_MASK) as u16;
277        let subtype = (word0 & SUBTYPE_MASK) as u16;
278        let type_specific_info = broadcast_core::wire::Reader::at(bytes, super::TYPE_FIELD_OFFSET)
279            .u32("type_specific_info")?;
280        let timestamp = SrtTimestamp::from_wire(
281            broadcast_core::wire::Reader::at(bytes, super::TIMESTAMP_OFFSET).u32("timestamp")?,
282        );
283        let dest_socket_id = SocketId::from_wire(
284            broadcast_core::wire::Reader::at(bytes, super::DEST_SOCKET_ID_OFFSET)
285                .u32("SocketId")?,
286        );
287        let cif = &bytes[SRT_HEADER_LEN..];
288        let control_type = ControlType::from_bits(control_type_bits);
289
290        Ok(match control_type {
291            ControlType::Handshake => {
292                check_reserved_u16("Subtype", subtype)?;
293                check_reserved_u32("Type-specific Information", type_specific_info)?;
294                ControlPacket::Handshake(HandshakePacket::parse_cif(
295                    timestamp,
296                    dest_socket_id,
297                    cif,
298                )?)
299            }
300            ControlType::KeepAlive => {
301                check_reserved_u16("Subtype", subtype)?;
302                check_reserved_u32("Type-specific Information", type_specific_info)?;
303                let libsrt_pad = check_no_cif_or_libsrt_pad("keep-alive CIF", cif)?;
304                ControlPacket::KeepAlive(KeepAlivePacket {
305                    timestamp,
306                    dest_socket_id,
307                    libsrt_pad,
308                })
309            }
310            ControlType::Ack => {
311                check_reserved_u16("Subtype", subtype)?;
312                ControlPacket::Ack(AckPacket::parse_cif(
313                    type_specific_info,
314                    timestamp,
315                    dest_socket_id,
316                    cif,
317                )?)
318            }
319            ControlType::Nak => {
320                check_reserved_u16("Subtype", subtype)?;
321                check_reserved_u32("Type-specific Information", type_specific_info)?;
322                ControlPacket::Nak(NakPacket::parse_cif(timestamp, dest_socket_id, cif)?)
323            }
324            ControlType::CongestionWarning => {
325                check_reserved_u16("Subtype", subtype)?;
326                check_reserved_u32("Type-specific Information", type_specific_info)?;
327                let libsrt_pad = check_no_cif_or_libsrt_pad("congestion warning CIF", cif)?;
328                ControlPacket::CongestionWarning(CongestionWarningPacket {
329                    timestamp,
330                    dest_socket_id,
331                    libsrt_pad,
332                })
333            }
334            ControlType::Shutdown => {
335                check_reserved_u16("Subtype", subtype)?;
336                check_reserved_u32("Type-specific Information", type_specific_info)?;
337                let libsrt_pad = check_no_cif_or_libsrt_pad("shutdown CIF", cif)?;
338                ControlPacket::Shutdown(ShutdownPacket {
339                    timestamp,
340                    dest_socket_id,
341                    libsrt_pad,
342                })
343            }
344            ControlType::AckAck => {
345                check_reserved_u16("Subtype", subtype)?;
346                let libsrt_pad = check_no_cif_or_libsrt_pad("ACKACK CIF", cif)?;
347                ControlPacket::AckAck(AckAckPacket {
348                    ack_number: AckNumber::from_wire(type_specific_info),
349                    timestamp,
350                    dest_socket_id,
351                    libsrt_pad,
352                })
353            }
354            ControlType::DropReq => {
355                check_reserved_u16("Subtype", subtype)?;
356                ControlPacket::DropReq(DropReqPacket::parse_cif(
357                    type_specific_info,
358                    timestamp,
359                    dest_socket_id,
360                    cif,
361                )?)
362            }
363            ControlType::PeerError => {
364                check_reserved_u16("Subtype", subtype)?;
365                let libsrt_pad = check_no_cif_or_libsrt_pad("peer error CIF", cif)?;
366                ControlPacket::PeerError(PeerErrorPacket {
367                    error_code: type_specific_info,
368                    timestamp,
369                    dest_socket_id,
370                    libsrt_pad,
371                })
372            }
373            ControlType::UserDefined | ControlType::Reserved(_) => {
374                ControlPacket::UserDefined(UserDefinedPacket {
375                    control_type: control_type_bits,
376                    subtype,
377                    type_specific_info,
378                    timestamp,
379                    dest_socket_id,
380                    cif,
381                })
382            }
383        })
384    }
385
386    /// The `Control Type` this packet carries.
387    pub fn control_type(&self) -> ControlType {
388        match self {
389            ControlPacket::Handshake(_) => ControlType::Handshake,
390            ControlPacket::KeepAlive(_) => ControlType::KeepAlive,
391            ControlPacket::Ack(_) => ControlType::Ack,
392            ControlPacket::Nak(_) => ControlType::Nak,
393            ControlPacket::CongestionWarning(_) => ControlType::CongestionWarning,
394            ControlPacket::Shutdown(_) => ControlType::Shutdown,
395            ControlPacket::AckAck(_) => ControlType::AckAck,
396            ControlPacket::DropReq(_) => ControlType::DropReq,
397            ControlPacket::PeerError(_) => ControlType::PeerError,
398            ControlPacket::UserDefined(u) => ControlType::from_bits(u.control_type),
399        }
400    }
401
402    fn subtype(&self) -> u16 {
403        match self {
404            ControlPacket::UserDefined(u) => u.subtype,
405            _ => 0,
406        }
407    }
408
409    fn word1(&self) -> Result<u32> {
410        Ok(match self {
411            ControlPacket::Handshake(_)
412            | ControlPacket::KeepAlive(_)
413            | ControlPacket::Nak(_)
414            | ControlPacket::CongestionWarning(_)
415            | ControlPacket::Shutdown(_) => 0,
416            // An ACK's and an ACKACK's Acknowledgement Number fill their
417            // whole `Type-specific Information` word (§3.2.4, §3.2.8): every
418            // `u32` is a legal value, so nothing is bounded here (it was, to
419            // 31 bits, which made serialize refuse a packet parse accepted).
420            ControlPacket::Ack(a) => a.ack_number.value(),
421            ControlPacket::AckAck(a) => a.ack_number.value(),
422            ControlPacket::DropReq(d) => d.message_number.value(),
423            ControlPacket::PeerError(p) => p.error_code,
424            ControlPacket::UserDefined(u) => u.type_specific_info,
425        })
426    }
427
428    fn timestamp(&self) -> SrtTimestamp {
429        match self {
430            ControlPacket::Handshake(h) => h.timestamp,
431            ControlPacket::KeepAlive(k) => k.timestamp,
432            ControlPacket::Ack(a) => a.timestamp,
433            ControlPacket::Nak(n) => n.timestamp,
434            ControlPacket::CongestionWarning(c) => c.timestamp,
435            ControlPacket::Shutdown(s) => s.timestamp,
436            ControlPacket::AckAck(a) => a.timestamp,
437            ControlPacket::DropReq(d) => d.timestamp,
438            ControlPacket::PeerError(p) => p.timestamp,
439            ControlPacket::UserDefined(u) => u.timestamp,
440        }
441    }
442
443    fn dest_socket_id(&self) -> SocketId {
444        match self {
445            ControlPacket::Handshake(h) => h.dest_socket_id,
446            ControlPacket::KeepAlive(k) => k.dest_socket_id,
447            ControlPacket::Ack(a) => a.dest_socket_id,
448            ControlPacket::Nak(n) => n.dest_socket_id,
449            ControlPacket::CongestionWarning(c) => c.dest_socket_id,
450            ControlPacket::Shutdown(s) => s.dest_socket_id,
451            ControlPacket::AckAck(a) => a.dest_socket_id,
452            ControlPacket::DropReq(d) => d.dest_socket_id,
453            ControlPacket::PeerError(p) => p.dest_socket_id,
454            ControlPacket::UserDefined(u) => u.dest_socket_id,
455        }
456    }
457
458    fn cif_len(&self) -> usize {
459        match self {
460            ControlPacket::Handshake(h) => h.cif_len(),
461            // Emit libsrt's 4-byte zero pad (see `LIBSRT_CIF_PAD_LEN`) when
462            // requested, or empty CIF otherwise, so packets round-trip
463            // byte-identically regardless of which spec-legal shape they parsed.
464            ControlPacket::KeepAlive(k) => {
465                if k.libsrt_pad {
466                    LIBSRT_CIF_PAD_LEN
467                } else {
468                    0
469                }
470            }
471            ControlPacket::CongestionWarning(c) => {
472                if c.libsrt_pad {
473                    LIBSRT_CIF_PAD_LEN
474                } else {
475                    0
476                }
477            }
478            ControlPacket::Shutdown(s) => {
479                if s.libsrt_pad {
480                    LIBSRT_CIF_PAD_LEN
481                } else {
482                    0
483                }
484            }
485            ControlPacket::AckAck(a) => {
486                if a.libsrt_pad {
487                    LIBSRT_CIF_PAD_LEN
488                } else {
489                    0
490                }
491            }
492            ControlPacket::PeerError(p) => {
493                if p.libsrt_pad {
494                    LIBSRT_CIF_PAD_LEN
495                } else {
496                    0
497                }
498            }
499            ControlPacket::Ack(a) => a.cif_len(),
500            ControlPacket::Nak(n) => n.cif_len(),
501            ControlPacket::DropReq(d) => d.cif_len(),
502            ControlPacket::UserDefined(u) => u.cif.len(),
503        }
504    }
505
506    /// Number of bytes [`Self::serialize_into`] will write.
507    pub fn serialized_len(&self) -> usize {
508        SRT_HEADER_LEN + self.cif_len()
509    }
510
511    /// Serialize this control packet into `buf`.
512    pub fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
513        let len = self.serialized_len();
514        need_out(buf, len, "ControlPacket")?;
515        let control_type_bits = self.control_type().to_bits();
516        broadcast_core::len::fit_bits(
517            u64::from(control_type_bits),
518            CONTROL_TYPE_BITS,
519            "Control Type",
520        )?;
521        let word0 = super::F_BIT
522            | (u32::from(control_type_bits) << CONTROL_TYPE_SHIFT)
523            | u32::from(self.subtype());
524        put_be32(buf, 0, word0);
525        put_be32(buf, super::TYPE_FIELD_OFFSET, self.word1()?);
526        put_be32(buf, super::TIMESTAMP_OFFSET, self.timestamp().value());
527        put_be32(
528            buf,
529            super::DEST_SOCKET_ID_OFFSET,
530            self.dest_socket_id().value(),
531        );
532        let cif = &mut buf[SRT_HEADER_LEN..len];
533        match self {
534            ControlPacket::Handshake(h) => {
535                h.write_cif(cif)?;
536            }
537            ControlPacket::KeepAlive(_)
538            | ControlPacket::CongestionWarning(_)
539            | ControlPacket::Shutdown(_)
540            | ControlPacket::AckAck(_)
541            | ControlPacket::PeerError(_) => {
542                cif.fill(0);
543            }
544            ControlPacket::Ack(a) => {
545                a.write_cif(cif)?;
546            }
547            ControlPacket::Nak(n) => {
548                n.write_cif(cif);
549            }
550            ControlPacket::DropReq(d) => {
551                d.write_cif(cif)?;
552            }
553            ControlPacket::UserDefined(u) => {
554                cif.copy_from_slice(u.cif);
555            }
556        }
557        Ok(len)
558    }
559}
560
561impl<'a> broadcast_core::Parse<'a> for ControlPacket<'a> {
562    type Error = crate::Error;
563
564    fn parse(bytes: &'a [u8]) -> core::result::Result<Self, Self::Error> {
565        ControlPacket::parse(bytes)
566    }
567}
568
569impl broadcast_core::Serialize for ControlPacket<'_> {
570    type Error = crate::Error;
571
572    fn serialized_len(&self) -> usize {
573        ControlPacket::serialized_len(self)
574    }
575
576    fn serialize_into(&self, buf: &mut [u8]) -> core::result::Result<usize, Self::Error> {
577        ControlPacket::serialize_into(self, buf)
578    }
579}
580
581#[cfg(test)]
582mod tests {
583    use super::*;
584
585    #[test]
586    fn every_control_type_round_trips_its_table_1_wire_value() {
587        for (ty, value) in [
588            (ControlType::Handshake, 0x0000u16),
589            (ControlType::KeepAlive, 0x0001),
590            (ControlType::Ack, 0x0002),
591            (ControlType::Nak, 0x0003),
592            (ControlType::CongestionWarning, 0x0004),
593            (ControlType::Shutdown, 0x0005),
594            (ControlType::AckAck, 0x0006),
595            (ControlType::DropReq, 0x0007),
596            (ControlType::PeerError, 0x0008),
597            (ControlType::UserDefined, 0x7FFF),
598        ] {
599            assert_eq!(ty.to_bits(), value, "{}", ty.name());
600            assert_eq!(ControlType::from_bits(value), ty);
601        }
602    }
603
604    #[test]
605    fn a_control_type_off_table_1_is_reserved_and_keeps_its_value() {
606        // 0x0009..=0x7FFE are not in Table 1; the enum, not a raw constant,
607        // is the public way to name and recover them.
608        for value in [0x0009u16, 0x0010, 0x7FFE] {
609            assert_eq!(ControlType::from_bits(value), ControlType::Reserved(value));
610            assert_eq!(ControlType::from_bits(value).to_bits(), value);
611        }
612        assert_eq!(ControlType::Reserved(0x0010).name(), "reserved");
613    }
614}