use std::fmt::Debug;
use thiserror::Error;
pub struct TinyString([u8; 6]);
impl TinyString {
pub fn to_bytes(self) -> [u8; 6] {
self.0
}
pub unsafe fn from_bytes_unchecked(bytes: [u8; 6]) -> Self {
Self(bytes)
}
}
impl<'a> TryFrom<&'a str> for TinyString {
type Error = TinyStringError;
fn try_from(s: &'a str) -> Result<Self, Self::Error> {
if s.len() > 6 {
return Err(TinyStringError::TooLong);
}
if s.contains('\0') {
return Err(TinyStringError::ContainsNul);
}
let mut bytes = [0; 6];
bytes[..s.len()].copy_from_slice(s.as_bytes());
Ok(TinyString(bytes))
}
}
#[derive(Error, Debug)]
pub enum TinyStringError {
#[error("String is too long for TinyString")]
TooLong,
#[error("String contains a NUL byte")]
ContainsNul,
}
impl AsRef<str> for TinyString {
fn as_ref(&self) -> &str {
let len = self.0.iter().position(|&b| b == 0).unwrap_or(6);
unsafe { std::str::from_utf8_unchecked(&self.0[..len]) }
}
}
impl Debug for TinyString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.as_ref().fmt(f)
}
}
impl PartialEq for TinyString {
fn eq(&self, other: &Self) -> bool {
self.as_ref() == other.as_ref()
}
}
impl Eq for TinyString {}