Skip to content

Commit a037a0e

Browse files
authored
improv: AsciiNumber API
* automatically derive `Clone` & `Copy` for `AsciiNumber<N>` * custom implementation of `PartialEq`, `Eq`, `Default` for `AsciiNumber<N>` * add new constant `AsciiNumber::<N>::ZERO` with const assertion `AsciiNumber::<N>::MIN_LEN_ASSERTION` to make sure N is at least 1
1 parent 7a454c3 commit a037a0e

1 file changed

Lines changed: 26 additions & 0 deletions

File tree

src/lib.rs

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,12 +130,24 @@ const DEC_LOOKUP: &[u8; 200] = b"0001020304050607080910111213141516171819\
130130
const MAX_SUPPORTED_BASE: u128 = LOOKUP.len() as u128;
131131

132132
/// The result of a number conversion to ascii containing a string with at most length `N` bytes/characters
133+
#[derive(Clone, Copy)]
133134
pub struct AsciiNumber<const N: usize> {
134135
string: [u8; N],
135136
start: usize,
136137
}
137138

138139
impl <const N: usize> AsciiNumber<N> {
140+
141+
#[allow(dead_code)]
142+
const MIN_LEN_ASSERTION: () = assert!(N > 0);
143+
144+
pub const ZERO: AsciiNumber<N> = {
145+
let mut string = [0_u8; N];
146+
string[N-1] = b'0';
147+
let start = N-1;
148+
AsciiNumber { string, start }
149+
};
150+
139151
/// Get the ascii representation of the number as a byte slice
140152
pub const fn as_slice(&self) -> &[u8] {
141153
self.string.split_at(self.start).1
@@ -150,6 +162,20 @@ impl <const N: usize> AsciiNumber<N> {
150162
}
151163
}
152164

165+
impl <const N: usize> PartialEq for AsciiNumber<N> {
166+
fn eq(&self, other: &AsciiNumber<N>) -> bool {
167+
PartialEq::eq(self.as_slice(), other.as_slice())
168+
}
169+
}
170+
171+
impl <const N: usize> Eq for AsciiNumber<N> {}
172+
173+
impl <const N: usize> Default for AsciiNumber<N> {
174+
fn default() -> Self {
175+
Self::ZERO
176+
}
177+
}
178+
153179
impl <const N: usize> Deref for AsciiNumber<N> {
154180
type Target = str;
155181
fn deref(&self) -> &<Self as Deref>::Target {

0 commit comments

Comments
 (0)