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
use std::path::{Path, PathBuf};
use crate::fs::Stack;
impl Stack {
pub fn root(&self) -> &Path {
&self.root
}
pub fn current(&self) -> &Path {
&self.current
}
pub fn current_relative(&self) -> &Path {
&self.current_relative
}
}
pub trait Delegate {
fn push_directory(&mut self, stack: &Stack) -> std::io::Result<()>;
fn push(&mut self, is_last_component: bool, stack: &Stack) -> std::io::Result<()>;
fn pop_directory(&mut self);
}
impl Stack {
pub fn new(root: impl Into<PathBuf>) -> Self {
let root = root.into();
Stack {
current: root.clone(),
current_relative: PathBuf::with_capacity(128),
valid_components: 0,
root,
current_is_directory: true,
}
}
pub fn make_relative_path_current(
&mut self,
relative: impl AsRef<Path>,
delegate: &mut impl Delegate,
) -> std::io::Result<()> {
let relative = relative.as_ref();
debug_assert!(
relative.is_relative(),
"only index paths are handled correctly here, must be relative"
);
debug_assert!(!relative.to_string_lossy().is_empty(), "empty paths are not allowed");
if self.valid_components == 0 {
delegate.push_directory(self)?;
}
let mut components = relative.components().peekable();
let mut existing_components = self.current_relative.components();
let mut matching_components = 0;
while let (Some(existing_comp), Some(new_comp)) = (existing_components.next(), components.peek()) {
if existing_comp == *new_comp {
components.next();
matching_components += 1;
} else {
break;
}
}
for _ in 0..self.valid_components - matching_components {
self.current.pop();
self.current_relative.pop();
if self.current_is_directory {
delegate.pop_directory();
}
self.current_is_directory = true;
}
self.valid_components = matching_components;
if !self.current_is_directory && components.peek().is_some() {
delegate.push_directory(self)?;
}
while let Some(comp) = components.next() {
let is_last_component = components.peek().is_none();
self.current_is_directory = !is_last_component;
self.current.push(comp);
self.current_relative.push(comp);
self.valid_components += 1;
let res = delegate.push(is_last_component, self);
if self.current_is_directory {
delegate.push_directory(self)?;
}
if let Err(err) = res {
self.current.pop();
self.current_relative.pop();
self.valid_components -= 1;
return Err(err);
}
}
Ok(())
}
}