rusty_rtos_kernel_core/
name.rs1use core::fmt;
10use core::str;
11
12pub const NAME_CAPACITY: usize = 32;
18
19#[derive(Clone, Copy, PartialEq, Eq)]
22pub struct Name {
23 bytes: [u8; NAME_CAPACITY],
24 len: u8,
25}
26
27impl Default for Name {
28 fn default() -> Self {
29 Self {
30 bytes: [0; NAME_CAPACITY],
31 len: 0,
32 }
33 }
34}
35
36impl Name {
37 #[must_use]
46 pub fn new(name: &str, max_len: usize) -> Self {
47 let limit = max_len.saturating_sub(1).min(NAME_CAPACITY).min(name.len());
48 let mut end = limit;
50 while end > 0 && !name.is_char_boundary(end) {
51 end = end.saturating_sub(1);
52 }
53 let src = name.as_bytes().get(..end).unwrap_or(&[]);
54 let mut bytes = [0u8; NAME_CAPACITY];
55 for (slot, byte) in bytes.iter_mut().zip(src.iter()) {
56 *slot = *byte;
57 }
58 Self {
59 bytes,
60 len: u8::try_from(end).unwrap_or(0),
61 }
62 }
63
64 #[must_use]
66 pub fn as_str(&self) -> &str {
67 let end = usize::from(self.len);
68 let slice = self.bytes.get(..end).unwrap_or(&[]);
69 str::from_utf8(slice).unwrap_or("")
70 }
71
72 #[must_use]
74 pub const fn len(&self) -> usize {
75 self.len as usize
76 }
77
78 #[must_use]
80 pub const fn is_empty(&self) -> bool {
81 self.len == 0
82 }
83}
84
85impl fmt::Debug for Name {
86 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
87 fmt::Debug::fmt(self.as_str(), f)
88 }
89}
90
91impl fmt::Display for Name {
92 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
93 f.write_str(self.as_str())
94 }
95}
96
97#[cfg(test)]
98mod tests {
99 use super::*;
100
101 #[test]
102 fn short_names_survive_whole() {
103 assert_eq!(Name::new("CNT_INC", 12).as_str(), "CNT_INC");
104 assert_eq!(Name::new("Tmr Svc", 12).as_str(), "Tmr Svc");
105 assert_eq!(Name::new("IDLE", 12).as_str(), "IDLE");
106 }
107
108 #[test]
109 fn long_names_truncate_like_the_c_kernel() {
110 assert_eq!(Name::new("ABCDEFGHIJKLMNOP", 12).as_str(), "ABCDEFGHIJK");
112 assert_eq!(Name::new("ABCDEFGHIJKLMNOP", 12).len(), 11);
113 }
114
115 #[test]
116 fn degenerate_limits_are_errors_not_panics() {
117 assert!(Name::new("anything", 0).is_empty());
118 assert!(Name::new("anything", 1).is_empty());
119 assert_eq!(Name::new("anything", 2).as_str(), "a");
120 assert_eq!(Name::new("", 12).as_str(), "");
121 }
122
123 #[test]
124 fn a_name_longer_than_the_capacity_is_capped() {
125 let long = "x".repeat(NAME_CAPACITY * 2);
126 let n = Name::new(&long, usize::MAX);
127 assert_eq!(n.len(), NAME_CAPACITY);
128 }
129}