1#[derive(Copy, Clone, Debug, PartialEq, Eq)]
10pub struct Label {
11 bytes: [u8; Label::CAPACITY],
12 len: u8,
13}
14
15impl Label {
16 pub const CAPACITY: usize = 12;
19
20 pub const fn word(word: &[u8]) -> Self {
22 let mut bytes = [b' '; Self::CAPACITY];
23 let len = if word.len() < Self::CAPACITY {
24 word.len()
25 } else {
26 Self::CAPACITY
27 };
28 let mut at = 0;
29 while at < len {
30 bytes[at] = word[at];
31 at += 1;
32 }
33 Self {
34 bytes,
35 len: len as u8,
36 }
37 }
38
39 pub const fn toward(word: &[u8], steps: u8) -> Self {
42 let mut label = Self::word(word);
43 let mut at = label.len as usize;
44 let digits = if steps >= 100 {
46 3
47 } else if steps >= 10 {
48 2
49 } else {
50 1
51 };
52 if at + 1 + digits > Self::CAPACITY {
53 at = Self::CAPACITY - 1 - digits;
54 }
55 label.bytes[at] = b' ';
56 at += 1;
57 let mut place = digits;
58 let mut rest = steps;
59 while place > 0 {
60 place -= 1;
61 label.bytes[at + place] = b'0' + rest % 10;
62 rest /= 10;
63 }
64 label.len = (at + digits) as u8;
65 label
66 }
67
68 pub fn as_bytes(&self) -> &[u8] {
70 &self.bytes[..self.len as usize]
71 }
72
73 pub fn as_str(&self) -> &str {
76 let bytes = self.as_bytes();
77 if bytes.is_ascii() {
78 unsafe { core::str::from_utf8_unchecked(bytes) }
81 } else {
82 ""
83 }
84 }
85
86 pub const fn len(&self) -> usize {
88 self.len as usize
89 }
90
91 pub const fn is_empty(&self) -> bool {
93 self.len == 0
94 }
95
96 pub fn copy_into(&self, buf: &mut [u8; Self::CAPACITY]) -> usize {
99 *buf = self.bytes;
100 self.len as usize
101 }
102}
103
104#[cfg(test)]
105mod tests {
106 use super::Label;
107
108 #[test]
109 fn word_and_toward_build_the_row_text() {
110 assert_eq!(Label::word(b"DEFAULT").as_str(), "DEFAULT");
111 assert_eq!(Label::toward(b"DARKER", 3).as_str(), "DARKER 3");
112 assert_eq!(Label::toward(b"RIGHT", 16).as_str(), "RIGHT 16");
113 assert_eq!(Label::toward(b"LEFT", 0).as_str(), "LEFT 0");
114 }
115
116 #[test]
117 fn every_step_of_an_i8_fits() {
118 for steps in 0..=u8::MAX {
119 let label = Label::toward(b"BRIGHTER", steps);
120 let mut want = [0u8; 16];
121 let text = b"BRIGHTER ";
122 want[..text.len()].copy_from_slice(text);
123 let mut at = text.len();
124 let mut digits = [0u8; 3];
125 let mut n = 0;
126 let mut rest = steps;
127 loop {
128 digits[n] = b'0' + rest % 10;
129 n += 1;
130 rest /= 10;
131 if rest == 0 {
132 break;
133 }
134 }
135 while n > 0 {
136 n -= 1;
137 want[at] = digits[n];
138 at += 1;
139 }
140 assert_eq!(label.as_bytes(), &want[..at], "steps {steps}");
141 }
142 }
143
144 #[test]
145 fn copy_into_matches_the_bytes() {
146 let label = Label::toward(b"UP", 7);
147 let mut buf = [0u8; Label::CAPACITY];
148 let len = label.copy_into(&mut buf);
149 assert_eq!(&buf[..len], b"UP 7");
150 assert_eq!(len, label.len());
151 assert!(!label.is_empty());
152 }
153}