use std::borrow::Cow;
use std::fmt::{Debug, Display};
#[repr(C)]
#[derive(Clone, Copy, PartialEq, Eq, Hash)]
pub struct PaddedString<const SIZE: usize> {
array: [u8; SIZE],
}
impl<const SIZE: usize> PaddedString<SIZE> {
pub fn as_bytes(&self) -> &[u8] {
&self.array[..self.len()]
}
pub fn to_string_lossy(&self) -> Cow<'_, str> {
String::from_utf8_lossy(self.as_bytes())
}
pub fn len(&self) -> usize {
self.array.iter().position(|&b| b == 0).unwrap_or(SIZE)
}
pub fn is_empty(&self) -> bool {
self.array.first() == Some(&0)
}
}
impl<const SIZE: usize> Display for PaddedString<SIZE> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}", self.to_string_lossy())
}
}
impl<const SIZE: usize> Debug for PaddedString<SIZE> {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
Debug::fmt(&self.to_string_lossy(), f)
}
}
impl<const SIZE: usize> AsRef<[u8]> for PaddedString<SIZE> {
fn as_ref(&self) -> &[u8] {
self.as_bytes()
}
}