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
use crate::fs::path::Path;
use crate::fs::SEPARATOR;
use crate::{CStr16, CString16, Char16};
use core::fmt::{Display, Formatter};

/// A path buffer similar to the `PathBuf` of the standard library, but based on
/// [`CString16`] strings and [`SEPARATOR`] as separator.
///
/// `/` is replaced by [`SEPARATOR`] on the fly.
#[derive(Clone, Debug, Default, Eq, PartialOrd, Ord)]
pub struct PathBuf(CString16);

impl PathBuf {
    /// Constructor.
    #[must_use]
    pub fn new() -> Self {
        Self::default()
    }

    /// Constructor that replaces all occurrences of `/` with `\`.
    fn new_from_cstring16(mut string: CString16) -> Self {
        const SEARCH: Char16 = unsafe { Char16::from_u16_unchecked('/' as u16) };
        string.replace_char(SEARCH, SEPARATOR);
        Self(string)
    }

    /// Extends self with path.
    ///
    /// UNIX separators (`/`) will be replaced by [`SEPARATOR`] on the fly.
    pub fn push<P: AsRef<Path>>(&mut self, path: P) {
        const SEARCH: Char16 = unsafe { Char16::from_u16_unchecked('/' as u16) };

        // do nothing on empty path
        if path.as_ref().is_empty() {
            return;
        }

        let empty = self.0.is_empty();
        let needs_sep = *self
            .0
            .as_slice_with_nul()
            .last()
            .expect("Should have at least null character")
            != SEPARATOR;
        if !empty && needs_sep {
            self.0.push(SEPARATOR)
        }

        self.0.push_str(path.as_ref().to_cstr16());
        self.0.replace_char(SEARCH, SEPARATOR);
    }
}

impl PartialEq for PathBuf {
    fn eq(&self, other: &Self) -> bool {
        let path1: &Path = self.as_ref();
        let path2: &Path = other.as_ref();
        path1 == path2
    }
}

impl Display for PathBuf {
    fn fmt(&self, f: &mut Formatter<'_>) -> core::fmt::Result {
        Display::fmt(self.to_cstr16(), f)
    }
}

mod convenience_impls {
    use super::*;
    use core::borrow::Borrow;
    use core::ops::Deref;

    impl From<CString16> for PathBuf {
        fn from(value: CString16) -> Self {
            Self::new_from_cstring16(value)
        }
    }

    impl From<&CStr16> for PathBuf {
        fn from(value: &CStr16) -> Self {
            Self::new_from_cstring16(CString16::from(value))
        }
    }

    impl Deref for PathBuf {
        type Target = Path;

        fn deref(&self) -> &Self::Target {
            Path::new(&self.0)
        }
    }

    impl AsRef<Path> for PathBuf {
        fn as_ref(&self) -> &Path {
            // falls back to deref impl
            self
        }
    }

    impl Borrow<Path> for PathBuf {
        fn borrow(&self) -> &Path {
            // falls back to deref impl
            self
        }
    }

    impl AsRef<CStr16> for PathBuf {
        fn as_ref(&self) -> &CStr16 {
            &self.0
        }
    }

    impl Borrow<CStr16> for PathBuf {
        fn borrow(&self) -> &CStr16 {
            &self.0
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::cstr16;
    use alloc::string::ToString;

    #[test]
    fn from_cstr16() {
        let source: &CStr16 = cstr16!("\\hello\\foo\\bar");
        let _path: PathBuf = source.into();
    }

    #[test]
    fn from_cstring16() {
        let source = CString16::try_from("\\hello\\foo\\bar").unwrap();
        let _path: PathBuf = source.as_ref().into();
        let _path: PathBuf = source.clone().into();
        let _path: PathBuf = PathBuf::new_from_cstring16(source);
    }

    #[test]
    fn from_std_string() {
        let std_string = "\\hello\\foo\\bar".to_string();
        let _path = PathBuf::new_from_cstring16(CString16::try_from(std_string.as_str()).unwrap());
    }

    #[test]
    fn push() {
        let mut pathbuf = PathBuf::new();
        pathbuf.push(cstr16!("first"));
        pathbuf.push(cstr16!("second"));
        pathbuf.push(cstr16!("third"));
        assert_eq!(pathbuf.to_cstr16(), cstr16!("first\\second\\third"));

        let mut pathbuf = PathBuf::new();
        pathbuf.push(cstr16!("\\first"));
        pathbuf.push(cstr16!("second"));
        assert_eq!(pathbuf.to_cstr16(), cstr16!("\\first\\second"));

        // empty pushes should be ignored and have no effect
        let empty_cstring16 = CString16::try_from("").unwrap();
        let mut pathbuf = PathBuf::new();
        pathbuf.push(cstr16!("first"));
        pathbuf.push(empty_cstring16.as_ref());
        pathbuf.push(empty_cstring16.as_ref());
        pathbuf.push(empty_cstring16.as_ref());
        pathbuf.push(cstr16!("second"));
        assert_eq!(pathbuf.to_cstr16(), cstr16!("first\\second"));
    }

    #[test]
    fn partial_eq() {
        let mut pathbuf1 = PathBuf::new();
        pathbuf1.push(cstr16!("first"));
        pathbuf1.push(cstr16!("second"));
        pathbuf1.push(cstr16!("third"));

        assert_eq!(pathbuf1, pathbuf1);

        let mut pathbuf2 = PathBuf::new();
        pathbuf2.push(cstr16!("\\first"));
        pathbuf2.push(cstr16!("second"));

        assert_eq!(pathbuf2, pathbuf2);
        assert_ne!(pathbuf1, pathbuf2);
    }
}