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
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
//! A segmented [`Path`] safe to use as a filesystem [`std::path::Path`] or in a [`super::Link`].

use std::ops::{Deref, DerefMut};
use std::str::FromStr;
use std::{fmt, iter};

use get_size::GetSize;
use smallvec::*;

use super::{label, Id, Label, ParseError, Segments};

/// A segment of a [`Path`]
pub type PathSegment = Id;

/// A constant representing a [`PathBuf`].
pub struct PathLabel {
    segments: &'static [&'static str],
}

impl<Idx: std::slice::SliceIndex<[&'static str]>> std::ops::Index<Idx> for PathLabel {
    type Output = Idx::Output;

    fn index(&self, index: Idx) -> &Self::Output {
        &self.segments[index]
    }
}

/// Return a [`PathLabel`] with the given segments.
pub const fn path_label(segments: &'static [&'static str]) -> PathLabel {
    PathLabel { segments }
}

impl fmt::Display for PathLabel {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("/")?;

        let mut segments = self.segments.iter();
        let last = segments.next_back();

        for id in segments {
            f.write_str(id)?;
            f.write_str("/")?;
        }

        if let Some(last) = last {
            f.write_str(last)?;
        }

        Ok(())
    }
}

impl From<PathLabel> for Id {
    fn from(path: PathLabel) -> Self {
        Label::from(path).into()
    }
}

impl From<PathLabel> for Label {
    fn from(path: PathLabel) -> Self {
        match path.segments {
            [id] => label(id),
            _ => panic!("not an Id: {}", PathBuf::from(path)),
        }
    }
}

impl From<PathLabel> for PathBuf {
    fn from(path: PathLabel) -> Self {
        let segments = path
            .segments
            .into_iter()
            .map(|segment| label(*segment))
            .map(PathSegment::from)
            .collect();

        Self { segments }
    }
}

/// A segmented link safe to use with a filesystem or via HTTP.
pub struct Path<'a> {
    inner: &'a [PathSegment],
}

impl Default for Path<'static> {
    fn default() -> Self {
        Self { inner: &[] }
    }
}

impl<'a> Deref for Path<'a> {
    type Target = [PathSegment];

    fn deref(&self) -> &Self::Target {
        &self.inner
    }
}

impl<'a> From<&'a [PathSegment]> for Path<'a> {
    fn from(inner: &'a [PathSegment]) -> Path<'a> {
        Path { inner }
    }
}

impl<'a, Idx: std::slice::SliceIndex<[PathSegment]>> std::ops::Index<Idx> for Path<'a> {
    type Output = Idx::Output;

    fn index(&self, index: Idx) -> &Self::Output {
        &self.inner[index]
    }
}

impl<'a> fmt::Debug for Path<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        fmt::Display::fmt(self, f)
    }
}

impl<'a> fmt::Display for Path<'a> {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        f.write_str("/")?;

        for i in 0..self.len() {
            write!(f, "{}", self[i])?;

            if i < self.len() - 1 {
                f.write_str("/")?;
            }
        }

        Ok(())
    }
}

/// A segmented link buffer safe to use with a filesystem or via HTTP.
#[derive(Clone, Default, Hash, Eq, PartialEq)]
pub struct PathBuf {
    segments: Segments<PathSegment>,
}

impl PathBuf {
    /// Construct a new, empty [`PathBuf`].
    pub fn new() -> Self {
        Self {
            segments: Segments::new(),
        }
    }

    /// Construct a new [`PathBuf`] by cloning the path segments in the given `slice`.
    pub fn from_slice(segments: &[PathSegment]) -> Self {
        Self {
            segments: segments.into_iter().cloned().collect(),
        }
    }

    /// Construct a new, empty [`PathBuf`] with the given `capacity`.
    pub fn with_capacity(capacity: usize) -> Self {
        Self {
            segments: Segments::with_capacity(capacity),
        }
    }

    /// Destructures this [`PathBuf`] into its underlying [`SmallVec`].
    pub fn into_inner(self) -> Segments<PathSegment> {
        self.segments
    }

    /// Appends `suffix` to this `PathBuf`.
    pub fn append<S: Into<PathSegment>>(mut self, suffix: S) -> Self {
        self.segments.push(suffix.into());
        self
    }

    /// Remove and return the last segment in this path, if any.
    pub fn pop(&mut self) -> Option<PathSegment> {
        self.segments.pop()
    }

    /// If this path begins with the specified prefix, returns the suffix following the prefix.
    pub fn suffix<'a>(&self, path: &'a [PathSegment]) -> Option<&'a [PathSegment]> {
        if path.starts_with(&self.segments) {
            Some(&path[self.segments.len()..])
        } else {
            None
        }
    }
}

