1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
// Temporary while this code is being fleshed out.
#![allow(dead_code)]
use core::str;

use crate::util;

// .:?/\a
// &['\\', '/', '.', '?', ':', 'T', '£', '三', '😍']

/// Parse the prefix from a path.
pub struct ParsedUtf8Path<'a> {
    path: &'a str,
    kind: WinPathKind,
    prefix_len: usize,
}
impl<'a> ParsedUtf8Path<'a> {
    /// Parse a UTF-8 string into a prefix and subpath..
    pub fn from_utf8(path: &'a str) -> ParsedUtf8Path<'a> {
        let (kind, len) = WinPathKind::from_str_with_len(path);
        Self {
            path,
            kind,
            prefix_len: match kind {
                WinPathKind::Unc => len + str_unc_prefix_len(&path[len..]),
                _ => len,
            },
        }
    }

    /// Get the original, unparsed path.
    pub fn as_utf8(&self) -> &str {
        self.path
    }

    /// Get the type of path.
    pub const fn kind(&self) -> WinPathKind {
        self.kind
    }

    /// Normalize the kind
    pub fn normalized_str_kind(&self) -> NormalizedStrKind {
        match self.kind() {
            WinPathKind::DriveRelative(_) => {
                let mut buffer = [0; 4];
                buffer[..self.prefix_len].copy_from_slice(&self.path.as_bytes()[..self.prefix_len]);
                NormalizedStrKind { buffer, len: self.prefix_len }
            }
            WinPathKind::Drive(_) => {
                let mut buffer = [0; 4];
                buffer[..self.prefix_len].copy_from_slice(&self.path.as_bytes()[..self.prefix_len]);
                buffer[self.prefix_len - 1] = b'\\';
                NormalizedStrKind { buffer, len: self.prefix_len }
            }
            WinPathKind::Verbatim => NormalizedStrKind { buffer: *br"\\?\", len: 4 },
            WinPathKind::Device => {
                // Preserves the `.` or `?`.
                // Maybe we should normalize this as `.` even if that's not what the OS does.
                let mut buffer = [b'\\'; 4];
                buffer[2] = self.path.as_bytes()[2];
                NormalizedStrKind { buffer, len: 4 }
            }
            WinPathKind::CurrentDirectoryRelative => NormalizedStrKind { buffer: [0; 4], len: 0 },
            WinPathKind::RootRelative => NormalizedStrKind { buffer: [b'\\', 0, 0, 0], len: 1 },
            WinPathKind::Unc => NormalizedStrKind { buffer: [b'\\', b'\\', 0, 0], len: 2 },
        }
    }

    /// Returns the (prefix, subpath) pair.
    pub fn parts<'b>(&'b self) -> (&'a str, &'a str)
    where
        'a: 'b,
    {
        self.path.split_at(self.prefix_len)
    }
}

pub struct NormalizedStrKind {
    buffer: [u8; 4],
    len: usize,
}
impl NormalizedStrKind {
    pub fn as_str(&self) -> &str {
        str::from_utf8(&self.buffer[..self.len]).unwrap()
    }
}

/// Parse the server and share name from the path.
///
/// This assumes the leading `\\` has already be parsed.
fn str_unc_prefix_len(path: &str) -> usize {
    let mut iter = path.as_bytes().iter();
    match iter.position(|&c| c == b'\\' || c == b'/') {
        Some(pos) => iter.position(|&c| c == b'\\' || c == b'/').map(|n| pos + n + 1),
        None => None,
    }
    .unwrap_or(path.len())
}

/// Windows path type.
///
/// This does not do any validation so parsing the kind will never fail,
/// even for broken or invalid paths.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum WinPathKind {
    /// A traditional drive path such as `C:\`, `R:\`, etc.
    Drive(u16),
    /// A path to a network directory such as `\\server\share\`.
    Unc,
    /// A device path such as `\\.\COM1`.
    Device,
    /// A path that's relative to the current directory.
    CurrentDirectoryRelative,

    /// A path that is passed to the NT kernel without parsing, except to change
    /// the prefix.
    ///
    /// These start with `\\?\`, avoid DOS path length limits and can contain
    /// paths that are otherwise illegal.
    Verbatim,

