Skip to main content

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    #[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    /// How many bytes the name occupies.
73    #[must_use]
74    pub const fn len(&self) -> usize {
75        self.len as usize
76    }
77
78    /// Whether the name is empty.
79    #[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        // configMAX_TASK_NAME_LEN counts the NUL, so 12 keeps 11 characters.
111        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}