Skip to main content

rtmp_runtime/
amf0.rs

1//! AMF0 (Action Message Format 0) value encoding/decoding, used by RTMP
2//! command and data messages.
3//!
4//! See `private/specs-verified/rtmp/rtmp-runtime/rtmp.md` §8 (AMF0) for the full transcription
5//! of `[AMF0]` (the companion spec this doc cites): §8.1 for the type marker
6//! table, §8.2 for the wire encoding of each data type needed by RTMP command
7//! messages.
8//!
9//! RTMP does not wrap command/data message bodies in AMF0's own
10//! `amf-packet` framing — a message body is simply a sequence of AMF0
11//! `value-type`s (marker + body) concatenated one after another (§8.2). This
12//! module implements that sequence-of-values contract via [`Amf0Value`]
13//! (single value parse/serialize) and [`Command`] (the `name` +
14//! `transaction_id` + `arguments` sequence carried by Command Messages,
15//! §7.1.1).
16//!
17//! # Scope
18//!
19//! Implements the markers actually needed to decode/encode the ingest
20//! command set (`connect`/`createStream`/`publish`/`_result`/`onStatus`/…):
21//! Number, Boolean, String, Object, Null, Undefined, ECMA Array, Strict
22//! Array, plus Date and Long String (trivial once String/Number exist).
23//!
24//! Out of scope, and rejected as [`RtmpError::UnsupportedAmf0Marker`] rather than
25//! panicking or silently misparsing: `movieclip-marker` (`0x04`, reserved),
26//! `reference-marker` (`0x07`), `unsupported-marker` (`0x0D`),
27//! `recordset-marker` (`0x0E`, reserved), `xml-document-marker` (`0x0F`),
28//! `typed-object-marker` (`0x10`), and `avmplus-object-marker` (`0x11`, the
29//! AMF3 switch — AMF3 itself, `[AMF3]`, is a separate spec and explicitly
30//! out of scope for this ingest engine per private/specs-verified/rtmp/rtmp-runtime/rtmp.md §8.3).
31//!
32//! [`Amf0Value`] is a data-carrying ADT (like `Fmt`/`MessageHeader`'s payload
33//! variants), not a closed label enum, so it is a `#204` `label_coverage`
34//! SKIP-list candidate rather than a `name()`/`impl_spec_display!` target
35//! (tracked for the crate's Task 10 label-coverage pass).
36
37use broadcast_common::error::BufferTooShort;
38use broadcast_common::{Parse, Serialize};
39
40use crate::RtmpError;
41use alloc::string::String;
42use alloc::vec::Vec;
43
44type Result<T> = core::result::Result<T, RtmpError>;
45
46/// AMF0 type markers (`[AMF0]` §2.1, private/specs-verified/rtmp/rtmp-runtime/rtmp.md §8.1) — 1 byte.
47pub mod marker {
48    /// Number (§2.2): `DOUBLE`, 8-byte big-endian IEEE-754.
49    pub const NUMBER: u8 = 0x00;
50    /// Boolean (§2.3): 1 byte, `0` = false, nonzero = true.
51    pub const BOOLEAN: u8 = 0x01;
52    /// String (§2.4): `U16` length + UTF-8 bytes.
53    pub const STRING: u8 = 0x02;
54    /// Object (§2.5): key/value pairs terminated by [`OBJECT_END`].
55    pub const OBJECT: u8 = 0x03;
56    /// null (§2.7): no payload.
57    pub const NULL: u8 = 0x05;
58    /// undefined (§2.8): no payload.
59    pub const UNDEFINED: u8 = 0x06;
60    /// ECMA Array (§2.10): `U32` associative-count + key/value pairs
61    /// terminated by [`OBJECT_END`].
62    pub const ECMA_ARRAY: u8 = 0x08;
63    /// Object End (§2.11): always preceded by an empty (`U16` = 0) key — the
64    /// 3-byte sequence `00 00 09`.
65    pub const OBJECT_END: u8 = 0x09;
66    /// Strict Array (§2.12): `U32` count + that many values, ordinal only.
67    pub const STRICT_ARRAY: u8 = 0x0A;
68    /// Date (§2.13): `DOUBLE` (ms since Unix epoch, UTC) + reserved `S16`
69    /// time zone (MUST be `0x0000`).
70    pub const DATE: u8 = 0x0B;
71    /// Long String (§2.14): `U32` length + UTF-8 bytes, for strings over
72    /// 65535 bytes.
73    pub const LONG_STRING: u8 = 0x0C;
74}
75
76/// Maximum AMF0 container nesting depth (Object/ECMA Array/Strict Array)
77/// [`Amf0Value::parse`] will descend into. Bounds recursion so a
78/// pathologically nested input returns [`RtmpError::Amf0DepthExceeded`] instead of
79/// overflowing the native call stack — the guard is checked on *entering*
80/// each nested container, so recursion never actually reaches an
81/// attacker-chosen depth, only this constant.
82pub const MAX_AMF0_DEPTH: usize = 32;
83
84/// Maximum number of AMF0 values one byte sequence may decode into, counting
85/// every value read at any nesting level (containers included). Bounds
86/// *width* the way [`MAX_AMF0_DEPTH`] bounds depth: millions of one-byte
87/// nulls inside a Strict Array, or three-byte empty-key pairs inside an
88/// Object, otherwise expand into millions of `Amf0Value`s (plus a `String`
89/// per key) from a single message. A decode past the limit returns
90/// [`RtmpError::Amf0TooManyValues`].
91pub const MAX_AMF0_VALUES: usize = 4096;
92
93/// Count one more decoded value against `values`, rejecting the sequence once
94/// it passes [`MAX_AMF0_VALUES`].
95fn count_value(values: &mut usize) -> Result<()> {
96    *values = values.checked_add(1).ok_or(RtmpError::Amf0TooManyValues {
97        max: MAX_AMF0_VALUES,
98    })?;
99    if *values > MAX_AMF0_VALUES {
100        return Err(RtmpError::Amf0TooManyValues {
101            max: MAX_AMF0_VALUES,
102        });
103    }
104    Ok(())
105}
106
107const MARKER_LEN: usize = 1;
108const NUMBER_LEN: usize = 8;
109const BOOLEAN_LEN: usize = 1;
110const U16_LEN: usize = 2;
111const U32_LEN: usize = 4;
112const DATE_RESERVED_LEN: usize = 2;
113/// `00 00 09`: empty key + [`marker::OBJECT_END`].
114const OBJECT_END_LEN: usize = 3;
115
116/// A single AMF0 value (`[AMF0]` §2, private/specs-verified/rtmp/rtmp-runtime/rtmp.md §8.2).
117///
118/// AMF3 (`avmplus-object-marker`, `0x11`) and the reserved/legacy markers
119/// (`movieclip`, `reference`, `unsupported`, `recordset`, `xml-document`,
120/// `typed-object`) are out of scope — see the module doc.
121///
122/// `#[non_exhaustive]`: this models a documented subset of `[AMF0]` §2's
123/// value types (see the module doc's Scope section); a future release may
124/// add a variant for one of the currently-`Unsupported` markers (e.g. a
125/// typed AMF3 bridge) without that being a breaking change for existing
126/// `match` callers.
127#[non_exhaustive]
128#[derive(Debug, Clone, PartialEq)]
129#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
130pub enum Amf0Value {
131    /// Number (§2.2).
132    Number(f64),
133    /// Boolean (§2.3).
134    Boolean(bool),
135    /// String (§2.4): `U16`-length UTF-8, at most 65535 bytes.
136    String(String),
137    /// Object (§2.5): ordered key/value pairs.
138    Object(Vec<(String, Amf0Value)>),
139    /// null (§2.7).
140    Null,
141    /// undefined (§2.8).
142    Undefined,
143    /// ECMA Array (§2.10): an associative array, encoded like Object plus a
144    /// leading (informational) `U32` count.
145    EcmaArray(Vec<(String, Amf0Value)>),
146    /// Strict Array (§2.12): an ordinal array of values.
147    StrictArray(Vec<Amf0Value>),
148    /// Date (§2.13): milliseconds since the Unix epoch, UTC.
149    Date(f64),
150    /// Long String (§2.14): `U32`-length UTF-8, for strings over 65535
151    /// bytes.
152    LongString(String),
153}
154
155fn buffer_too_short(need: usize, have: usize, what: &'static str) -> RtmpError {
156    RtmpError::BufferTooShort(BufferTooShort { need, have, what })
157}
158
159/// Read a `U16`-length-prefixed UTF-8 string from the front of `bytes`.
160/// Returns the decoded string and the total bytes consumed (`2 + len`).
161/// Used for both the String value body and Object/ECMA-Array keys, which
162/// share this exact encoding (§2.4 / §2.5).
163fn read_utf8_short(bytes: &[u8]) -> Result<(String, usize)> {
164    if bytes.len() < U16_LEN {
165        return Err(buffer_too_short(U16_LEN, bytes.len(), "AMF0 string length"));
166    }
167    let len = u16::from_be_bytes([bytes[0], bytes[1]]) as usize;
168    // `len` is at most `u16::MAX`, so `U16_LEN + len` cannot actually
169    // overflow `usize` on any real target, but guard it anyway (rather than
170    // a bare `+`) so this stays correct even on a hypothetical narrow
171    // `usize` platform, and matches the same guard on `read_utf8_long`
172    // below where the addend genuinely can overflow.
173    let total = U16_LEN.checked_add(len).ok_or(RtmpError::FieldOverflow(
174        broadcast_common::len::FieldOverflow {
175            field: "AMF0 string length",
176            value: u64::from(u16::MAX),
177            max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
178        },
179    ))?;
180    if bytes.len() < total {
181        return Err(buffer_too_short(total, bytes.len(), "AMF0 string"));
182    }
183    let s = String::from_utf8(bytes[U16_LEN..total].to_vec())
184        .map_err(|_| RtmpError::Amf0Utf8 { what: "string" })?;
185    Ok((s, total))
186}
187
188/// Read a `U32`-length-prefixed UTF-8 string (Long String, §2.14).
189fn read_utf8_long(bytes: &[u8]) -> Result<(String, usize)> {
190    if bytes.len() < U32_LEN {
191        return Err(buffer_too_short(
192            U32_LEN,
193            bytes.len(),
194            "AMF0 long string length",
195        ));
196    }
197    let len = u32::from_be_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) as usize;
198    // `len` can be up to `u32::MAX`: on a 32-bit target, `U32_LEN + len`
199    // wraps `usize` (e.g. `len == usize::MAX - 1`), which would make
200    // `bytes.len() < total` compare against a garbage-small wrapped value
201    // and misparse a length claim that should instead be rejected as too
202    // short. `checked_add` catches that instead of wrapping.
203    let total = U32_LEN.checked_add(len).ok_or(RtmpError::FieldOverflow(
204        broadcast_common::len::FieldOverflow {
205            field: "AMF0 long string length",
206            value: u64::from(u32::MAX),
207            max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
208        },
209    ))?;
210    if bytes.len() < total {
211        return Err(buffer_too_short(total, bytes.len(), "AMF0 long string"));
212    }
213    let s = String::from_utf8(bytes[U32_LEN..total].to_vec()).map_err(|_| RtmpError::Amf0Utf8 {
214        what: "long string",
215    })?;
216    Ok((s, total))
217}
218
219/// Parse the key/value pairs of an Object or ECMA Array body (§2.5/§2.10),
220/// starting right after any leading count field. Terminates on an empty key
221/// followed by [`marker::OBJECT_END`] (§2.11). `depth` is the nesting depth
222/// of the *values* in this container (already incremented past the
223/// container itself by the caller). `values` counts every value decoded so
224/// far, shared across the whole top-level sequence.
225fn parse_pairs(
226    bytes: &[u8],
227    depth: usize,
228    values: &mut usize,
229) -> Result<(Vec<(String, Amf0Value)>, usize)> {
230    let mut consumed = 0;
231    let mut pairs = Vec::new();
232    loop {
233        let (key, key_len) = read_utf8_short(&bytes[consumed..])?;
234        let after_key = consumed + key_len;
235        if key.is_empty() {
236            if bytes.len() < after_key + MARKER_LEN {
237                return Err(buffer_too_short(
238                    after_key + MARKER_LEN,
239                    bytes.len(),
240                    "amf0 object-end marker",
241                ));
242            }
243            if bytes[after_key] == marker::OBJECT_END {
244                return Ok((pairs, after_key + MARKER_LEN));
245            }
246        }
247        let (value, value_len) = parse_value(&bytes[after_key..], depth, values)?;
248        pairs.push((key, value));
249        consumed = after_key
250            .checked_add(value_len)
251            .ok_or(RtmpError::FieldOverflow(
252                broadcast_common::len::FieldOverflow {
253                    field: "AMF0 object pair length",
254                    value: u64::from(u32::try_from(after_key).unwrap_or(u32::MAX))
255                        + u64::from(u32::try_from(value_len).unwrap_or(u32::MAX)),
256                    max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
257                },
258            ))?;
259    }
260}
261
262/// Parse one AMF0 value (marker + body) from the front of `bytes`, ignoring
263/// any surplus trailing bytes, and return it with the number of bytes its
264/// encoding occupied. That count comes from the parser itself, so a caller
265/// walking a sequence of values advances by what was actually read rather
266/// than by a re-serialized length, which only agrees while every encoding is
267/// canonical. `depth` counts container nesting already
268/// entered (0 at the top level); checked *before* descending into a nested
269/// Object/ECMA-Array/Strict-Array so recursion is bounded by
270/// [`MAX_AMF0_DEPTH`] regardless of how deeply the input is (adversarially)
271/// nested. `values` counts every value decoded across the whole top-level
272/// sequence, bounded by [`MAX_AMF0_VALUES`].
273fn parse_value(bytes: &[u8], depth: usize, values: &mut usize) -> Result<(Amf0Value, usize)> {
274    if bytes.is_empty() {
275        return Err(buffer_too_short(MARKER_LEN, 0, "amf0 value marker"));
276    }
277    count_value(values)?;
278    let body = &bytes[MARKER_LEN..];
279    match bytes[0] {
280        marker::NUMBER => {
281            if body.len() < NUMBER_LEN {
282                return Err(buffer_too_short(NUMBER_LEN, body.len(), "amf0 number"));
283            }
284            let mut b = [0u8; NUMBER_LEN];
285            b.copy_from_slice(&body[..NUMBER_LEN]);
286            Ok((
287                Amf0Value::Number(f64::from_be_bytes(b)),
288                MARKER_LEN + NUMBER_LEN,
289            ))
290        }
291        marker::BOOLEAN => {
292            if body.is_empty() {
293                return Err(buffer_too_short(BOOLEAN_LEN, 0, "amf0 boolean"));
294            }
295            Ok((Amf0Value::Boolean(body[0] != 0), MARKER_LEN + BOOLEAN_LEN))
296        }
297        marker::STRING => {
298            let (s, len) = read_utf8_short(body)?;
299            Ok((Amf0Value::String(s), MARKER_LEN + len))
300        }
301        marker::OBJECT => {
302            if depth >= MAX_AMF0_DEPTH {
303                return Err(RtmpError::Amf0DepthExceeded {
304                    max: MAX_AMF0_DEPTH,
305                });
306            }
307            let (pairs, len) = parse_pairs(body, depth + 1, values)?;
308            Ok((Amf0Value::Object(pairs), MARKER_LEN + len))
309        }
310        marker::NULL => Ok((Amf0Value::Null, MARKER_LEN)),
311        marker::UNDEFINED => Ok((Amf0Value::Undefined, MARKER_LEN)),
312        marker::ECMA_ARRAY => {
313            if depth >= MAX_AMF0_DEPTH {
314                return Err(RtmpError::Amf0DepthExceeded {
315                    max: MAX_AMF0_DEPTH,
316                });
317            }
318            if body.len() < U32_LEN {
319                return Err(buffer_too_short(
320                    U32_LEN,
321                    body.len(),
322                    "amf0 ecma array count",
323                ));
324            }
325            // The associative-count is informational only (§2.10); the
326            // object-end terminator is authoritative, so it is read and
327            // discarded rather than cross-checked against the parsed pair
328            // count.
329            let (pairs, len) = parse_pairs(&body[U32_LEN..], depth + 1, values)?;
330            Ok((Amf0Value::EcmaArray(pairs), MARKER_LEN + U32_LEN + len))
331        }
332        marker::STRICT_ARRAY => {
333            if depth >= MAX_AMF0_DEPTH {
334                return Err(RtmpError::Amf0DepthExceeded {
335                    max: MAX_AMF0_DEPTH,
336                });
337            }
338            if body.len() < U32_LEN {
339                return Err(buffer_too_short(
340                    U32_LEN,
341                    body.len(),
342                    "amf0 strict array count",
343                ));
344            }
345            let count = u32::from_be_bytes([body[0], body[1], body[2], body[3]]);
346            let mut rest = &body[U32_LEN..];
347            let mut elements = Vec::new();
348            for _ in 0..count {
349                let (value, consumed) = parse_value(rest, depth + 1, values)?;
350                elements.push(value);
351                rest = rest.get(consumed..).ok_or(RtmpError::FieldOverflow(
352                    broadcast_common::len::FieldOverflow {
353                        field: "AMF0 strict array element length",
354                        value: u64::try_from(consumed).unwrap_or(u64::MAX),
355                        max: u64::try_from(rest.len()).unwrap_or(u64::MAX),
356                    },
357                ))?;
358            }
359            let elements_len =
360                body[U32_LEN..]
361                    .len()
362                    .checked_sub(rest.len())
363                    .ok_or(RtmpError::Malformed {
364                        what: "AMF0 strict array body",
365                    })?;
366            Ok((
367                Amf0Value::StrictArray(elements),
368                MARKER_LEN + U32_LEN + elements_len,
369            ))
370        }
371        marker::DATE => {
372            if body.len() < NUMBER_LEN + DATE_RESERVED_LEN {
373                return Err(buffer_too_short(
374                    NUMBER_LEN + DATE_RESERVED_LEN,
375                    body.len(),
376                    "amf0 date",
377                ));
378            }
379            let mut b = [0u8; NUMBER_LEN];
380            b.copy_from_slice(&body[..NUMBER_LEN]);
381            let tz = u16::from_be_bytes([body[NUMBER_LEN], body[NUMBER_LEN + 1]]);
382            if tz != 0 {
383                return Err(RtmpError::Amf0DateTimeZone { value: tz });
384            }
385            Ok((
386                Amf0Value::Date(f64::from_be_bytes(b)),
387                MARKER_LEN + NUMBER_LEN + DATE_RESERVED_LEN,
388            ))
389        }
390        marker::LONG_STRING => {
391            let (s, len) = read_utf8_long(body)?;
392            Ok((Amf0Value::LongString(s), MARKER_LEN + len))
393        }
394        other => Err(RtmpError::UnsupportedAmf0Marker { marker: other }),
395    }
396}
397
398/// The `FieldOverflow` for a value sequence whose total length does not fit a
399/// `usize`: the sum of real element lengths against the addressable maximum.
400fn sequence_length_overflow(so_far: usize, next: usize) -> RtmpError {
401    RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
402        field: "amf0 value sequence length",
403        value: u64::from(u32::try_from(so_far).unwrap_or(u32::MAX))
404            + u64::from(u32::try_from(next).unwrap_or(u32::MAX)),
405        max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
406    })
407}
408
409fn pairs_body_len(pairs: &[(String, Amf0Value)]) -> usize {
410    pairs
411        .iter()
412        .map(|(k, v)| U16_LEN + k.len() + v.serialized_len())
413        .sum::<usize>()
414        + OBJECT_END_LEN
415}
416
417fn write_pairs(pairs: &[(String, Amf0Value)], buf: &mut [u8]) -> Result<usize> {
418    let mut offset = 0;
419    for (k, v) in pairs {
420        let key_total = U16_LEN + k.len();
421        if buf.len() < offset + key_total {
422            return Err(buffer_too_short(
423                offset + key_total,
424                buf.len(),
425                "amf0 object key output",
426            ));
427        }
428        let key_len = broadcast_common::len::fit_u16(k.len(), "amf0 object key length")?;
429        buf[offset..offset + U16_LEN].copy_from_slice(&key_len.to_be_bytes());
430        buf[offset + U16_LEN..offset + key_total].copy_from_slice(k.as_bytes());
431        offset += key_total;
432        offset += v.serialize_into(&mut buf[offset..])?;
433    }
434    if buf.len() < offset + OBJECT_END_LEN {
435        return Err(buffer_too_short(
436            offset + OBJECT_END_LEN,
437            buf.len(),
438            "amf0 object-end output",
439        ));
440    }
441    buf[offset] = 0;
442    buf[offset + 1] = 0;
443    buf[offset + 2] = marker::OBJECT_END;
444    Ok(offset + OBJECT_END_LEN)
445}
446
447impl<'a> Parse<'a> for Amf0Value {
448    type Error = RtmpError;
449
450    fn parse(bytes: &'a [u8]) -> Result<Self> {
451        let mut values = 0usize;
452        let (value, _) = parse_value(bytes, 0, &mut values)?;
453        Ok(value)
454    }
455}
456
457impl Serialize for Amf0Value {
458    type Error = RtmpError;
459
460    fn serialized_len(&self) -> usize {
461        MARKER_LEN
462            + match self {
463                Amf0Value::Number(_) | Amf0Value::Date(_) => NUMBER_LEN,
464                Amf0Value::Boolean(_) => BOOLEAN_LEN,
465                Amf0Value::String(s) => U16_LEN + s.len(),
466                Amf0Value::LongString(s) => U32_LEN + s.len(),
467                Amf0Value::Object(pairs) => pairs_body_len(pairs),
468                Amf0Value::Null | Amf0Value::Undefined => 0,
469                Amf0Value::EcmaArray(pairs) => U32_LEN + pairs_body_len(pairs),
470                Amf0Value::StrictArray(values) => {
471                    U32_LEN + values.iter().map(Serialize::serialized_len).sum::<usize>()
472                }
473            }
474            + match self {
475                Amf0Value::Date(_) => DATE_RESERVED_LEN,
476                _ => 0,
477            }
478    }
479
480    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize> {
481        let written = self.serialized_len();
482        if buf.len() < written {
483            return Err(buffer_too_short(written, buf.len(), "amf0 value output"));
484        }
485        let (marker_byte, body) = buf[..written].split_at_mut(MARKER_LEN);
486        match self {
487            Amf0Value::Number(v) => {
488                marker_byte[0] = marker::NUMBER;
489                body[..NUMBER_LEN].copy_from_slice(&v.to_be_bytes());
490            }
491            Amf0Value::Boolean(v) => {
492                marker_byte[0] = marker::BOOLEAN;
493                body[0] = u8::from(*v);
494            }
495            Amf0Value::String(s) => {
496                if s.len() > usize::from(u16::MAX) {
497                    return Err(RtmpError::Amf0StringTooLong { len: s.len() });
498                }
499                marker_byte[0] = marker::STRING;
500                body[..U16_LEN].copy_from_slice(&(s.len() as u16).to_be_bytes());
501                body[U16_LEN..].copy_from_slice(s.as_bytes());
502            }
503            Amf0Value::LongString(s) => {
504                marker_byte[0] = marker::LONG_STRING;
505                let len = broadcast_common::len::fit_u32(s.len(), "amf0 long string length")?;
506                body[..U32_LEN].copy_from_slice(&len.to_be_bytes());
507                body[U32_LEN..].copy_from_slice(s.as_bytes());
508            }
509            Amf0Value::Object(pairs) => {
510                marker_byte[0] = marker::OBJECT;
511                write_pairs(pairs, body)?;
512            }
513            Amf0Value::Null => marker_byte[0] = marker::NULL,
514            Amf0Value::Undefined => marker_byte[0] = marker::UNDEFINED,
515            Amf0Value::EcmaArray(pairs) => {
516                marker_byte[0] = marker::ECMA_ARRAY;
517                let count = broadcast_common::len::fit_u32(pairs.len(), "amf0 ECMA array count")?;
518                body[..U32_LEN].copy_from_slice(&count.to_be_bytes());
519                write_pairs(pairs, &mut body[U32_LEN..])?;
520            }
521            Amf0Value::StrictArray(values) => {
522                marker_byte[0] = marker::STRICT_ARRAY;
523                let count =
524                    broadcast_common::len::fit_u32(values.len(), "amf0 strict array count")?;
525                body[..U32_LEN].copy_from_slice(&count.to_be_bytes());
526                let mut offset = U32_LEN;
527                for v in values {
528                    offset += v.serialize_into(&mut body[offset..])?;
529                }
530            }
531            Amf0Value::Date(v) => {
532                marker_byte[0] = marker::DATE;
533                body[..NUMBER_LEN].copy_from_slice(&v.to_be_bytes());
534                body[NUMBER_LEN..NUMBER_LEN + DATE_RESERVED_LEN].copy_from_slice(&[0, 0]);
535            }
536        }
537        Ok(written)
538    }
539}
540
541/// An RTMP Command Message body (§7.1.1): `name` (AMF0 String) + AMF0
542/// `transaction_id` (AMF0 Number) + zero or more argument values (typically
543/// a Command Object, then optional trailing arguments) — see private/specs-verified/rtmp/rtmp-runtime/rtmp.md
544/// §8.2's closing note and §6.1 (Command Message).
545///
546/// This is the message-body-level container: unlike [`Amf0Value`] it is not
547/// itself a single AMF0 `value-type`, so it uses inherent `parse`/`to_body`
548/// methods rather than the [`Parse`]/[`Serialize`] traits.
549#[derive(Debug, Clone, PartialEq)]
550#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
551pub struct Command {
552    /// The command name, e.g. `"connect"`, `"createStream"`, `"publish"`,
553    /// `"_result"`.
554    pub name: String,
555    /// The transaction id correlating a response to its request (`0` for
556    /// commands that expect no response, e.g. `onStatus`).
557    pub transaction_id: f64,
558    /// The remaining AMF0 values in the command body, in wire order
559    /// (conventionally: Command Object, then any further arguments).
560    pub arguments: Vec<Amf0Value>,
561}
562
563impl Command {
564    /// Parse a Command Message body: AMF0 String (`name`) + AMF0 Number
565    /// (`transaction_id`) + the remaining AMF0 values (`arguments`), read
566    /// until `payload` is exhausted.
567    ///
568    /// # Errors
569    /// [`RtmpError::CommandNameNotString`] if the first value is not a
570    /// String, [`RtmpError::CommandTransactionIdNotNumber`] if the second is
571    /// not a Number; the remaining variants are propagated from
572    /// [`Amf0Value::parse`].
573    pub fn parse(payload: &[u8]) -> Result<Self> {
574        let mut values = 0usize;
575        let (name_value, name_len) = parse_value(payload, 0, &mut values)?;
576        let mut offset = name_len;
577        let name = match name_value {
578            Amf0Value::String(s) => s,
579            value => return Err(RtmpError::CommandNameNotString { value }),
580        };
581
582        let (txn_value, txn_len) =
583            parse_value(payload.get(offset..).unwrap_or_default(), 0, &mut values)?;
584        offset = offset.checked_add(txn_len).ok_or(RtmpError::FieldOverflow(
585            broadcast_common::len::FieldOverflow {
586                field: "RTMP command transaction id offset",
587                value: u64::try_from(offset).unwrap_or(u64::MAX),
588                max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
589            },
590        ))?;
591        let transaction_id = match txn_value {
592            Amf0Value::Number(n) => n,
593            value => return Err(RtmpError::CommandTransactionIdNotNumber { value }),
594        };
595
596        let mut arguments = Vec::new();
597        while offset < payload.len() {
598            let (value, len) = parse_value(&payload[offset..], 0, &mut values)?;
599            offset = offset.checked_add(len).ok_or(RtmpError::FieldOverflow(
600                broadcast_common::len::FieldOverflow {
601                    field: "RTMP command argument offset",
602                    value: u64::try_from(offset).unwrap_or(u64::MAX),
603                    max: u64::try_from(usize::MAX).unwrap_or(u64::MAX),
604                },
605            ))?;
606            arguments.push(value);
607        }
608
609        Ok(Command {
610            name,
611            transaction_id,
612            arguments,
613        })
614    }
615
616    /// Serialize this command back to an AMF0 command payload: `name` +
617    /// `transaction_id` + `arguments`, in that order.
618    ///
619    /// # Errors
620    ///
621    /// [`RtmpError::FieldOverflow`] when any string, key or array exceeds the
622    /// AMF0 16/32-bit length prefix (a peer-chosen publish name echoed into an
623    /// `onStatus` description can reach this).
624    pub fn to_body(&self) -> Result<Vec<u8>> {
625        let mut out = Amf0Value::String(self.name.clone()).try_to_bytes()?;
626        out.extend(Amf0Value::Number(self.transaction_id).try_to_bytes()?);
627        for arg in &self.arguments {
628            out.extend(arg.try_to_bytes()?);
629        }
630        Ok(out)
631    }
632}
633
634/// Encode `values` in order as one AMF0 byte sequence: what a message body
635/// carrying several bare values is (`onMetaData` is a String followed by an
636/// ECMA Array, §2 of the AMF0 spec).
637///
638/// # Errors
639///
640/// [`RtmpError::FieldOverflow`] when a string, key or array exceeds its AMF0
641/// length prefix (see [`Amf0Value`]'s own serializer).
642pub fn amf0_values(values: &[Amf0Value]) -> Result<Vec<u8>> {
643    let len = values.iter().try_fold(0usize, |acc, value| {
644        let value_len = value.serialized_len();
645        acc.checked_add(value_len)
646            .ok_or_else(|| sequence_length_overflow(acc, value_len))
647    })?;
648    let mut out = alloc::vec![0u8; len];
649    let mut written = 0usize;
650    for value in values {
651        written += value.serialize_into(&mut out[written..])?;
652    }
653    Ok(out)
654}
655
656#[cfg(test)]
657mod tests {
658    use super::*;
659
660    fn round_trip(v: &Amf0Value) {
661        let bytes = v.try_to_bytes().unwrap();
662        assert_eq!(bytes.len(), v.serialized_len());
663        let parsed = Amf0Value::parse(&bytes).expect("parse");
664        assert_eq!(&parsed, v);
665        // parse -> serialize -> byte-identical
666        assert_eq!(parsed.try_to_bytes().unwrap(), bytes);
667    }
668
669    #[test]
670    fn a_value_sequence_encodes_each_value_in_order() {
671        let values = [
672            Amf0Value::String("onMetaData".to_string()),
673            Amf0Value::EcmaArray(vec![("duration".to_string(), Amf0Value::Number(1.5))]),
674        ];
675        let body = amf0_values(&values).expect("encode");
676        let mut expected = values[0].try_to_bytes().unwrap();
677        expected.extend(values[1].try_to_bytes().unwrap());
678        assert_eq!(body, expected);
679    }
680
681    /// #2761: the overflow error carried `value = u64::MAX, max = u64::MAX`,
682    /// telling a caller nothing. It now carries the real current length and
683    /// the addressable maximum.
684    #[test]
685    fn a_sequence_length_overflow_reports_the_real_lengths() {
686        let err = sequence_length_overflow(6, 8);
687        let RtmpError::FieldOverflow(overflow) = err else {
688            panic!("expected FieldOverflow, got {err:?}");
689        };
690        assert_eq!(overflow.value, 14);
691        assert_eq!(
692            overflow.max,
693            u64::try_from(usize::MAX).expect("usize fits u64 on every supported target")
694        );
695    }
696
697    /// #2761: `Command::parse` advanced by each parsed value's re-serialized
698    /// length. The parser now reports what it consumed, so a value whose
699    /// encoding is not its canonical form (here AMF0 permits any non-zero
700    /// Boolean byte, and `0x02` re-serializes as `0x01`) no longer shifts the
701    /// boundary of the following argument.
702    #[test]
703    fn command_argument_boundaries_come_from_the_parse_not_a_re_derived_length() {
704        let mut payload = Amf0Value::String("connect".to_string())
705            .try_to_bytes()
706            .unwrap();
707        payload.extend(Amf0Value::Number(1.0).try_to_bytes().unwrap());
708        for i in 0..8u8 {
709            payload.extend([marker::BOOLEAN, i]);
710        }
711
712        let command = Command::parse(&payload).expect("any boolean byte is legal AMF0");
713        assert_eq!(
714            command.arguments,
715            (0..8u8)
716                .map(|i| Amf0Value::Boolean(i != 0))
717                .collect::<Vec<_>>()
718        );
719    }
720
721    #[test]
722    fn number_round_trips() {
723        round_trip(&Amf0Value::Number(0.0));
724        round_trip(&Amf0Value::Number(-1.5));
725        round_trip(&Amf0Value::Number(1_000_000.25));
726    }
727
728    #[test]
729    fn boolean_round_trips() {
730        round_trip(&Amf0Value::Boolean(true));
731        round_trip(&Amf0Value::Boolean(false));
732    }
733
734    /// An Object key of 65 536 bytes cannot fit its 16-bit length prefix
735    /// (#1129): unfixed, `(k.len() as u16)` silently wrapped 65536 to 0
736    /// while the full key bytes were still written, misframing the object.
737    #[test]
738    fn object_oversized_key_length_errors() {
739        let key = "k".repeat(65536);
740        let value = Amf0Value::Object(vec![(key, Amf0Value::Null)]);
741        let err = value.try_to_bytes().unwrap_err();
742        assert!(
743            matches!(
744                err,
745                RtmpError::FieldOverflow(broadcast_common::len::FieldOverflow {
746                    field: "amf0 object key length",
747                    ..
748                })
749            ),
750            "expected FieldOverflow for amf0 object key length, got {err:?}"
751        );
752    }
753
754    /// The AMF0 String marker carries a 16-bit length prefix, so a longer
755    /// value is rejected rather than written with a wrapped length.
756    #[test]
757    fn string_beyond_the_16_bit_prefix_is_rejected() {
758        let value = Amf0Value::String("x".repeat(0x1_0000));
759        let err = value.try_to_bytes().unwrap_err();
760        assert!(
761            matches!(err, RtmpError::Amf0StringTooLong { len } if len == 0x1_0000),
762            "expected Amf0StringTooLong for a 65 536-byte string, got {err:?}"
763        );
764        let boundary = Amf0Value::String("x".repeat(usize::from(u16::MAX)));
765        round_trip(&boundary);
766    }
767
768    /// The boundary: exactly 65 535 bytes (u16::MAX) still round-trips.
769    #[test]
770    fn object_max_key_length_round_trips() {
771        let key = "k".repeat(65535);
772        round_trip(&Amf0Value::Object(vec![(key, Amf0Value::Null)]));
773    }
774
775    #[test]
776    fn string_round_trips_including_empty_and_multibyte() {
777        round_trip(&Amf0Value::String(String::new()));
778        round_trip(&Amf0Value::String("live".to_string()));
779        round_trip(&Amf0Value::String("héllo wörld 日本語".to_string()));
780    }
781
782    #[test]
783    fn null_and_undefined_round_trip() {
784        round_trip(&Amf0Value::Null);
785        round_trip(&Amf0Value::Undefined);
786    }
787
788    #[test]
789    fn date_round_trips() {
790        round_trip(&Amf0Value::Date(1_700_000_000_000.0));
791    }
792
793    #[test]
794    fn long_string_round_trips() {
795        round_trip(&Amf0Value::LongString("x".repeat(70_000)));
796    }
797
798    #[test]
799    fn object_round_trips_including_nested_object() {
800        round_trip(&Amf0Value::Object(vec![]));
801        round_trip(&Amf0Value::Object(vec![
802            ("app".to_string(), Amf0Value::String("live".to_string())),
803            ("audioSampleRate".to_string(), Amf0Value::Number(44100.0)),
804            ("live".to_string(), Amf0Value::Boolean(true)),
805        ]));
806        // Nested Object (the `connect` command object has string/number/
807        // boolean fields, and encoders may nest e.g. a capabilities object).
808        round_trip(&Amf0Value::Object(vec![(
809            "capabilities".to_string(),
810            Amf0Value::Object(vec![("videoCodecs".to_string(), Amf0Value::Number(252.0))]),
811        )]));
812    }
813
814    #[test]
815    fn ecma_array_round_trips() {
816        round_trip(&Amf0Value::EcmaArray(vec![]));
817        round_trip(&Amf0Value::EcmaArray(vec![
818            ("duration".to_string(), Amf0Value::Number(0.0)),
819            ("width".to_string(), Amf0Value::Number(1920.0)),
820        ]));
821    }
822
823    #[test]
824    fn strict_array_round_trips() {
825        round_trip(&Amf0Value::StrictArray(vec![]));
826        round_trip(&Amf0Value::StrictArray(vec![
827            Amf0Value::Number(1.0),
828            Amf0Value::String("two".to_string()),
829            Amf0Value::Boolean(false),
830            Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)]),
831        ]));
832    }
833
834    #[test]
835    fn ecma_array_count_is_informational_not_cross_checked() {
836        // A real encoder writes the true pair count, but §2.10 makes the
837        // object-end terminator authoritative — a lying count must still
838        // parse correctly off the terminator, not the count field.
839        let mut bytes = vec![marker::ECMA_ARRAY];
840        bytes.extend_from_slice(&999u32.to_be_bytes()); // lying count
841        bytes.extend_from_slice(&1u16.to_be_bytes());
842        bytes.extend_from_slice(b"k");
843        bytes.push(marker::NULL);
844        bytes.extend_from_slice(&[0, 0, marker::OBJECT_END]);
845
846        let parsed = Amf0Value::parse(&bytes).expect("parse");
847        assert_eq!(
848            parsed,
849            Amf0Value::EcmaArray(vec![("k".to_string(), Amf0Value::Null)])
850        );
851    }
852
853    #[test]
854    fn depth_guard_rejects_pathological_nesting_without_stack_overflow() {
855        // Build a deeply-nested Object payload by pure byte manipulation
856        // (no recursive construction/serialization of our own types), so
857        // the test itself can never stack-overflow regardless of the depth
858        // guard's correctness.
859        let mut inner = vec![marker::NULL];
860        for _ in 0..(MAX_AMF0_DEPTH * 4) {
861            let mut wrapped = vec![marker::OBJECT];
862            wrapped.extend_from_slice(&1u16.to_be_bytes());
863            wrapped.push(b'a');
864            wrapped.extend_from_slice(&inner);
865            wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
866            inner = wrapped;
867        }
868
869        let result = Amf0Value::parse(&inner);
870        assert!(matches!(
871            result,
872            Err(RtmpError::Amf0DepthExceeded { max }) if max == MAX_AMF0_DEPTH
873        ));
874    }
875
876    #[test]
877    fn depth_guard_allows_nesting_at_the_limit() {
878        let mut inner = vec![marker::NULL];
879        for _ in 0..(MAX_AMF0_DEPTH - 1) {
880            let mut wrapped = vec![marker::OBJECT];
881            wrapped.extend_from_slice(&1u16.to_be_bytes());
882            wrapped.push(b'a');
883            wrapped.extend_from_slice(&inner);
884            wrapped.extend_from_slice(&[0, 0, marker::OBJECT_END]);
885            inner = wrapped;
886        }
887        assert!(Amf0Value::parse(&inner).is_ok());
888    }
889
890    /// #2813: width was unbounded — an 8 MiB Strict Array of one-byte nulls
891    /// decoded into millions of `Amf0Value`s, and an Object of three-byte
892    /// empty-key pairs into millions of `(String, Amf0Value)` pairs. The
893    /// value counter now rejects the element that crosses
894    /// [`MAX_AMF0_VALUES`].
895    #[test]
896    fn value_count_guard_rejects_wide_containers() {
897        let count = u32::try_from(MAX_AMF0_VALUES + 1).expect("limit fits u32");
898        let mut bytes = vec![marker::STRICT_ARRAY];
899        bytes.extend_from_slice(&count.to_be_bytes());
900        bytes.extend(core::iter::repeat_n(marker::NULL, MAX_AMF0_VALUES + 1));
901
902        let result = Amf0Value::parse(&bytes);
903        assert!(matches!(
904            result,
905            Err(RtmpError::Amf0TooManyValues { max }) if max == MAX_AMF0_VALUES
906        ));
907    }
908
909    #[test]
910    fn value_count_guard_allows_a_container_at_the_limit() {
911        let count = u32::try_from(MAX_AMF0_VALUES - 1).expect("limit fits u32");
912        let mut bytes = vec![marker::STRICT_ARRAY];
913        bytes.extend_from_slice(&count.to_be_bytes());
914        bytes.extend(core::iter::repeat_n(marker::NULL, MAX_AMF0_VALUES - 1));
915
916        let parsed =
917            Amf0Value::parse(&bytes).expect("the array itself plus its elements is the limit");
918        assert_eq!(
919            parsed,
920            Amf0Value::StrictArray(vec![Amf0Value::Null; MAX_AMF0_VALUES - 1])
921        );
922    }
923
924    /// #2813: the counter spans the whole top-level value sequence, so a
925    /// Command Message cannot dodge it by spreading its values over several
926    /// arguments.
927    #[test]
928    fn command_parse_counts_values_across_every_argument() {
929        let mut payload = Amf0Value::String("connect".to_string())
930            .try_to_bytes()
931            .expect("encode name");
932        payload.extend(
933            Amf0Value::Number(1.0)
934                .try_to_bytes()
935                .expect("encode transaction id"),
936        );
937        payload.extend(core::iter::repeat_n(marker::NULL, MAX_AMF0_VALUES));
938
939        let result = Command::parse(&payload);
940        assert!(matches!(
941            result,
942            Err(RtmpError::Amf0TooManyValues { max }) if max == MAX_AMF0_VALUES
943        ));
944    }
945
946    #[test]
947    fn dropping_object_end_marker_is_rejected() {
948        // Mutation check: an Object with its `00 00 09` terminator dropped
949        // must fail to parse (BufferTooShort), not silently succeed.
950        let full = Amf0Value::Object(vec![("k".to_string(), Amf0Value::Null)])
951            .try_to_bytes()
952            .unwrap();
953        let truncated = &full[..full.len() - 3];
954        assert!(matches!(
955            Amf0Value::parse(truncated),
956            Err(RtmpError::BufferTooShort(..))
957        ));
958    }
959
960    #[test]
961    fn mis_sized_string_length_is_rejected() {
962        // Mutation check: claiming a longer string length than the buffer
963        // actually holds must fail (BufferTooShort), not read garbage.
964        let mut bytes = vec![marker::STRING];
965        bytes.extend_from_slice(&100u16.to_be_bytes()); // claims 100 bytes
966        bytes.extend_from_slice(b"short"); // only 5 present
967        assert!(matches!(
968            Amf0Value::parse(&bytes),
969            Err(RtmpError::BufferTooShort(..))
970        ));
971    }
972
973    #[test]
974    fn invalid_utf8_string_is_malformed() {
975        let mut bytes = vec![marker::STRING];
976        bytes.extend_from_slice(&2u16.to_be_bytes());
977        bytes.extend_from_slice(&[0xFF, 0xFE]); // invalid UTF-8
978        assert!(matches!(
979            Amf0Value::parse(&bytes),
980            Err(RtmpError::Amf0Utf8 { what: "string" })
981        ));
982    }
983
984    #[test]
985    fn unsupported_marker_is_rejected_not_panicking() {
986        assert!(matches!(
987            Amf0Value::parse(&[0x11]), // avmplus-object-marker (AMF3 switch)
988            Err(RtmpError::UnsupportedAmf0Marker { marker: 0x11 })
989        ));
990        assert!(matches!(
991            Amf0Value::parse(&[0x07]), // reference-marker
992            Err(RtmpError::UnsupportedAmf0Marker { marker: 0x07 })
993        ));
994    }
995
996    #[test]
997    fn date_rejects_nonzero_reserved_timezone() {
998        let mut bytes = vec![marker::DATE];
999        bytes.extend_from_slice(&0.0f64.to_be_bytes());
1000        bytes.extend_from_slice(&1u16.to_be_bytes()); // reserved must be 0
1001        assert!(matches!(
1002            Amf0Value::parse(&bytes),
1003            Err(RtmpError::Amf0DateTimeZone { value: 1 })
1004        ));
1005    }
1006
1007    #[test]
1008    fn empty_buffer_and_truncated_marker_are_buffer_too_short_not_panics() {
1009        assert!(matches!(
1010            Amf0Value::parse(&[]),
1011            Err(RtmpError::BufferTooShort(..))
1012        ));
1013        assert!(matches!(
1014            Amf0Value::parse(&[marker::NUMBER, 0, 0, 0]),
1015            Err(RtmpError::BufferTooShort(..))
1016        ));
1017    }
1018
1019    // ── Command ──────────────────────────────────────────────────────────
1020
1021    fn connect_command() -> Command {
1022        Command {
1023            name: "connect".to_string(),
1024            transaction_id: 1.0,
1025            arguments: vec![Amf0Value::Object(vec![
1026                ("app".to_string(), Amf0Value::String("live".to_string())),
1027                (
1028                    "flashVer".to_string(),
1029                    Amf0Value::String("FMLE/3.0".to_string()),
1030                ),
1031                (
1032                    "tcUrl".to_string(),
1033                    Amf0Value::String("rtmp://example.test/live".to_string()),
1034                ),
1035                ("fpad".to_string(), Amf0Value::Boolean(false)),
1036            ])],
1037        }
1038    }
1039
1040    fn publish_command() -> Command {
1041        Command {
1042            name: "publish".to_string(),
1043            transaction_id: 5.0,
1044            arguments: vec![
1045                Amf0Value::Null,
1046                Amf0Value::String("stream_key_123".to_string()),
1047                Amf0Value::String("live".to_string()),
1048            ],
1049        }
1050    }
1051
1052    #[test]
1053    fn connect_command_round_trips_byte_identically() {
1054        let cmd = connect_command();
1055        let bytes = cmd.to_body().unwrap();
1056        let parsed = Command::parse(&bytes).expect("parse connect");
1057        assert_eq!(parsed, cmd);
1058        assert_eq!(parsed.to_body().unwrap(), bytes);
1059    }
1060
1061    #[test]
1062    fn publish_command_round_trips_byte_identically() {
1063        let cmd = publish_command();
1064        let bytes = cmd.to_body().unwrap();
1065        let parsed = Command::parse(&bytes).expect("parse publish");
1066        assert_eq!(parsed, cmd);
1067        assert_eq!(parsed.to_body().unwrap(), bytes);
1068    }
1069
1070    #[test]
1071    fn command_name_must_be_string() {
1072        let bytes = Amf0Value::Number(1.0).try_to_bytes().unwrap();
1073        assert!(matches!(
1074            Command::parse(&bytes),
1075            Err(RtmpError::CommandNameNotString { .. })
1076        ));
1077    }
1078
1079    #[test]
1080    fn command_transaction_id_must_be_number() {
1081        let mut bytes = Amf0Value::String("connect".to_string())
1082            .try_to_bytes()
1083            .unwrap();
1084        bytes.extend(
1085            Amf0Value::String("not a number".to_string())
1086                .try_to_bytes()
1087                .unwrap(),
1088        );
1089        assert!(matches!(
1090            Command::parse(&bytes),
1091            Err(RtmpError::CommandTransactionIdNotNumber { .. })
1092        ));
1093    }
1094
1095    // ── 32-bit overflow guards (mutation checks) ─────────────────────────
1096
1097    #[test]
1098    fn long_string_length_overflowing_usize_is_rejected_not_wrapped() {
1099        // Mutation check: a Long String claiming `usize::MAX - 1` bytes must
1100        // be rejected as too-short/malformed, not silently wrap `U32_LEN +
1101        // len` into a small `total` that then compares as if the string
1102        // were actually present.
1103        let mut bytes = vec![marker::LONG_STRING];
1104        bytes.extend_from_slice(&(u32::MAX - 1).to_be_bytes());
1105        bytes.extend_from_slice(b"short");
1106        let err = Amf0Value::parse(&bytes).unwrap_err();
1107        assert!(matches!(
1108            err,
1109            RtmpError::Malformed { .. } | RtmpError::BufferTooShort(..)
1110        ));
1111    }
1112
1113    // ── serde (feature "serde") ───────────────────────────────────────────
1114
1115    #[cfg(feature = "serde")]
1116    #[test]
1117    fn amf0_value_and_command_serde_round_trip() {
1118        let value = Amf0Value::Object(vec![
1119            ("app".to_string(), Amf0Value::String("live".to_string())),
1120            ("live".to_string(), Amf0Value::Boolean(true)),
1121            ("duration".to_string(), Amf0Value::Number(0.0)),
1122            (
1123                "items".to_string(),
1124                Amf0Value::StrictArray(vec![Amf0Value::Null, Amf0Value::Undefined]),
1125            ),
1126        ]);
1127        let json = serde_json::to_string(&value).expect("serialize Amf0Value");
1128        let back: Amf0Value = serde_json::from_str(&json).expect("deserialize Amf0Value");
1129        assert_eq!(back, value);
1130
1131        let cmd = publish_command();
1132        let json = serde_json::to_string(&cmd).expect("serialize Command");
1133        let back: Command = serde_json::from_str(&json).expect("deserialize Command");
1134        assert_eq!(back, cmd);
1135    }
1136}