    /// A DOS drive relative path (e.g. `C:file`).
    DriveRelative(u16),
    /// A DOS root relative path (e.g. `\file`).
    ///
    /// Note that some Windows APIs can return paths that are relative to a
    /// specified drive. These may start with a `\` but should be joined to the
    /// drive path instead of being treated like a DOS `RootRelative` path.
    RootRelative,
}

impl WinPathKind {
    /// Split the path into `WinPathKind` and the rest of the path.
    ///
    /// Note that this only splits off the smallest part needed to identify the
    /// path type. E.g. the UNC path `\\server\share\file.txt` will be split
    /// as `(WinPathKind::Unc, "server\share\file.txt")`.
    pub const fn split_str(path: &str) -> (Self, &str) {
        let (kind, len) = Self::from_str_with_len(path);
        // SAFETY: Splitting the str only happens after an ASCII character.
        let rest = unsafe { util::trim_start_str(path, len) };
        (kind, rest)
    }

    pub(crate) const fn from_str_with_len(path: &str) -> (Self, usize) {
        let kind = Self::from_str(path);
        let len = match kind {
            Self::Drive(_) | Self::DriveRelative(_) => {
                kind.utf16_len() - 1 + (util::utf8_len(path.as_bytes()[0]) as usize)
            }
            _ => kind.utf16_len(),
        };
        (kind, len)
    }

    /// Examine the path prefix to find the type of the path given.
    pub const fn from_str(path: &str) -> Self {
        let bytes = path.as_bytes();

        if bytes.is_empty() {
            return WinPathKind::CurrentDirectoryRelative;
        }

        // If the path starts with `\\?\` then it's a verbatim path.
        // Note that this is an exact match. `//?/` is not a verbatim path.
        if let [b'\\', b'\\', b'?', b'\\', ..] = bytes {
            return Self::Verbatim;
        }
        if is_verbatim_str(path) {
            return Self::Verbatim;
        }

        match util::utf8_len(bytes[0]) {
            // If the first Unicode scalar would need more than one UTF-16 code unit
            // then this must be a relative path because it won't match any prefix.
            4.. => Self::CurrentDirectoryRelative,
            // If this first Unicode scalar is not ascii then this can only be
            // Drive, DriveRelative or Relative.
            n @ 2.. => {
                match_pattern! {
                    util::trim_start(bytes, n);
                    [':', /, ..] => Self::Drive(util::bmp_utf8_to_utf16(bytes)),
                    [':', ..] => Self::DriveRelative(util::bmp_utf8_to_utf16(bytes)),
                    _ => Self::CurrentDirectoryRelative
                }
            }
            // If this first Unicode scalar is ascii then it could be any type.
            // Warning: The order of these matches is super important.
            // You can't take a pattern out of this context without modification.
            _ => match_pattern! {
                bytes;
                // `\\.\` | `\\?\`
                [/, /, '.', /, ..] => Self::Device,
                // `\\`
                [/, /, ..] => Self::Unc,
                // `\`
                [/, ..] => Self::RootRelative,
                // `C:\`
                [_, ':', /, ..] => Self::Drive(bytes[0] as u16),
                // `C:`
                [_, ':', ..] => Self::DriveRelative(bytes[0] as u16),
                // Anything else
                _ => Self::CurrentDirectoryRelative
            },
        }
    }

    /// Is the path absolute. Being absolute means it doesn't need to be joined
    /// to a base path (e.g. the current directory, or a drive current directory)
    pub const fn is_absolute(self) -> bool {
        matches!(self, Self::Drive(_) | Self::Unc | Self::Device | Self::Verbatim)
    }

    /// Returns the relative path kind or `None` for absolute paths.
    pub const fn as_relative(self) -> Option<Win32Relative> {
        Win32Relative::from_kind(self)
    }

    /// Is the path one of the weird ones from DOS.
    ///
    /// These should probably be considered invalid if given from a configuration file
    /// but you may want to support them if given through command line arguments
    /// (e.g. because they come from the command prompt or a bat file).
    pub const fn is_legacy_relative(self) -> bool {
        matches!(self, Self::DriveRelative(_) | Self::RootRelative)
    }

    /// The number of UTF-16 code units that make up the path kind.
    pub const fn utf16_len(self) -> usize {
        match self {
            Self::Drive(_) => r"C:\".len(),
            Self::Unc => r"\\".len(),
            Self::Device => r"\\.\".len(),
            Self::CurrentDirectoryRelative => "".len(),
            Self::Verbatim => r"\\?\".len(),
            Self::DriveRelative(_) => "C:".len(),
            Self::RootRelative => r"\".len(),
        }
    }

