#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct StandardId(u16);
impl StandardId {
pub const ZERO: Self = StandardId(0);
pub const MAX: Self = StandardId(0x7FF);
#[inline]
pub fn new(raw: u16) -> Option<Self> {
if raw <= 0x7FF {
Some(StandardId(raw))
} else {
None
}
}
#[inline]
pub const unsafe fn new_unchecked(raw: u16) -> Self {
StandardId(raw)
}
#[inline]
pub fn as_raw(&self) -> u16 {
self.0
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub struct ExtendedId(u32);
impl ExtendedId {
pub const ZERO: Self = ExtendedId(0);
pub const MAX: Self = ExtendedId(0x1FFF_FFFF);
#[inline]
pub fn new(raw: u32) -> Option<Self> {
if raw <= 0x1FFF_FFFF {
Some(ExtendedId(raw))
} else {
None
}
}
#[inline]
pub const unsafe fn new_unchecked(raw: u32) -> Self {
ExtendedId(raw)
}
#[inline]
pub fn as_raw(&self) -> u32 {
self.0
}
pub fn standard_id(&self) -> StandardId {
StandardId((self.0 >> 18) as u16)
}
}
#[derive(Debug, Copy, Clone, Eq, PartialEq)]
pub enum Id {
Standard(StandardId),
Extended(ExtendedId),
}
impl From<StandardId> for Id {
#[inline]
fn from(id: StandardId) -> Self {
Id::Standard(id)
}
}
impl From<ExtendedId> for Id {
#[inline]
fn from(id: ExtendedId) -> Self {
Id::Extended(id)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn standard_id_new() {
assert_eq!(
StandardId::new(StandardId::MAX.as_raw()),
Some(StandardId::MAX)
);
}
#[test]
fn standard_id_new_out_of_range() {
assert_eq!(StandardId::new(StandardId::MAX.as_raw() + 1), None);
}
#[test]
fn standard_id_new_unchecked_out_of_range() {
let id = StandardId::MAX.as_raw() + 1;
assert_eq!(unsafe { StandardId::new_unchecked(id) }, StandardId(id));
}
#[test]
fn extended_id_new() {
assert_eq!(
ExtendedId::new(ExtendedId::MAX.as_raw()),
Some(ExtendedId::MAX)
);
}
#[test]
fn extended_id_new_out_of_range() {
assert_eq!(ExtendedId::new(ExtendedId::MAX.as_raw() + 1), None);
}
#[test]
fn extended_id_new_unchecked_out_of_range() {
let id = ExtendedId::MAX.as_raw() + 1;
assert_eq!(unsafe { ExtendedId::new_unchecked(id) }, ExtendedId(id));
}
#[test]
fn get_standard_id_from_extended_id() {
assert_eq!(
Some(ExtendedId::MAX.standard_id()),
StandardId::new((ExtendedId::MAX.0 >> 18) as u16)
);
}
}