rusty_rtos_kernel_core/name.rs
1//! A task's name, stored the way the C kernel stores it.
2//!
3//! `prvInitialiseNewTask` copies at most `configMAX_TASK_NAME_LEN`
4//! characters into the TCB and writes a NUL at the last index, so a longer
5//! name is silently truncated and the trace prints the truncated form. A
6//! `&'static str` would have been simpler and wrong: the oracle's line for a
7//! long name is the truncated one, and the diff is the gate.
8
9use core::fmt;
10use core::str;
11
12/// The largest `configMAX_TASK_NAME_LEN` this build supports.
13///
14/// The C default is 16 and the `Posix_GCC` demo uses 12; a configuration
15/// asking for more than this is refused by [`Name::new`] rather than
16/// truncated silently at a limit nobody wrote down.
17pub const NAME_CAPACITY: usize = 32;
18
19/// A task name: at most [`NAME_CAPACITY`] bytes, truncated to the
20/// configuration's `MAX_TASK_NAME_LEN` exactly as C truncates it.
21#[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 /// Copy `name`, truncated the way `prvInitialiseNewTask` truncates:
38 /// at most `max_len - 1` bytes, because the C array's last slot is the
39 /// NUL. `max_len` of 0 yields an empty name, as C's loop would.
40 ///
41 /// Truncation happens on a character boundary, so the result is always
42 /// valid UTF-8 — C truncates on a byte, but every name in the corpus is
43 /// ASCII and a name that is not is a configuration error, not a silent
44 /// mojibake.
45 #[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 // Walk back to a character boundary; for ASCII this is `limit`.
49 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 /// The name as it will be printed.
65 ///
66 /// In line on purpose, and with the clamp below: a trace prints two
67 /// names on every context switch, and out of line each one paid a call
68 /// and a frame to hand back a slice of a field the caller already had.
69 #[must_use]
70 #[inline(always)]
71 pub fn as_str(&self) -> &str {
72 // `Name::new` is the only constructor and it writes a `len` no
73 // larger than the buffer, so the clamp changes no value. It says so
74 // to the compiler, which otherwise carries a bounds check and an
75 // `Option` into every read of a name -- and a trace prints two of
76 // them on every context switch.
77 let end = usize::from(self.len).min(NAME_CAPACITY);
78 // Validate a WINDOW, not the used prefix.
79 //
80 // `run_utf8_validation` only reaches its word-at-a-time ASCII path
81 // when two `usize`s remain, so an eleven-byte task name -- which is
82 // every name in this corpus -- is checked a byte at a time. The
83 // profile put `from_utf8` at 9,776,286 instructions over 113,645
84 // calls, 86 each, and that is where they went.
85 //
86 // Sixteen bytes is the smallest window that reaches the fast path.
87 // The answer is unchanged because the tail is NULs: `Name::new`
88 // starts from a zeroed array and writes only a prefix, `Default` is
89 // all zeros, `bytes` is private and nothing else writes it. A NUL
90 // is valid UTF-8, so widening the check cannot change its verdict.
91 const WINDOW: usize = 16;
92 let window = if end <= WINDOW { WINDOW } else { NAME_CAPACITY };
93 match str::from_utf8(self.bytes.get(..window).unwrap_or(&[])) {
94 // Every byte is ASCII or NUL, so `end` is a character boundary
95 // and this is a length test rather than a scan.
96 Ok(all) => all.get(..end).unwrap_or(""),
97 Err(_) => "",
98 }
99 }
100
101 /// How many bytes the name occupies.
102 #[must_use]
103 pub const fn len(&self) -> usize {
104 self.len as usize
105 }
106
107 /// Whether the name is empty.
108 #[must_use]
109 pub const fn is_empty(&self) -> bool {
110 self.len == 0
111 }
112}
113
114impl fmt::Debug for Name {
115 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
116 fmt::Debug::fmt(self.as_str(), f)
117 }
118}
119
120impl fmt::Display for Name {
121 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
122 f.write_str(self.as_str())
123 }
124}
125
126#[cfg(test)]
127mod tests {
128 use super::*;
129
130 #[test]
131 fn short_names_survive_whole() {
132 assert_eq!(Name::new("CNT_INC", 12).as_str(), "CNT_INC");
133 assert_eq!(Name::new("Tmr Svc", 12).as_str(), "Tmr Svc");
134 assert_eq!(Name::new("IDLE", 12).as_str(), "IDLE");
135 }
136
137 #[test]
138 fn long_names_truncate_like_the_c_kernel() {
139 // configMAX_TASK_NAME_LEN counts the NUL, so 12 keeps 11 characters.
140 assert_eq!(Name::new("ABCDEFGHIJKLMNOP", 12).as_str(), "ABCDEFGHIJK");
141 assert_eq!(Name::new("ABCDEFGHIJKLMNOP", 12).len(), 11);
142 }
143
144 #[test]
145 fn degenerate_limits_are_errors_not_panics() {
146 assert!(Name::new("anything", 0).is_empty());
147 assert!(Name::new("anything", 1).is_empty());
148 assert_eq!(Name::new("anything", 2).as_str(), "a");
149 assert_eq!(Name::new("", 12).as_str(), "");
150 }
151
152 /// `as_str` validates a sixteen-byte window and slices the answer out
153 /// of it, which is only right while the bytes past `len` stay valid
154 /// UTF-8. They are NULs today because `new` starts from a zeroed array
155 /// and writes only a prefix. Pin that: a `new` that left the tail dirty
156 /// would make `as_str` answer `""` for every name, and the conformance
157 /// gate would report a diff in twenty-two scenarios at once with no
158 /// clue which line caused it.
159 #[test]
160 fn the_tail_stays_valid_so_as_str_can_check_a_whole_window() {
161 for (text, limit) in [("StrTrig", 12), ("", 12), ("a", 2), ("IDLE", 12)] {
162 let n = Name::new(text, limit);
163 assert!(
164 str::from_utf8(n.bytes.get(..16).unwrap_or(&[])).is_ok(),
165 "the sixteen-byte window must be valid UTF-8, not just the prefix"
166 );
167 assert!(
168 n.bytes
169 .get(n.len()..)
170 .unwrap_or(&[])
171 .iter()
172 .all(|b| *b == 0),
173 "the tail past `len` must be NUL"
174 );
175 }
176 // And the window widens when the name fills it.
177 let long = Name::new("ABCDEFGHIJKLMNOPQRSTUVWXYZ", NAME_CAPACITY);
178 assert!(long.len() > 16, "this case must exercise the wide window");
179 assert_eq!(long.as_str(), "ABCDEFGHIJKLMNOPQRSTUVWXYZ");
180 }
181
182 #[test]
183 fn a_name_longer_than_the_capacity_is_capped() {
184 let long = "x".repeat(NAME_CAPACITY * 2);
185 let n = Name::new(&long, usize::MAX);
186 assert_eq!(n.len(), NAME_CAPACITY);
187 }
188}