    /// The number of UTF-8 code units that make up the path kind.
    pub const fn utf8_len(self) -> usize {
        const fn drive_utf8_len(drive: u16) -> usize {
            if drive > 0x7F {
                2
            } else {
                1
            }
        }
        match self {
            Self::Drive(drive) => drive_utf8_len(drive) + r":\".len(),
            Self::Unc => r"\\".len(),
            Self::Device => r"\\.\".len(),
            Self::CurrentDirectoryRelative => "".len(),
            Self::Verbatim => r"\\?\".len(),
            Self::DriveRelative(drive) => drive_utf8_len(drive) + ":".len(),
            Self::RootRelative => r"\".len(),
        }
    }
}

/// The type of relative path.
#[derive(Debug, Clone, Copy)]
pub enum Win32Relative {
    CurrentDirectory,
    DriveRelative(u16),
    Root,
}
impl Win32Relative {
    pub const fn from_kind(kind: WinPathKind) -> Option<Self> {
        match kind {
            WinPathKind::CurrentDirectoryRelative => Some(Self::CurrentDirectory),
            WinPathKind::DriveRelative(drive) => Some(Self::DriveRelative(drive)),
            WinPathKind::RootRelative => Some(Self::Root),
            _ => None,
        }
    }

    /// Is the path one of the weird ones from DOS.
    ///
    /// These should probably be considered invalid if given from a configuration file
    /// but you may want to support them if given through command line arguments
    /// (e.g. because they come from the command prompt or a bat file).
    pub const fn is_legacy_relative(self) -> bool {
        matches!(self, Self::DriveRelative(_) | Self::Root)
    }
}

/// The type of non-verbatim absolute path.
#[derive(Debug, Clone, Copy)]
pub enum Win32Absolute {
    Drive(u16),
    Unc,
    Device,
}
impl Win32Absolute {
    /// Verbatim paths will return `None`.
    pub const fn from_kind(kind: WinPathKind) -> Option<Self> {
        match kind {
            WinPathKind::Drive(drive) => Some(Self::Drive(drive)),
            WinPathKind::Unc => Some(Self::Unc),
            WinPathKind::Device => Some(Self::Device),
            _ => None,
        }
    }

    /// Get the Win32 type of a verbatim path.
    pub(crate) const fn from_verbatim_str(path: &str) -> Result<(Self, &str), ()> {
        let verbatim = match VerbatimStr::new(path) {
            Ok(verbatim) => verbatim,
            Err(e) => return Err(e),
        };
        let kind = verbatim.win32_kind();
        let rest = match kind {
            Win32Absolute::Unc => unsafe { util::trim_start_str(verbatim.path, "UNC".len()) },
            _ => verbatim.path,
        };
        Ok((kind, rest))
    }
}

pub struct VerbatimStr<'a> {
    path: &'a str,
}
impl<'a> VerbatimStr<'a> {
    const fn new(path: &'a str) -> Result<Self, ()> {
        match WinPathKind::split_str(path) {
            (WinPathKind::Verbatim, rest) => Ok(Self { path: rest }),
            _ => Err(()),
        }
    }
    const fn win32_kind(&self) -> Win32Absolute {
        // C:\, \\.\, \\
        match self.path.as_bytes() {
            // UNC\
            // Canonically `UNC` is uppercase but maybe we should ignore case here.
            [b'U', b'N', b'C', b'\\', ..] | [b'U', b'N', b'C'] => Win32Absolute::Unc,
            // C:\
            [d, b':', b'\\', ..] | [d, b':'] => Win32Absolute::Drive(*d as u16),
            [d1, d2, b':', b'\\', ..] | [d1, d2, b':'] => {
                let drive = util::bmp_utf8_to_utf16(&[*d1, *d2]);
                Win32Absolute::Drive(drive)
            }
            // Anything else is used as a device path.
            _ => Win32Absolute::Device,
        }
    }
}

#[inline]
pub const fn is_verbatim_str(path: &str) -> bool {
    matches!(path.as_bytes(), [b'\\', b'\\', b'?', b'\\', ..])
}