broadcast-core 0.1.0

Frozen wire-format contract for the rust-broadcast crates: symmetric Parse/Serialize traits, checked field-width helpers, MSB-first bit I/O, reserved-bit fields, media timescales, the shared error kinds and the CENC scheme identity. no_std + alloc.
Documentation
//! Canonical `Parse`, `ParsePrefix`, `ParseWith` and `Serialize` traits for the DVB crate family.
//!
//! Each implementer picks its own error type via `type Error`, so
//! domain-specific error variants stay visible to the caller.

use alloc::vec::Vec;

/// Parse a DVB structure from raw bytes. Borrowing allowed via `<'a>`; the
/// concrete error type is chosen per implementer.
pub trait Parse<'a>: Sized {
    /// The error type this implementer returns. Typically the enclosing
    /// crate's `Error` enum.
    type Error;

    /// Parse `bytes` as `Self`. Returns `Err(Self::Error)` on any protocol
    /// violation or buffer underrun.
    ///
    /// The structure starts at `bytes[0]`. Bytes after a structure's own
    /// declared end are not part of it (the crate's trailing-byte policy says
    /// whether they are ignored or refused); a structure with no declared end
    /// consumes all of `bytes`. A caller that needs the length consumed uses
    /// [`ParsePrefix`].
    fn parse(bytes: &'a [u8]) -> Result<Self, Self::Error>;
}

/// Parse one length-delimited structure from the front of `bytes` and say
/// how many bytes it took, so a loop can walk a run of them (TLV items,
/// descriptors, boxes, data units).
///
/// This is a separate trait, not a blanket over [`Parse`]: a type with its
/// own end implements it explicitly.
pub trait ParsePrefix<'a>: Sized {
    /// The error type this implementer returns. Typically the enclosing
    /// crate's `Error` enum.
    type Error;

    /// Parse one `Self` starting at `bytes[0]`, returning it and the number
    /// of bytes it occupies (never more than `bytes.len()`).
    fn parse_prefix(bytes: &'a [u8]) -> Result<(Self, usize), Self::Error>;
}

/// Parse a structure whose work or nesting the caller must bound.
///
/// A type implements [`Parse`] when its work and allocation are bounded by
/// `bytes.len()` and its recursion depth is fixed by the format; otherwise it
/// implements `ParseWith` and not `Parse`, so a limit is never invented by the
/// library. The limits are a plain `*Limits` literal struct the caller builds
/// and passes by reference; there is no default and no unlimited value.
pub trait ParseWith<'a>: Sized {
    /// The caller's bounds.
    type Limits: ?Sized;

    /// The error type this implementer returns.
    type Error;

    /// Parse `bytes` as `Self`, refusing or reporting what exceeds `limits`.
    fn parse_with(bytes: &'a [u8], limits: &Self::Limits) -> Result<Self, Self::Error>;
}

/// Serialize a DVB structure back to bytes. Split from [`Parse`] so owned
/// and borrowed variants of the same type can implement `Serialize`
/// without carrying a lifetime.
pub trait Serialize {
    /// The error type this implementer returns (usually the same as the
    /// corresponding [`Parse`] impl, but need not be).
    type Error;

    /// Number of bytes `serialize_into` will write.
    fn serialized_len(&self) -> usize;

    /// Write the serialised form into `buf`. Returns the number of bytes
    /// written (always equal to `serialized_len()`).
    fn serialize_into(&self, buf: &mut [u8]) -> Result<usize, Self::Error>;

    /// Allocate a `Vec` and serialize into it, returning the serializer's error instead of
    /// panicking. This is the only
    /// allocate-and-serialize entry point: there is deliberately no panicking
    /// `to_bytes` (hand-built values, or values assembled from damaged wire data,
    /// can violate a wire constraint, so the error must reach the caller).
    fn try_to_bytes(&self) -> Result<Vec<u8>, Self::Error> {
        let mut v = alloc::vec![0u8; self.serialized_len()];
        let written = self.serialize_into(&mut v)?;
        // A serializer that writes fewer bytes than it promised must not
        // leave trailing zeros in the result.
        if written != v.len() {
            v.truncate(written);
        }
        Ok(v)
    }

