use core::fmt;
use core::str;
pub const NAME_CAPACITY: usize = 16;
const _: () = assert!(
NAME_CAPACITY <= 16,
"NAME_CAPACITY above 16 makes as_str's widening branch live again: give it a test case, and re-measure the trace rows, before raising this."
);
#[derive(Clone, Copy, PartialEq, Eq)]
#[cfg_attr(target_pointer_width = "64", repr(align(8)))]
pub struct Name {
bytes: [u8; NAME_CAPACITY],
len: u8,
}
#[cfg(target_pointer_width = "64")]
const _: () = assert!(
core::mem::align_of::<Name>() >= core::mem::size_of::<usize>(),
"Name must be usize-aligned on the host or as_str's word-at-a-time UTF-8 path stops being taken and every name a trace prints costs three times what it should."
);
impl Default for Name {
fn default() -> Self {
Self {
bytes: [0; NAME_CAPACITY],
len: 0,
}
}
}
impl Name {
#[must_use]
#[inline(always)]
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 (d, s) in bytes.iter_mut().zip(src.iter()) {
*d = *s;
}
Self {
bytes,
len: u8::try_from(end).unwrap_or(0),
}
}
#[must_use]
#[inline(always)]
pub fn as_str(&self) -> &str {
let end = usize::from(self.len).min(NAME_CAPACITY);
const WINDOW: usize = 16;
let window = if end <= WINDOW { WINDOW } else { NAME_CAPACITY };
match str::from_utf8(self.bytes.get(..window).unwrap_or(&[])) {
Ok(all) => all.get(..end).unwrap_or(""),
Err(_) => "",
}
}
#[must_use]
#[inline(always)]
pub fn matches(&self, other: &str) -> bool {
let end = usize::from(self.len).min(NAME_CAPACITY);
self.bytes.get(..end) == Some(other.as_bytes())
}
#[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 the_tail_stays_valid_so_as_str_can_check_a_whole_window() {
for (text, limit) in [("StrTrig", 12), ("", 12), ("a", 2), ("IDLE", 12)] {
let n = Name::new(text, limit);
assert!(
str::from_utf8(n.bytes.get(..16).unwrap_or(&[])).is_ok(),
"the sixteen-byte window must be valid UTF-8, not just the prefix"
);
assert!(
n.bytes
.get(n.len()..)
.unwrap_or(&[])
.iter()
.all(|b| *b == 0),
"the tail past `len` must be NUL"
);
}
let full = Name::new(&"A".repeat(NAME_CAPACITY), NAME_CAPACITY);
assert_eq!(full.len(), NAME_CAPACITY - 1);
assert_eq!(full.as_str(), "A".repeat(NAME_CAPACITY - 1));
let brim = Name::new(&"B".repeat(NAME_CAPACITY * 2), usize::MAX);
assert_eq!(brim.len(), NAME_CAPACITY);
assert_eq!(brim.as_str(), "B".repeat(NAME_CAPACITY));
}
#[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);
}
#[test]
fn a_name_with_characters_is_not_empty() {
assert!(!Name::new("IDLE", 12).is_empty());
assert!(Name::new("", 12).is_empty());
}
#[test]
fn display_and_debug_print_the_name() {
let n = Name::new("Tmr Svc", 12);
assert_eq!(std::format!("{n}"), "Tmr Svc");
assert_eq!(std::format!("{n:?}"), "\"Tmr Svc\"");
}
}