-
Notifications
You must be signed in to change notification settings - Fork 24
/
canon.rs
197 lines (177 loc) · 6.09 KB
/
canon.rs
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
//! Path canonicalization.
use std::mem::MaybeUninit;
/// An on-stack stack of values.
/// Used for tracking locations of parent components within a path.
struct StackStack<T> {
n: usize,
vals: [MaybeUninit<T>; 60],
}
impl<T: Copy> StackStack<T> {
fn new() -> Self {
StackStack {
n: 0,
// Safety: we only access vals[i] after setting it.
vals: unsafe { MaybeUninit::uninit().assume_init() },
}
}
fn push(&mut self, val: T) {
if self.n >= self.vals.len() {
panic!("too many path components");
}
self.vals[self.n].write(val);
self.n += 1;
}
fn pop(&mut self) -> Option<T> {
if self.n > 0 {
self.n -= 1;
// Safety: we only access vals[i] after setting it.
Some(unsafe { self.vals[self.n].assume_init() })
} else {
None
}
}
}
/// Lexically canonicalize a path, removing redundant components.
/// Does not access the disk, but only simplifies things like
/// "foo/./bar" => "foo/bar".
/// These paths can show up due to variable expansion in particular.
/// Returns the new length of the path, guaranteed <= the original length.
#[must_use]
pub fn canon_path_fast(path: &mut str) -> usize {
assert!(!path.is_empty());
// Safety: this traverses the path buffer to move data around.
// We maintain the invariant that *dst always points to a point within
// the buffer, and that src is always checked against end before reading.
unsafe {
let mut components = StackStack::<*mut u8>::new();
let mut dst = path.as_mut_ptr();
let mut src = path.as_ptr();
let start = path.as_mut_ptr();
let end = src.add(path.len());
if src == end {
return 0;
}
if *src == b'/' || *src == b'\\' {
src = src.add(1);
dst = dst.add(1);
}
// Outer loop: one iteration per path component.
while src < end {
// Peek ahead for special path components: "/", ".", and "..".
match *src {
b'/' | b'\\' => {
src = src.add(1);
continue;
}
b'.' => {
let mut peek = src.add(1);
if peek == end {
break; // Trailing '.', trim.
}
match *peek {
b'/' | b'\\' => {
// "./", skip.
src = src.add(2);
continue;
}
b'.' => {
// ".."
peek = peek.add(1);
if !(peek == end || *peek == b'/' || *peek == b'\\') {
// Componet that happens to start with "..".
// Handle as an ordinary component.
break;
}
// ".." component, try to back up.
if let Some(ofs) = components.pop() {
dst = ofs;
} else {
*dst = b'.';
dst = dst.add(1);
*dst = b'.';
dst = dst.add(1);
if peek != end {
*dst = *peek;
dst = dst.add(1);
}
}
src = src.add(3);
continue;
}
_ => {}
}
}
_ => {}
}
// Mark this point as a possible target to pop to.
components.push(dst);
// Inner loop: copy one path component, including trailing '/'.
while src < end {
*dst = *src;
src = src.add(1);
dst = dst.add(1);
if *src.offset(-1) == b'/' || *src.offset(-1) == b'\\' {
break;
}
}
}
if dst == start {
*start = b'.';
1
} else {
dst.offset_from(start) as usize
}
}
}
pub fn canon_path<T: Into<String>>(path: T) -> String {
let mut path = path.into();
let len = canon_path_fast(&mut path);
path.truncate(len);
path
}
#[cfg(test)]
mod tests {
use super::*;
// Assert that canon path equals expected path with different path separators
fn assert_canon_path_eq(left: &str, right: &str) {
assert_eq!(canon_path(left), right);
assert_eq!(
canon_path(left.replace('/', "\\")),
right.replace('/', "\\")
);
}
#[test]
fn noop() {
assert_canon_path_eq("foo", "foo");
assert_canon_path_eq("foo/bar", "foo/bar");
}
#[test]
fn dot() {
assert_canon_path_eq("./foo", "foo");
assert_canon_path_eq("foo/.", "foo/");
assert_canon_path_eq("foo/./bar", "foo/bar");
assert_canon_path_eq("./", ".");
assert_canon_path_eq("./.", ".");
assert_canon_path_eq("././", ".");
assert_canon_path_eq("././.", ".");
assert_canon_path_eq(".", ".");
}
#[test]
fn slash() {
assert_canon_path_eq("/foo", "/foo");
assert_canon_path_eq("foo//bar", "foo/bar");
}
#[test]
fn parent() {
assert_canon_path_eq("foo/../bar", "bar");
assert_canon_path_eq("/foo/../bar", "/bar");
assert_canon_path_eq("../foo", "../foo");
assert_canon_path_eq("../foo/../bar", "../bar");
assert_canon_path_eq("../../bar", "../../bar");
assert_canon_path_eq("./../foo", "../foo");
assert_canon_path_eq("foo/..", ".");
assert_canon_path_eq("foo/../", ".");
assert_canon_path_eq("foo/../../", "../");
assert_canon_path_eq("foo/../../bar", "../bar");
}
}