Skip to main content

file_storage/path/system/
is_windows.rs

1use crate::StoragePath;
2
3impl StoragePath {
4    //! Is Windows
5
6    /// Checks if the path is a Windows path.
7    pub fn is_windows_path(&self) -> bool {
8        Self::is_windows_path_str(self.path())
9    }
10
11    /// Checks if the `path` is a Windows path.
12    ///
13    /// Matches drive letter paths (`C:\` or `C:/`) and UNC paths (`\\server\...`).
14    pub fn is_windows_path_str<S>(path: S) -> bool
15    where
16        S: AsRef<str>,
17    {
18        let path: &str = path.as_ref();
19        let bytes: &[u8] = path.as_bytes();
20        if bytes.len() < 3 {
21            return false;
22        }
23        let is_drive_letter: bool = bytes[0].is_ascii_alphabetic()
24            && bytes[1] == b':'
25            && (bytes[2] == b'\\' || bytes[2] == b'/');
26        let is_unc: bool =
27            bytes[0] == b'\\' && bytes[1] == b'\\' && bytes[2] != b'\\';
28        is_drive_letter || is_unc
29    }
30}
31
32#[cfg(test)]
33mod tests {
34    use crate::StoragePath;
35
36    #[test]
37    fn is_windows_path_str() {
38        // Drive letter paths.
39        assert!(StoragePath::is_windows_path_str("C:\\"));
40        assert!(StoragePath::is_windows_path_str("C:/"));
41        assert!(StoragePath::is_windows_path_str("D:\\folder\\file"));
42
43        // UNC paths.
44        assert!(StoragePath::is_windows_path_str("\\\\server\\share"));
45        assert!(StoragePath::is_windows_path_str("\\\\s\\share\\file"));
46
47        // Not Windows paths.
48        assert!(!StoragePath::is_windows_path_str("/unix/path"));
49        assert!(!StoragePath::is_windows_path_str("C:"));
50        assert!(!StoragePath::is_windows_path_str("\\\\\\bad"));
51        assert!(!StoragePath::is_windows_path_str("ab"));
52    }
53}