bare_types/sys/
username.rs1use core::fmt;
28use core::str::FromStr;
29
30#[cfg(feature = "serde")]
31use serde::{Deserialize, Serialize};
32
33#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
36#[non_exhaustive]
37pub enum UsernameError {
38 Empty,
42 TooLong(usize),
47 InvalidFirstCharacter,
52 InvalidCharacter,
57}
58
59impl fmt::Display for UsernameError {
60 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
61 match self {
62 Self::Empty => write!(f, "username cannot be empty"),
63 Self::TooLong(len) => write!(f, "username too long (got {len}, max 32 characters)"),
64 Self::InvalidFirstCharacter => {
65 write!(f, "username must start with a letter or underscore")
66 }
67 Self::InvalidCharacter => write!(f, "username contains invalid character"),
68 }
69 }
70}
71
72#[cfg(feature = "std")]
73impl std::error::Error for UsernameError {}
74
75#[repr(transparent)]
80#[derive(Debug, Clone, PartialEq, Eq, Hash)]
81#[cfg_attr(feature = "serde", derive(Serialize, Deserialize))]
82pub struct Username(heapless::String<32>);
83
84impl Username {
85 pub const MAX_LEN: usize = 32;
87
88 pub fn new(s: &str) -> Result<Self, UsernameError> {
94 Self::validate(s)?;
95 let mut value = heapless::String::new();
96 value
97 .push_str(s)
98 .map_err(|_| UsernameError::TooLong(s.len()))?;
99 Ok(Self(value))
100 }
101
102 fn validate(s: &str) -> Result<(), UsernameError> {
104 if s.is_empty() {
105 return Err(UsernameError::Empty);
106 }
107 if s.len() > Self::MAX_LEN {
108 return Err(UsernameError::TooLong(s.len()));
109 }
110 let mut chars = s.chars();
111 if let Some(first) = chars.next() {
112 if !first.is_ascii_alphabetic() && first != '_' {
113 return Err(UsernameError::InvalidFirstCharacter);
114 }
115 }
116 for ch in chars {
117 if !ch.is_ascii_alphanumeric() && ch != '_' && ch != '-' {
118 return Err(UsernameError::InvalidCharacter);
119 }
120 }
121 Ok(())
122 }
123
124 #[must_use]
126 #[inline]
127 pub fn as_str(&self) -> &str {
128 &self.0
129 }
130
131 #[must_use]
133 #[inline]
134 pub const fn as_inner(&self) -> &heapless::String<32> {
135 &self.0
136 }
137
138 #[must_use]
140 #[inline]
141 pub fn into_inner(self) -> heapless::String<32> {
142 self.0
143 }
144
145 #[must_use]
149 pub fn is_system_user(&self) -> bool {
150 self.0.starts_with('_') || self.0 == "root" || self.0 == "daemon"
151 }
152
153 #[must_use]
157 pub fn is_service_account(&self) -> bool {
158 self.0.starts_with("svc-") || self.0.starts_with("service-")
159 }
160}
161
162impl AsRef<str> for Username {
163 fn as_ref(&self) -> &str {
164 self.as_str()
165 }
166}
167
168impl TryFrom<&str> for Username {
169 type Error = UsernameError;
170
171 fn try_from(s: &str) -> Result<Self, Self::Error> {
172 Self::new(s)
173 }
174}
175
176impl FromStr for Username {
177 type Err = UsernameError;
178
179 fn from_str(s: &str) -> Result<Self, Self::Err> {
180 Self::new(s)
181 }
182}
183
184impl fmt::Display for Username {
185 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
186 write!(f, "{}", self.0)
187 }
188}
189
190#[cfg(feature = "arbitrary")]
191impl<'a> arbitrary::Arbitrary<'a> for Username {
192 fn arbitrary(u: &mut arbitrary::Unstructured<'a>) -> arbitrary::Result<Self> {
193 const ALPHABET: &[u8] = b"abcdefghijklmnopqrstuvwxyz";
194 const DIGITS: &[u8] = b"0123456789";
195
196 let len = 1 + (u8::arbitrary(u)? % 32).min(31);
198 let mut inner = heapless::String::<32>::new();
199
200 let first_byte = u8::arbitrary(u)?;
202 if first_byte % 10 == 0 {
203 inner
205 .push('_')
206 .map_err(|_| arbitrary::Error::IncorrectFormat)?;
207 } else {
208 let first = ALPHABET[(first_byte % 26) as usize] as char;
209 inner
210 .push(first)
211 .map_err(|_| arbitrary::Error::IncorrectFormat)?;
212 }
213
214 for _ in 1..len {
216 let byte = u8::arbitrary(u)?;
217 let c = match byte % 4 {
218 0 => ALPHABET[((byte >> 2) % 26) as usize] as char,
219 1 => DIGITS[((byte >> 2) % 10) as usize] as char,
220 2 => '_',
221 _ => '-',
222 };
223 inner
224 .push(c)
225 .map_err(|_| arbitrary::Error::IncorrectFormat)?;
226 }
227
228 Ok(Self(inner))
229 }
230}
231
232#[cfg(test)]
233mod tests {
234 use super::*;
235
236 #[test]
237 fn test_new_valid() {
238 let username = Username::new("root").unwrap();
239 assert_eq!(username.as_str(), "root");
240 }
241
242 #[test]
243 fn test_new_empty() {
244 assert!(matches!(Username::new(""), Err(UsernameError::Empty)));
245 }
246
247 #[test]
248 fn test_new_too_long() {
249 let long_name = "a".repeat(33);
250 assert!(matches!(
251 Username::new(&long_name),
252 Err(UsernameError::TooLong(33))
253 ));
254 }
255
256 #[test]
257 fn test_new_invalid_first_character() {
258 assert!(matches!(
259 Username::new("1root"),
260 Err(UsernameError::InvalidFirstCharacter)
261 ));
262 assert!(matches!(
263 Username::new("-root"),
264 Err(UsernameError::InvalidFirstCharacter)
265 ));
266 }
267
268 #[test]
269 fn test_new_invalid_character() {
270 assert!(matches!(
271 Username::new("root@"),
272 Err(UsernameError::InvalidCharacter)
273 ));
274 assert!(matches!(
275 Username::new("root.user"),
276 Err(UsernameError::InvalidCharacter)
277 ));
278 }
279
280 #[test]
281 fn test_is_system_user() {
282 let root = Username::new("root").unwrap();
283 assert!(root.is_system_user());
284 let daemon = Username::new("daemon").unwrap();
285 assert!(daemon.is_system_user());
286 let system = Username::new("_system").unwrap();
287 assert!(system.is_system_user());
288 let user = Username::new("user").unwrap();
289 assert!(!user.is_system_user());
290 }
291
292 #[test]
293 fn test_is_service_account() {
294 let svc = Username::new("svc-api").unwrap();
295 assert!(svc.is_service_account());
296 let service = Username::new("service-api").unwrap();
297 assert!(service.is_service_account());
298 let user = Username::new("user").unwrap();
299 assert!(!user.is_service_account());
300 }
301
302 #[test]
303 fn test_from_str() {
304 let username: Username = "root".parse().unwrap();
305 assert_eq!(username.as_str(), "root");
306 }
307
308 #[test]
309 fn test_from_str_error() {
310 assert!("".parse::<Username>().is_err());
311 assert!("1root".parse::<Username>().is_err());
312 }
313
314 #[test]
315 fn test_display() {
316 let username = Username::new("root").unwrap();
317 assert_eq!(format!("{}", username), "root");
318 }
319
320 #[test]
321 fn test_as_ref() {
322 let username = Username::new("root").unwrap();
323 let s: &str = username.as_ref();
324 assert_eq!(s, "root");
325 }
326
327 #[test]
328 fn test_clone() {
329 let username = Username::new("root").unwrap();
330 let username2 = username.clone();
331 assert_eq!(username, username2);
332 }
333
334 #[test]
335 fn test_equality() {
336 let u1 = Username::new("root").unwrap();
337 let u2 = Username::new("root").unwrap();
338 let u3 = Username::new("user").unwrap();
339 assert_eq!(u1, u2);
340 assert_ne!(u1, u3);
341 }
342
343 #[test]
344 fn test_as_inner() {
345 let username = Username::new("root").unwrap();
346 let inner = username.as_inner();
347 assert_eq!(inner.as_str(), "root");
348 }
349
350 #[test]
351 fn test_into_inner() {
352 let username = Username::new("root").unwrap();
353 let inner = username.into_inner();
354 assert_eq!(inner.as_str(), "root");
355 }
356}