    /// Append the serialised form to `out`, returning the number of bytes
    /// appended. `out` is left unchanged when the serializer fails.
    fn serialize_append(&self, out: &mut Vec<u8>) -> Result<usize, Self::Error> {
        let start = out.len();
        out.resize(start + self.serialized_len(), 0);
        match self.serialize_into(&mut out[start..]) {
            Ok(written) => {
                out.truncate(start + written);
                Ok(written)
            }
            Err(e) => {
                out.truncate(start);
                Err(e)
            }
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::vec;
    use core::fmt;

    #[derive(Debug, PartialEq)]
    struct TestError;

    #[derive(Debug, PartialEq)]
    struct LengthPrefixed<'a>(&'a [u8]);

    impl<'a> ParsePrefix<'a> for LengthPrefixed<'a> {
        type Error = TestError;
        fn parse_prefix(bytes: &'a [u8]) -> Result<(Self, usize), TestError> {
            let (&len, rest) = bytes.split_first().ok_or(TestError)?;
            let body = rest.get(..usize::from(len)).ok_or(TestError)?;
            Ok((LengthPrefixed(body), 1 + body.len()))
        }
    }

    #[derive(Debug, PartialEq)]
    struct Bounded<'a>(&'a [u8]);

    struct MaxLen {
        max: usize,
    }

    impl<'a> ParseWith<'a> for Bounded<'a> {
        type Limits = MaxLen;
        type Error = TestError;
        fn parse_with(bytes: &'a [u8], limits: &MaxLen) -> Result<Self, TestError> {
            if bytes.len() > limits.max {
                return Err(TestError);
            }
            Ok(Bounded(bytes))
        }
    }

    #[test]
    fn parse_with_takes_the_callers_limits() {
        let limits = MaxLen { max: 2 };
        assert_eq!(Bounded::parse_with(&[1, 2], &limits), Ok(Bounded(&[1, 2])));
        assert_eq!(Bounded::parse_with(&[1, 2, 3], &limits), Err(TestError));
    }

    #[test]
    fn parse_prefix_walks_a_run_and_reports_what_it_consumed() {
        let run = [2, 0xA, 0xB, 0, 1, 0xC];
        let mut rest = &run[..];
        let mut items = vec![];
        while !rest.is_empty() {
            let (item, used) = LengthPrefixed::parse_prefix(rest).unwrap();
            items.push(item);
            rest = &rest[used..];
        }
        assert_eq!(
            items,
            [
                LengthPrefixed(&[0xA, 0xB]),
                LengthPrefixed(&[]),
                LengthPrefixed(&[0xC])
            ]
        );
        assert_eq!(LengthPrefixed::parse_prefix(&[]), Err(TestError));
        assert_eq!(LengthPrefixed::parse_prefix(&[2, 0xA]), Err(TestError));
    }

    impl fmt::Display for TestError {
        fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
            f.write_str("test serializer error")
        }
    }

    /// Minimal `Serialize` impl whose `serialize_into` fails when `fail` is set.
    struct Flagged {
        fail: bool,
        written: usize,
    }

    impl Serialize for Flagged {
        type Error = TestError;

        fn serialized_len(&self) -> usize {
            4
        }

        fn serialize_into(&self, buf: &mut [u8]) -> Result<usize, Self::Error> {
            if self.fail {
                return Err(TestError);
            }
            let n = self.written.min(buf.len());
            buf[..n].copy_from_slice(&[1, 2, 3, 4][..n]);
            Ok(n)
        }
    }

    #[test]
    fn serialize_append_extends_and_leaves_out_untouched_on_error() {
        let mut out = vec![9u8];
        let ok = Flagged {
            fail: false,
            written: 4,
        };
        assert_eq!(ok.serialize_append(&mut out), Ok(4));
        assert_eq!(out, [9, 1, 2, 3, 4]);
        let bad = Flagged {
            fail: true,
            written: 4,
        };
        assert_eq!(bad.serialize_append(&mut out), Err(TestError));
        assert_eq!(out, [9, 1, 2, 3, 4]);
    }

    #[test]
    fn try_to_bytes_returns_serializer_error() {
        assert_eq!(
            Flagged {
                fail: true,
                written: 0
            }
            .try_to_bytes(),
            Err(TestError)
        );
    }

    #[test]
    fn try_to_bytes_truncates_when_serializer_writes_less_than_promised() {
        // serialized_len is 4 but only 3 bytes are written: no trailing zero.
        let v = Flagged {
            fail: false,
            written: 3,
        }
        .try_to_bytes()
        .unwrap();
        assert_eq!(v, vec![1, 2, 3]);
    }

    #[test]
    fn try_to_bytes_happy_path_fills_buffer() {
        let ok = Flagged {
            fail: false,
            written: 4,
        };
        assert_eq!(ok.try_to_bytes().unwrap(), vec![1, 2, 3, 4]);
    }
}