can-hal-rs 0.3.4

Hardware-agnostic traits for CAN bus communication
Documentation
/// Maximum value for an 11-bit standard CAN identifier.
const STANDARD_MAX: u16 = 0x7FF;

/// Maximum value for a 29-bit extended CAN identifier.
const EXTENDED_MAX: u32 = 0x1FFF_FFFF;

/// A CAN bus identifier, either standard (11-bit) or extended (29-bit).
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub enum CanId {
    /// Standard 11-bit identifier (0x000–0x7FF).
    Standard(u16),
    /// Extended 29-bit identifier (0x00000000–0x1FFFFFFF).
    Extended(u32),
}

impl CanId {
    /// Create a standard (11-bit) CAN ID, returning `None` if the value exceeds 0x7FF.
    #[must_use]
    pub const fn new_standard(id: u16) -> Option<Self> {
        if id <= STANDARD_MAX {
            Some(Self::Standard(id))
        } else {
            None
        }
    }

    /// Create an extended (29-bit) CAN ID, returning `None` if the value exceeds 0x1FFFFFFF.
    #[must_use]
    pub const fn new_extended(id: u32) -> Option<Self> {
        if id <= EXTENDED_MAX {
            Some(Self::Extended(id))
        } else {
            None
        }
    }

    /// Returns the raw numeric identifier value.
    #[must_use]
    #[allow(clippy::cast_lossless)] // From is not const-stable
    pub const fn raw(&self) -> u32 {
        match *self {
            Self::Standard(id) => id as u32,
            Self::Extended(id) => id,
        }
    }

    /// Returns `true` if this is a standard (11-bit) identifier.
    #[must_use]
    pub const fn is_standard(&self) -> bool {
        matches!(self, Self::Standard(_))
    }

    /// Returns `true` if this is an extended (29-bit) identifier.
    #[must_use]
    pub const fn is_extended(&self) -> bool {
        matches!(self, Self::Extended(_))
    }
}