impl GetSize for PathBuf {
    fn get_size(&self) -> usize {
        self.segments.iter().map(|segment| segment.get_size()).sum()
    }
}

impl Extend<PathSegment> for PathBuf {
    fn extend<T: IntoIterator<Item = PathSegment>>(&mut self, iter: T) {
        self.segments.extend(iter)
    }
}

impl<Idx: std::slice::SliceIndex<[PathSegment]>> std::ops::Index<Idx> for PathBuf {
    type Output = Idx::Output;

    fn index(&self, index: Idx) -> &Self::Output {
        &self.segments[index]
    }
}

#[cfg(feature = "hash")]
impl<D: async_hash::Digest> async_hash::Hash<D> for PathBuf {
    fn hash(self) -> async_hash::Output<D> {
        async_hash::Hash::<D>::hash(&self)
    }
}

#[cfg(feature = "hash")]
impl<'a, D: async_hash::Digest> async_hash::Hash<D> for &'a PathBuf {
    fn hash(self) -> async_hash::Output<D> {
        if self == &PathBuf::default() {
            return async_hash::default_hash::<D>();
        } else {
            async_hash::Hash::<D>::hash(self.to_string())
        }
    }
}

impl PartialEq<String> for PathBuf {
    fn eq(&self, other: &String) -> bool {
        self == other.as_str()
    }
}

impl PartialEq<str> for PathBuf {
    fn eq(&self, other: &str) -> bool {
        if other.is_empty() {
            return false;
        } else if self.segments.is_empty() {
            return other == "/";
        }

        let mut i = 0;
        for segment in other.split('/') {
            if i >= self.segments.len() {
                return false;
            } else if segment == self.segments[i] {
                i += 1;
            } else {
                return false;
            }
        }

        self.segments.len() == i
    }
}

impl IntoIterator for PathBuf {
    type Item = PathSegment;
    type IntoIter = <Segments<PathSegment> as IntoIterator>::IntoIter;

    fn into_iter(self) -> Self::IntoIter {
        self.segments.into_iter()
    }
}

impl std::borrow::Borrow<[PathSegment]> for PathBuf {
    fn borrow(&self) -> &[PathSegment] {
        &self.segments[..]
    }
}

impl Deref for PathBuf {
    type Target = [PathSegment];

    fn deref(&self) -> &Self::Target {
        &self.segments
    }
}

impl DerefMut for PathBuf {
    fn deref_mut(&mut self) -> &mut Self::Target {
        &mut self.segments
    }
}

impl PartialEq<[PathSegment]> for PathBuf {
    fn eq(&self, other: &[PathSegment]) -> bool {
        self.segments.as_slice() == other
    }
}

impl From<PathSegment> for PathBuf {
    fn from(segment: PathSegment) -> PathBuf {
        PathBuf {
            segments: iter::once(segment).collect(),
        }
    }
}

impl From<Label> for PathBuf {
    fn from(segment: Label) -> PathBuf {
        PathBuf {
            segments: iter::once(segment.into()).collect(),
        }
    }
}

impl FromStr for PathBuf {
    type Err = ParseError;

    #[inline]
    fn from_str(to: &str) -> Result<Self, Self::Err> {
        if to == "/" {
            Ok(PathBuf {
                segments: smallvec![],
            })
        } else if to.ends_with('/') {
            Err(format!("Path {} cannot end with a slash", to).into())
        } else if to.starts_with('/') {
            let segments = to
                .split('/')
                .skip(1)
                .map(PathSegment::from_str)
                .collect::<Result<Segments<PathSegment>, ParseError>>()?;

            Ok(PathBuf { segments })
        } else {
            to.parse()
                .map(|id| PathBuf {
                    segments: iter::once(id).collect(),
                })
                .map_err(|cause| format!("invalid path: {}", cause).into())
        }
    }
}

impl From<Segments<PathSegment>> for PathBuf {
    fn from(segments: Segments<PathSegment>) -> Self {
        Self { segments }
    }
}

impl iter::FromIterator<PathSegment> for PathBuf {
    fn from_iter<T: IntoIterator<Item = PathSegment>>(iter: T) -> Self {
        PathBuf {
            segments: iter.into_iter().collect(),
        }
    }
}

impl fmt::Debug for PathBuf {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", Path::from(&self[..]))
    }
}

impl fmt::Display for PathBuf {
    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
        write!(f, "{}", Path::from(&self[..]))
    }
}

#[cfg(test)]
mod test {
    use super::*;

    #[test]
    fn test_path_label_to_string() {
        let path = path_label(&[]);
        assert_eq!(path.to_string(), "/".to_string());

        let path = path_label(&["one"]);
        assert_eq!(path.to_string(), "/one".to_string());

        let path = path_label(&["one", "two"]);
        assert_eq!(path.to_string(), "/one/two".to_string());
    }
}