use core::fmt;
use core::str;
pub const NAME_CAPACITY: usize = 32;
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Name {
bytes: [u8; NAME_CAPACITY],
len: u8,
}
impl Default for Name {
fn default() -> Self {
Self {
bytes: [0; NAME_CAPACITY],
len: 0,
}
}
}
impl Name {
#[must_use]
pub fn new(name: &str, max_len: usize) -> Self {
let limit = max_len.saturating_sub(1).min(NAME_CAPACITY).min(name.len());
let mut end = limit;
while end > 0 && !name.is_char_boundary(end) {
end = end.saturating_sub(1);
}
let src = name.as_bytes().get(..end).unwrap_or(&[]);
let mut bytes = [0u8; NAME_CAPACITY];
for (slot, byte) in bytes.iter_mut().zip(src.iter()) {
*slot = *byte;
}
Self {
bytes,
len: u8::try_from(end).unwrap_or(0),
}
}
#[must_use]
pub fn as_str(&self) -> &str {
let end = usize::from(self.len);
let slice = self.bytes.get(..end).unwrap_or(&[]);
str::from_utf8(slice).unwrap_or("")
}
#[must_use]
pub const fn len(&self) -> usize {
self.len as usize
}
#[must_use]
pub const fn is_empty(&self) -> bool {
self.len == 0
}
}
impl fmt::Debug for Name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
fmt::Debug::fmt(self.as_str(), f)
}
}
impl fmt::Display for Name {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(self.as_str())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn short_names_survive_whole() {
assert_eq!(Name::new("CNT_INC", 12).as_str(), "CNT_INC");
assert_eq!(Name::new("Tmr Svc", 12).as_str(), "Tmr Svc");
assert_eq!(Name::new("IDLE", 12).as_str(), "IDLE");
}
#[test]
fn long_names_truncate_like_the_c_kernel() {
assert_eq!(Name::new("ABCDEFGHIJKLMNOP", 12).as_str(), "ABCDEFGHIJK");
assert_eq!(Name::new("ABCDEFGHIJKLMNOP", 12).len(), 11);
}
#[test]
fn degenerate_limits_are_errors_not_panics() {
assert!(Name::new("anything", 0).is_empty());
assert!(Name::new("anything", 1).is_empty());
assert_eq!(Name::new("anything", 2).as_str(), "a");
assert_eq!(Name::new("", 12).as_str(), "");
}
#[test]
fn a_name_longer_than_the_capacity_is_capped() {
let long = "x".repeat(NAME_CAPACITY * 2);
let n = Name::new(&long, usize::MAX);
assert_eq!(n.len(), NAME_CAPACITY);
}
}