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
use std::collections::{vec_deque::IntoIter, VecDeque};
use std::fmt::{Debug, Display};
use std::hash::Hash;
use std::str::FromStr;

pub type PathIDX = usize;

/// A path to a [Tree] node
/// A [Path] is a collection of branches to follow to get to the desired node.
/// An empty [Path] represents the root of the [Tree].
///
/// # Examples
/// ```rust
/// use nb_tree::prelude::{Tree, Path};
/// let mut tree = Tree::new();
/// // Paths from string litterals, vectors, or manually built
/// let path_d: Path<String> = "/b/d".into();
/// //let path_e: Path<String> = vec!["a", "c", "e"].into();
/// //let mut path_f = Path::new();
/// //path_f.l("b").l("f");
/// // Use paths to insert data
/// tree.i("/", 0)
///     .i("/a", 1)
///     .i("/b", 2)
///     .i("/a/c", 3)
///     .i(path_d, 4)
/// //    .i(path_e, 5)
///     .i("/a/c/e", 5)
///     .i("/b/f", 6);
/// //    .i(path_f, 6);
///
/// // Use paths to retrieve data
/// assert_eq!(tree.get(&"/a/c".into()), Ok(&3));
///
/// // Use paths to remove data
/// //tree.remove_sub_tree()
/// //assert
/// ```
#[derive(Clone, Debug, Default, PartialEq, Eq, PartialOrd, Ord, Hash)]
pub struct Path<B: Clone + Default + PartialEq + Eq + PartialOrd + Ord + Hash> {
    path: VecDeque<B>,
}

impl<B: Clone + Default + PartialEq + Eq + PartialOrd + Ord + Hash> Path<B> {
    pub fn new() -> Self {
        Self {
            path: VecDeque::new(),
        }
    }
    /*
    pub fn branches_mut(&mut self) -> &mut [B] {
        self.path.make_contiguous().as_mut()
    }*/

    pub fn pop_root(&mut self) -> Option<B> {
        self.path.pop_front()
    }

    pub fn pop_leaf(&mut self) -> Option<B> {
        self.path.pop_back()
    }

    pub(crate) fn path_to(&self, path_idx: PathIDX) -> Path<B> {
        Self {
            path: self.path.range(..path_idx).cloned().collect(),
        }
    }

    pub(crate) fn path_from(&self, path_idx: PathIDX) -> Path<B> {
        Self {
            path: self.path.range(path_idx..).cloned().collect(),
        }
    }

    pub fn push_leaf(&mut self, value: B) {
        self.path.push_back(value);
    }

    pub fn push_root(&mut self, value: B) {
        self.path.push_front(value);
    }

    pub fn last(&self) -> Option<&B> {
        self.path.back()
    }

    pub fn first(&self) -> Option<&B> {
        self.path.front()
    }

    pub fn iter(&self) -> std::collections::vec_deque::Iter<'_, B> {
        self.path.iter()
    }
}

//TODO: P parse error
#[derive(Debug)]
pub enum ParsePathError {
    NoRoot,
    ParseError,
}

/*
impl<P> From<P> for ParsePathError {
    fn from(value: P) -> Self {
        ParsePathError::ParseError(value)
    }
}*/

impl<B: Clone + Default + PartialEq + Eq + PartialOrd + Ord + Hash + FromStr> FromStr for Path<B> {
    type Err = ParsePathError; //<B::Err>;

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        if !s.contains('/') {
            return Err(ParsePathError::NoRoot);
        }
        // Skip everything preceeding the root slash
        Ok(Self {
            path: s
                .split('/')
                .skip(1)
                .filter(|s| !s.is_empty())
                .map(|s| s.parse::<B>())
                .collect::<Result<VecDeque<B>, _>>()
                .map_err(|_| ParsePathError::ParseError)?,
        })
    }
}
impl<B: Clone + Default + PartialEq + Eq + PartialOrd + Ord + Hash> From<Vec<B>> for Path<B> {
    fn from(value: Vec<B>) -> Self {
        Self { path: value.into() }
    }
}

impl<B: Clone + Default + PartialEq + Eq + PartialOrd + Ord + Hash + FromStr> From<&str>
    for Path<B>
{
    fn from(value: &str) -> Self {
        value.parse().unwrap()
    }
}
/*

impl<B: Clone + Default + PartialEq + Eq + PartialOrd + Ord + Hash, C: Into<B>> From<Vec<C>>
    for Path<B>
{
    fn from(value: Vec<C>) -> Self {
        Self {
            path: value.into_iter().map(|v| v.into()).collect(),
        }
    }
}*/

impl<B: Clone + Default + Ord + Hash> IntoIterator for Path<B> {
    type Item = B;

    type IntoIter = IntoIter<B>;

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

impl<B: Clone + Default + PartialEq + Eq + PartialOrd + Ord + Hash> FromIterator<B> for Path<B> {
    fn from_iter<T: IntoIterator<Item = B>>(iter: T) -> Self {
        Self {
            path: iter.into_iter().collect(),
        }
    }
}

impl<B: Clone + Default + Display + PartialEq + Eq + PartialOrd + Ord + Hash> Display for Path<B> {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        //TODO: multi line B display management?
        for b in self.path.iter() {
            write!(f, "/{}", b)?;
        }
        Ok(())
    }
}