Skip to main content

sdmmc_async/
name.rs

1/// The longest name, in bytes.
2pub const MAX_NAME: usize = 255;
3
4/// A file or directory name, stored as UTF-8. FAT names are ASCII; exFAT names
5/// are UTF-16 and are transcoded. Names longer than `MAX_NAME` bytes are
6/// rejected rather than truncated.
7#[derive(Clone, Copy)]
8pub struct Name {
9    bytes: [u8; MAX_NAME],
10    len: u8,
11}
12
13impl Name {
14    /// A name with no characters.
15    pub const fn empty() -> Self {
16        Self {
17            bytes: [0; MAX_NAME],
18            len: 0,
19        }
20    }
21
22    /// The name as text.
23    pub fn as_str(&self) -> &str {
24        core::str::from_utf8(&self.bytes[..self.len as usize]).unwrap_or("")
25    }
26
27    /// Whether the name has no characters.
28    pub fn is_empty(&self) -> bool {
29        self.len == 0
30    }
31
32    /// Whether the name equals `other`, ignoring ASCII case.
33    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/// Whether `name` can be stored on FAT32 or exFAT at all: 1 to 255 UTF-16 units (a limit `check_name` tightens to bytes), no control characters or any of
67/// `\ / : * ? " < > |`, and no trailing space or dot.
68#[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/// The name checks of every operation that creates one: at most `MAX_NAME` bytes of UTF-8 (so that this crate can read
82/// back what it writes), and valid on both filesystems.
83#[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}