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
use std::{ops::Deref, borrow::Borrow};

use ref_cast::RefCast;
use serde::{Serialize, Deserialize};

use crate::Id;

/// A borrowed path of ids.
#[derive(Debug, Hash, PartialEq, Eq, RefCast)]
#[repr(transparent)]
pub struct IdPath([Id]);

/// An owned path of ids.
#[derive(Debug, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct IdPathBuf(Vec<Id>);

impl IdPath {
    pub fn root() -> &'static Self {
        Self::ref_cast(&[])
    }

    pub fn is_root(&self) -> bool {
        self.0.is_empty()
    }

    pub fn head(&self) -> Option<Id> {
        self.0.first().cloned()
    }

    pub fn tail(&self) -> &Self {
        Self::ref_cast(&self.0[1..])
    }

    pub fn child(&self, id: impl Into<Id>) -> IdPathBuf {
        self.to_owned().child(id)
    }

    pub fn join(&self, path: &IdPath) -> IdPathBuf {
        self.to_owned().join(path)
    }
}

impl IdPathBuf {
    pub fn root() -> Self {
        Self(Vec::new())
    }

    pub fn child(&self, id: impl Into<Id>) -> Self {
        let mut components = self.0.clone();
        components.push(id.into());
        Self(components)
    }

    pub fn join(&self, path: &IdPath) -> Self {
        let mut components = self.0.clone();
        components.extend(path.0.into_iter().cloned());
        Self(components)
    }
}

impl ToOwned for IdPath {
    type Owned = IdPathBuf;

    fn to_owned(&self) -> IdPathBuf {
        IdPathBuf(self.0.to_vec())
    }
}

impl Default for IdPathBuf {
    fn default() -> Self {
        Self::root()
    }
}

impl From<Id> for IdPathBuf {
    fn from(id: Id) -> Self {
        Self(vec![id])
    }
}

impl Deref for IdPathBuf {
    type Target = IdPath;

    fn deref(&self) -> &IdPath {
        // Unfortunately, casting `&[Id]` to our (newtype-style) DST `IdPath`
        // cannot be done easily and safely using the language only, see
        // https://internals.rust-lang.org/t/brainstorming-newtypes-for-dsts-without-needing-unsafe/8515/7
        // We therefore use the ref-cell library providing a safe abstraction.
        IdPath::ref_cast(&self.0[..])
    }
}

impl AsRef<IdPath> for IdPathBuf {
    fn as_ref(&self) -> &IdPath {
        self.deref()
    }
}

impl Borrow<IdPath> for IdPathBuf {
    fn borrow(&self) -> &IdPath {
        self.deref()
    }
}