use std::fmt;
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct SymbolId(usize);
impl SymbolId {
#[inline]
pub const fn try_new(dense_index: usize, slot_count: usize) -> Option<Self> {
if dense_index > 0 && dense_index < slot_count {
Some(Self(dense_index))
} else {
None
}
}
#[inline]
pub const fn packed_membership_bit(self) -> Option<u64> {
if self.0 <= u64::BITS as usize {
Some(1u64 << (self.0 - 1))
} else {
None
}
}
#[inline]
pub const fn index(self) -> usize {
self.0
}
}
impl fmt::Display for SymbolId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct AggregateId(usize);
impl AggregateId {
pub const fn try_new(index: usize, aggregate_count: usize) -> Option<Self> {
if index < aggregate_count {
Some(Self(index))
} else {
None
}
}
pub const fn index(self) -> usize {
self.0
}
}
impl fmt::Display for AggregateId {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[repr(transparent)]
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct PositionOffset(u32);
impl PositionOffset {
pub const fn try_new(value: u64) -> Option<Self> {
if value <= u32::MAX as u64 {
Some(Self(value as u32))
} else {
None
}
}
#[cfg(test)]
pub const fn as_u32(self) -> u32 {
self.0
}
}
impl fmt::Display for PositionOffset {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
self.0.fmt(f)
}
}
#[cfg(test)]
mod tests {
use super::{AggregateId, PositionOffset, SymbolId};
#[test]
fn symbol_ids_exclude_empty_and_out_of_bounds_slots() {
assert_eq!(SymbolId::try_new(0, 3), None);
assert_eq!(SymbolId::try_new(1, 3).map(SymbolId::index), Some(1));
assert_eq!(SymbolId::try_new(2, 3).map(SymbolId::index), Some(2));
assert_eq!(SymbolId::try_new(3, 3), None);
}
#[test]
fn aggregate_ids_validate_zero_based_program_bounds() {
assert_eq!(AggregateId::try_new(0, 0), None);
assert_eq!(AggregateId::try_new(0, 2).map(AggregateId::index), Some(0));
assert_eq!(AggregateId::try_new(1, 2).map(AggregateId::index), Some(1));
assert_eq!(AggregateId::try_new(2, 2), None);
}
#[test]
fn position_offsets_are_checked_at_u32_max() {
assert_eq!(
PositionOffset::try_new(0).map(PositionOffset::as_u32),
Some(0)
);
assert_eq!(
PositionOffset::try_new(u32::MAX as u64).map(PositionOffset::as_u32),
Some(u32::MAX)
);
assert_eq!(PositionOffset::try_new(u32::MAX as u64 + 1), None);
}
#[test]
fn candidate_offsets_are_compact() {
assert_eq!(size_of::<PositionOffset>(), size_of::<u32>());
}
}