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
//! A byte range of the input.

use core::fmt;

/// An absolute byte range of the input: `len` bytes from `offset`, as far as
/// the reader knows it. It may be empty: a zero-length range marks a point,
/// such as a loss whose bytes are not in the input at all (packets dropped
/// upstream), at which `offset` is where the loss begins.
#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash)]
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
pub struct ByteRange {
    offset: u64,
    len: u64,
}

impl ByteRange {
    /// The `len` bytes starting at absolute offset `offset`.
    #[must_use]
    pub const fn new(offset: u64, len: u64) -> Self {
        Self { offset, len }
    }

    /// Offset of the first byte, from the start of the input.
    #[must_use]
    pub const fn offset(self) -> u64 {
        self.offset
    }

    /// Number of bytes covered.
    #[must_use]
    pub const fn len(self) -> u64 {
        self.len
    }

    /// The range of the inclusive byte positions `first..=last`. `None` when
    /// `first > last` (an empty range has no last byte) or when the length
    /// does not fit a `u64`.
    #[must_use]
    pub const fn from_inclusive(first: u64, last: u64) -> Option<Self> {
        match last.checked_sub(first) {
            Some(span) => match span.checked_add(1) {
                Some(len) => Some(Self::new(first, len)),
                None => None,
            },
            None => None,
        }
    }

    /// Whether the range covers no bytes.
    #[must_use]
    pub const fn is_empty(self) -> bool {
        self.len == 0
    }

    /// Offset one past the last byte covered, or `None` when that offset does
    /// not fit a `u64` (an end past the clock is never a saturated end).
    #[must_use]
    pub const fn end(self) -> Option<u64> {
        self.offset.checked_add(self.len)
    }

    /// The inclusive position of the last byte covered, or `None` for an
    /// empty range or one whose last position does not fit a `u64`.
    #[must_use]
    pub const fn last(self) -> Option<u64> {
        match self.len.checked_sub(1) {
            Some(back) => self.offset.checked_add(back),
            None => None,
        }
    }
}

impl fmt::Display for ByteRange {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        match self.end() {
            Some(end) => write!(f, "bytes {}..{end}", self.offset),
            None => write!(f, "bytes {}+{}", self.offset, self.len),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use alloc::string::ToString;

    #[test]
    fn end_is_checked_and_display_names_the_span() {
        let range = ByteRange::new(10, 5);
        assert_eq!(
            (range.offset(), range.len(), range.end()),
            (10, 5, Some(15))
        );
        assert!(!range.is_empty());
        assert!(ByteRange::new(10, 0).is_empty());
        assert_eq!(ByteRange::new(u64::MAX, 1).end(), None);
        assert_eq!(range.to_string(), "bytes 10..15");
        assert_eq!(range.last(), Some(14));
        assert_eq!(ByteRange::new(10, 0).last(), None);
        assert_eq!(ByteRange::new(u64::MAX, 1).last(), Some(u64::MAX));
        assert_eq!(ByteRange::new(u64::MAX, 2).last(), None);
        assert_eq!(
            ByteRange::new(u64::MAX, 2).to_string(),
            "bytes 18446744073709551615+2"
        );
    }

    #[test]
    fn an_inclusive_range_is_built_from_its_two_ends() {
        let range = ByteRange::from_inclusive(90, 99).expect("a range");
        assert_eq!((range.offset(), range.len()), (90, 10));
        assert_eq!(ByteRange::from_inclusive(7, 7), Some(ByteRange::new(7, 1)));
        assert_eq!(ByteRange::from_inclusive(9, 0), None);
        assert_eq!(
            ByteRange::from_inclusive(0, u64::MAX),
            None,
            "a range longer than u64 is not one"
        );
    }
}