Skip to main content

o3/buffer/raw/length/
mod.rs

1use std::marker;
2
3mod seal;
4pub(super) use seal::Seal;
5
6pub trait Length: Seal + marker::Copy {
7    const MAX: usize;
8    const ZERO: Self;
9
10    fn from_usize(value: usize) -> Self;
11    fn into_usize(self) -> usize;
12
13    /// # Safety
14    /// The sum must fit this length representation and therefore `usize`.
15    unsafe fn add(self, amount: usize) -> Self {
16        Self::from_usize(self.into_usize() + amount)
17    }
18}
19
20impl Length for u8 {
21    const MAX: usize = u8::MAX as usize;
22    const ZERO: Self = 0;
23
24    fn from_usize(value: usize) -> Self {
25        value as Self
26    }
27
28    fn into_usize(self) -> usize {
29        self as usize
30    }
31}
32
33impl Length for u16 {
34    const MAX: usize = u16::MAX as usize;
35    const ZERO: Self = 0;
36
37    fn from_usize(value: usize) -> Self {
38        value as Self
39    }
40
41    fn into_usize(self) -> usize {
42        self as usize
43    }
44}
45
46impl Length for u32 {
47    const MAX: usize = u32::MAX as usize;
48    const ZERO: Self = 0;
49
50    fn from_usize(value: usize) -> Self {
51        value as Self
52    }
53
54    fn into_usize(self) -> usize {
55        self as usize
56    }
57}
58
59impl Length for usize {
60    const MAX: usize = usize::MAX;
61    const ZERO: Self = 0;
62
63    fn from_usize(value: usize) -> Self {
64        value
65    }
66
67    fn into_usize(self) -> usize {
68        self
69    }
70}