use core::fmt;
#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
#[cfg_attr(feature = "serde", serde(transparent))]
#[repr(transparent)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord, Hash, Default)]
pub struct BytePos(u32);
impl BytePos {
#[inline]
#[must_use]
pub const fn new(offset: u32) -> Self {
Self(offset)
}
#[inline]
#[must_use]
pub const fn to_u32(self) -> u32 {
self.0
}
#[inline]
#[must_use]
pub const fn to_usize(self) -> usize {
self.0 as usize
}
}
impl From<u32> for BytePos {
#[inline]
fn from(offset: u32) -> Self {
Self(offset)
}
}
impl From<BytePos> for u32 {
#[inline]
fn from(pos: BytePos) -> Self {
pos.0
}
}
impl fmt::Display for BytePos {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Display::fmt(&self.0, f)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_byte_pos_round_trips_through_u32() {
let p = BytePos::new(123);
assert_eq!(u32::from(p), 123);
assert_eq!(BytePos::from(123u32), p);
}
#[test]
fn test_byte_pos_default_is_zero() {
assert_eq!(BytePos::default(), BytePos::new(0));
}
#[test]
fn test_byte_pos_ordering_matches_offset() {
assert!(BytePos::new(3) < BytePos::new(4));
assert!(BytePos::new(9) > BytePos::new(8));
}
#[test]
fn test_byte_pos_display_is_the_number() {
extern crate alloc;
use alloc::string::ToString;
assert_eq!(BytePos::new(256).to_string(), "256");
}
}