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
//! The decimal time-unit ratios every crate that converts between seconds, milliseconds,
//! microseconds and nanoseconds uses, declared once.
//!
//! All are `u64`; a caller that works in another integer or float width casts at the use
//! (`NANOS_PER_SEC as i128`). [`crate::timescale::Timescale::MICROS`] is built from
//! [`MICROS_PER_SEC`].

/// Milliseconds in a second.
pub const MILLIS_PER_SEC: u64 = 1_000;
/// Microseconds in a millisecond.
pub const MICROS_PER_MILLI: u64 = 1_000;
/// Microseconds in a second.
pub const MICROS_PER_SEC: u64 = MILLIS_PER_SEC * MICROS_PER_MILLI;
/// Nanoseconds in a microsecond.
pub const NANOS_PER_MICRO: u64 = 1_000;
/// Nanoseconds in a millisecond.
pub const NANOS_PER_MILLI: u64 = NANOS_PER_MICRO * MICROS_PER_MILLI;
/// Nanoseconds in a second.
pub const NANOS_PER_SEC: u64 = NANOS_PER_MILLI * MILLIS_PER_SEC;

/// Bits in a byte.
pub const BITS_PER_BYTE: u32 = u8::BITS;
/// Bytes in a kibibyte.
pub const KIB: u64 = 1 << 10;
/// Bytes in a mebibyte.
pub const MIB: u64 = KIB << 10;

/// Greatest common divisor of two values, never below 1 so a caller can always divide by it.
pub fn gcd(mut a: u64, mut b: u64) -> u64 {
    while b != 0 {
        (a, b) = (b, a % b);
    }
    a.max(1)
}

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

    #[test]
    fn gcd_reduces_and_is_never_zero() {
        assert_eq!(gcd(48, 18), 6);
        assert_eq!(gcd(7, 0), 7);
        assert_eq!(gcd(0, 0), 1);
        assert_eq!(gcd(90_000, 1_001), 1);
    }

    #[test]
    fn the_ratios_are_the_decimal_units() {
        assert_eq!(MICROS_PER_SEC, 1_000_000);
        assert_eq!(NANOS_PER_MILLI, 1_000_000);
        assert_eq!(NANOS_PER_SEC, 1_000_000_000);
        assert_eq!((BITS_PER_BYTE, KIB, MIB), (8, 1_024, 1_048_576));
        assert_eq!(
            MICROS_PER_SEC,
            u64::from(crate::timescale::Timescale::MICROS.get())
        );
    }
}