1pub const MAX_NAME: usize = 255;
3
4#[derive(Clone, Copy)]
8pub struct Name {
9 bytes: [u8; MAX_NAME],
10 len: u8,
11}
12
13impl Name {
14 pub const fn empty() -> Self {
16 Self {
17 bytes: [0; MAX_NAME],
18 len: 0,
19 }
20 }
21
22 pub fn as_str(&self) -> &str {
24 core::str::from_utf8(&self.bytes[..self.len as usize]).unwrap_or("")
25 }
26
27 pub fn is_empty(&self) -> bool {
29 self.len == 0
30 }
31
32 pub fn eq_ignore_ascii_case(&self, other: &str) -> bool {
34 self.as_str().eq_ignore_ascii_case(other)
35 }
36
37 #[cfg(feature = "fat32")]
38 pub(crate) fn push_byte(&mut self, byte: u8) -> Result<(), ()> {
39 if self.len as usize >= MAX_NAME {
40 return Err(());
41 }
42 self.bytes[self.len as usize] = byte;
43 self.len += 1;
44 Ok(())
45 }
46
47 pub(crate) fn push_char(&mut self, c: char) -> Result<(), ()> {
48 let mut buffer = [0u8; 4];
49 let encoded = c.encode_utf8(&mut buffer);
50 let start = self.len as usize;
51 if start + encoded.len() > MAX_NAME {
52 return Err(());
53 }
54 self.bytes[start..start + encoded.len()].copy_from_slice(encoded.as_bytes());
55 self.len += encoded.len() as u8;
56 Ok(())
57 }
58}
59
60impl core::fmt::Debug for Name {
61 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
62 f.debug_tuple("Name").field(&self.as_str()).finish()
63 }
64}
65
66#[cfg(feature = "write")]
69pub(crate) fn is_valid_name(name: &str) -> bool {
70 if name.is_empty() || name.encode_utf16().count() > MAX_NAME {
71 return false;
72 }
73 if name.ends_with(' ') || name.ends_with('.') {
74 return false;
75 }
76 !name
77 .chars()
78 .any(|c| (c as u32) < 0x20 || "\\/:*?\"<>|".contains(c))
79}
80
81#[cfg(feature = "write")]
84pub(crate) fn check_name<E>(name: &str) -> Result<(), crate::Error<E>> {
85 if name.len() > MAX_NAME {
86 return Err(crate::Error::NameTooLong);
87 }
88 if !is_valid_name(name) {
89 return Err(crate::Error::InvalidName);
90 }
91 Ok(())
92}