use super::{
nice_arr,
nice_str,
nice_uint,
NiceChar,
};
use std::num::NonZeroU8;
#[repr(u8)]
#[derive(Debug, Clone, Copy, Eq, Ord, PartialEq, PartialOrd)]
enum NiceU8Idx {
From00 = 0_u8, From01 = 1_u8, From02 = 2_u8, }
#[cfg_attr(
not(test),
expect(dead_code, reason = "For consistency with bigger index types.")
)]
impl NiceU8Idx {
const DIGITS: [Self; 3] = [
Self::From02, Self::From01, Self::From00,
];
const LAST: Self = Self::From02;
const LEN: usize = 3;
}
nice_uint! {
NiceU8, NiceU8Idx,
u8, NonZeroU8,
[ 0 0 0 ],
[ 2 5 5 ]
}
impl From<u8> for NiceU8 {
#[inline]
fn from(src: u8) -> Self {
let (data, from) = data_from(src);
Self { data, from }
}
}
impl NiceU8 {
#[must_use]
#[inline]
pub const fn as_bytes2(&self) -> &[u8] {
NiceChar::as_bytes(
if matches!(self.from, NiceU8Idx::From00) { self.data.as_slice() }
else {
let (_, rest) = self.data.split_at(1);
rest
}
)
}
#[must_use]
#[inline]
pub const fn as_bytes3(&self) -> &[u8] {
NiceChar::as_bytes(self.data.as_slice())
}
#[must_use]
#[inline]
pub const fn as_str2(&self) -> &str {
NiceChar::as_str(
if matches!(self.from, NiceU8Idx::From00) { self.data.as_slice() }
else {
let (_, rest) = self.data.split_at(1);
rest
}
)
}
#[must_use]
#[inline]
pub const fn as_str3(&self) -> &str {
NiceChar::as_str(self.data.as_slice())
}
}
impl NiceU8 {
pub const fn replace(&mut self, src: u8) {
(self.data, self.from) = data_from(src);
}
}
#[inline]
const fn data_from(num: u8) -> ([NiceChar; 3], NiceU8Idx) {
if 99 < num {
let a = if 199 < num { NiceChar::Digit2 } else { NiceChar::Digit1 };
let b = NiceChar::from_digit_u8(num / 10);
let c = NiceChar::from_digit_u8(num);
([a, b, c], NiceU8Idx::From00)
}
else if 9 < num {
let b = NiceChar::from_digit_u8(num / 10);
let c = NiceChar::from_digit_u8(num);
([NiceChar::Digit0, b, c], NiceU8Idx::From01)
}
else {
(
[NiceChar::Digit0, NiceChar::Digit0, NiceChar::from_digit_u8(num)],
NiceU8Idx::From02
)
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn t_nice() {
assert_eq!(NiceU8::default(), NiceU8::from(0));
assert_eq!(NiceU8::MIN, NiceU8::from(0));
assert_eq!(NiceU8::MAX, NiceU8::from(u8::MAX));
let mut last = NiceU8::MAX;
for i in u8::MIN..=u8::MAX {
let istr = i.to_string();
let nice = NiceU8::from(i);
assert_eq!(istr, nice.as_str());
assert_eq!(istr.as_bytes(), nice.as_bytes());
assert_eq!(istr.len(), nice.len());
assert_ne!(nice, last);
last.replace(i);
assert_eq!(nice, last);
}
}
super::super::nice_test!(NiceU8Idx);
}