#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FixedText<const N: usize> {
buf: [u8; N],
}
impl<const N: usize> FixedText<N> {
pub(crate) const fn from_bytes(buf: [u8; N]) -> Self {
Self { buf }
}
#[must_use]
pub fn from_text(s: &str) -> Self {
let mut buf = [0u8; N];
let bytes = s.as_bytes();
let len = bytes.len().min(N);
buf[..len].copy_from_slice(&bytes[..len]);
Self { buf }
}
pub(crate) const fn as_bytes(&self) -> &[u8; N] {
&self.buf
}
#[must_use]
pub fn as_str(&self) -> &str {
let mut end = N;
while end > 0 && self.buf[end - 1] == 0 {
end -= 1;
}
core::str::from_utf8(&self.buf[..end]).unwrap_or_default()
}
}
impl<const N: usize> core::fmt::Display for FixedText<N> {
fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
f.write_str(self.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn round_trips_a_short_string() {
let t: FixedText<16> = FixedText::from_text("THR_MAX");
assert_eq!(t.as_str(), "THR_MAX");
assert_eq!(t.as_bytes()[7], 0);
}
#[test]
fn truncates_a_too_long_string() {
let t: FixedText<4> = FixedText::from_text("hello");
assert_eq!(t.as_str(), "hell");
}
#[test]
fn from_bytes_trims_nul_padding() {
let t = FixedText::from_bytes(*b"AB\0\0");
assert_eq!(t.as_str(), "AB");
}
}