nb-tree 0.2.0-alpha01

Very simple tree structure with generic node and branch data.
Documentation
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
use replace_with::replace_with_or_abort;

use crate::path::Path;

/// Descripion of a position in a tree
///
/// Tthe position can either be attached (targetting a node)
/// or detached (outside of the tree).
/// Positions are described by an absolute Path
/// that cannot move above the tree root.
#[derive(Debug, Clone)]
pub enum Position<B, I> {
    /// The position is targetting a node
    Attached(AttachedPosition<B, I>),
    /// The position is leaving the tree
    Detached(DetachedPosition<B, I>),
}

impl<B, I> Position<B, I> {
    pub fn new_detached() -> Self {
        Self::Detached(DetachedPosition::new())
    }

    pub fn new_attached(root: I) -> Self {
        let mut ph = Path::new();
        ph.push_last(root);
        Self::Attached(AttachedPosition::from(Path::new(), ph))
    }

    pub fn from(path: Path<B>, idxs: Path<I>) -> Self {
        if !idxs.is_empty() && path.len() == idxs.len() - 1 {
            Self::Attached(AttachedPosition::from(path, idxs))
        } else {
            Self::Detached(DetachedPosition::from(path, idxs))
        }
    }

    pub fn move_up(&mut self, up: usize) -> Option<usize> {
        let mut overflow = None;
        replace_with_or_abort(self, |s| match s {
            Position::Attached(mut attached) => {
                attached.move_up(up).map(|e| {
                    overflow = Some(e);
                    e
                });
                attached.into()
            }
            Position::Detached(detached) => {
                let (p, e) = detached.move_up(up);
                overflow = e;
                p
            }
        });
        overflow
    }

    //TODO: move_down? And use it

    pub fn parent(&self) -> Option<(Option<&B>, Option<&I>)> {
        match self {
            Position::Attached(attached) => attached.parent().map(|(b, i)| (b, Some(i))),
            Position::Detached(detached) => detached.parent(),
        }
    }

    pub fn is_attached(&self) -> bool {
        match self {
            Position::Attached(_) => true,
            Position::Detached(_) => false,
        }
    }

    pub fn attached_mut(&mut self) -> Option<&mut AttachedPosition<B, I>> {
        match self {
            Position::Attached(position) => Some(position),
            Position::Detached(_) => None,
        }
    }

    pub fn detached_mut(&mut self) -> Option<&mut DetachedPosition<B, I>> {
        match self {
            Position::Attached(_) => None,
            Position::Detached(position) => Some(position),
        }
    }

    pub fn attached(&self) -> Option<&AttachedPosition<B, I>> {
        match self {
            Position::Attached(position) => Some(position),
            Position::Detached(_) => None,
        }
    }

    pub fn detached(&self) -> Option<&DetachedPosition<B, I>> {
        match self {
            Position::Attached(_) => None,
            Position::Detached(position) => Some(position),
        }
    }

    pub fn unwrap_detached(self) -> DetachedPosition<B, I> {
        match self {
            Position::Attached(_) => panic!("Unwrapping an Attached Position as DetachedPosition"),
            Position::Detached(position) => position,
        }
    }

    pub fn unwrap_attached(self) -> AttachedPosition<B, I> {
        match self {
            Position::Attached(position) => position,
            Position::Detached(_) => panic!("Unwrapping a Detached Position as AttachedPosition"),
        }
    }

    pub fn at(&self) -> Option<&I> {
        match self {
            Position::Attached(position) => Some(position.at()),
            Position::Detached(_) => None,
        }
    }

    pub fn path(&self) -> &Path<B> {
        match self {
            Position::Attached(position) => position.path(),
            Position::Detached(position) => position.path(),
        }
    }

    pub fn idxs(&self) -> &Path<I> {
        match self {
            Position::Attached(position) => position.idxs(),
            Position::Detached(position) => position.idxs(),
        }
    }

    pub fn at_branch(&self) -> Option<&B> {
        match self {
            Position::Attached(position) => position.at_branch(),
            Position::Detached(position) => position.at_branch(),
        }
    }
}

impl<B, I> From<AttachedPosition<B, I>> for Position<B, I> {
    fn from(value: AttachedPosition<B, I>) -> Self {
        Self::Attached(value)
    }
}

impl<B, I> From<DetachedPosition<B, I>> for Position<B, I> {
    fn from(value: DetachedPosition<B, I>) -> Self {
        Self::Detached(value)
    }
}

#[derive(Debug, Clone)]
pub struct AttachedPosition<B, I> {
    path: Path<B>,
    idxs: Path<I>,
}

#[derive(Debug, Clone)]
pub struct DetachedPosition<B, I> {
    path: Path<B>,
    idxs: Path<I>,
}

/*
impl<B, I> Deref for AttachedPosition<B, I> {
    type Target = I;

    fn deref(&self) -> &Self::Target {
        self.at()
    }
}*/

impl<B, I> AttachedPosition<B, I> {
    /// # Panics
    /// Panics if the built position is not attached
    pub fn from(path: Path<B>, idxs: Path<I>) -> Self {
        assert!(path.len() + 1 == idxs.len(), "Position is not attached");
        Self { path, idxs }
    }

    pub fn at(&self) -> &I {
        self.idxs.last().unwrap()
    }

    pub fn move_up(&mut self, up: usize) -> Option<usize> {
        let len = self.path.len();
        if up > len {
            self.path.clear();
            // Keep the root
            self.idxs.truncate_end(self.idxs.len() - 1);
            Some(up - len)
        } else {
            self.path.truncate_end(up);
            self.idxs.truncate_end(up);
            None
        }
    }
    /// Returns None upon trying to move down to an indexed position while detached
    pub fn move_down(&mut self, branch: B, idx: I) {
        self.path.push_last(branch);
        self.idxs.push_last(idx);
    }

    /// Returns None upon trying to move down to an indexed position while detached
    pub fn move_down_detach(mut self, branch: B) -> DetachedPosition<B, I> {
        self.path.push_last(branch);
        self.into_detached()
    }

    /// Returns the branch and index of the parent node or None if the current node is the root.
    /// The branch is None if the parent node is the tree root.
    pub fn parent(&self) -> Option<(Option<&B>, &I)> {
        // If there is at least two nodes in the path (idx -(branch)-> idx)
        if self.path.last().is_some() {
            Some((
                // If there is more than two nodes in the path
                if self.path.len() > 1 {
                    // Retrieve the parent's branch
                    Some(&self.path[self.path.len() - 2])
                } else {
                    None
                },
                &self.idxs[self.path.len() - 1],
            ))
        } else {
            None
        }
    }

    pub fn remove_node(mut self) -> DetachedPosition<B, I> {
        self.idxs.pop_last();
        self.into_detached()
    }

    pub fn into_detached(self) -> DetachedPosition<B, I> {
        DetachedPosition {
            path: self.path,
            idxs: self.idxs,
        }
    }
    pub fn at_branch(&self) -> Option<&B> {
        self.path.last()
    }

    pub fn path(&self) -> &Path<B> {
        &self.path
    }

    pub fn idxs(&self) -> &Path<I> {
        &self.idxs
    }
}

impl<B, I> DetachedPosition<B, I> {
    pub fn new() -> Self {
        Self {
            path: Path::new(),
            idxs: Path::new(),
        }
    }

    /// # Panics
    /// Panics if the built position is not detached
    pub fn from(path: Path<B>, idxs: Path<I>) -> Self {
        assert!(path.len() >= idxs.len(), "Position is not detached");
        Self { path, idxs }
    }

    pub fn into_attached(self) -> AttachedPosition<B, I> {
        assert!(self.is_attached());
        AttachedPosition {
            path: self.path,
            idxs: self.idxs,
        }
    }

    pub fn detached_at(&self) -> Option<&I> {
        self.idxs.last()
    }

    pub fn move_up(mut self, up: usize) -> (Position<B, I>, Option<usize>) {
        let len = self.path.len();
        if up > len {
            self.path.clear();
            // Keep the root if any
            if !self.idxs.is_empty() {
                self.idxs.truncate_end(self.idxs.len() - 1);
                (self.into_attached().into(), Some(up - len))
            } else {
                (self.into(), Some(up - len))
            }
        } else {
            self.path.truncate_end(up);
            (
                if self.path.len() < self.idxs.len() {
                    self.idxs
                        .truncate_end(self.idxs.len() - self.path.len() - 1);
                    self.into_attached().into()
                } else {
                    self.into()
                },
                None,
            )
        }
    }

    pub fn move_to_attached(mut self) -> Result<AttachedPosition<B, I>, Self> {
        if !self.idxs.is_empty() && self.idxs.len() <= self.path.len() {
            self.path
                .truncate_end(self.path.len() - self.idxs.len() + 1);
            debug_assert!(
                self.is_attached(),
                "Position is still not attached after moving to attached position"
            );
            Ok(self.into_attached())
        } else {
            Err(self)
        }
    }

    pub fn move_down(&mut self, branch: B) {
        self.path.push_last(branch);
    }

    /// Returns the branch and index of the parent node or None if the current node is the root.
    /// The branch is None if the parent node is the tree root and the index is None if it is unknown.
    pub fn parent(&self) -> Option<(Option<&B>, Option<&I>)> {
        // If there is at least two nodes in the path (idx -(branch)-> idx)
        if self.path.last().is_some() {
            let l = self.path.len();
            Some((
                // If there is more than two nodes in the path
                if l > 1 {
                    // Retrieve the parent's branch
                    Some(&self.path[l - 2])
                } else {
                    None
                },
                // If the index of the parent is known
                if self.idxs.len() == l {
                    self.idxs.last()
                } else {
                    None
                },
            ))
        } else {
            None
        }
    }

    pub fn attach(mut self, idx: I) -> Position<B, I> {
        self.idxs.push_last(idx);
        if self.is_attached() {
            self.into_attached().into()
        } else {
            self.into()
        }
    }

    pub fn attach_all(mut self, mut idxs: Vec<I>) -> Position<B, I> {
        idxs.truncate(self.path.len() - self.idxs.len() + 1);
        self.idxs.append(idxs.into());
        if self.is_attached() {
            self.into_attached().into()
        } else {
            self.into()
        }
    }

    fn is_attached(&self) -> bool {
        self.is_rooted() && self.path.len() == self.idxs.len() - 1 // Root idx
    }

    pub fn path(&self) -> &Path<B> {
        &self.path
    }

    pub fn idxs(&self) -> &Path<I> {
        &self.idxs
    }

    pub fn iter_detached_path(&self) -> std::collections::vec_deque::Iter<'_, B> {
        if self.is_rooted() {
            self.path.range((self.idxs.len() - 1)..)
        } else {
            self.path.range(..)
        }
    }

    pub fn offshoot_len(&self) -> usize {
        self.path.len() + 1 - self.idxs.len()
    }

    pub fn is_rooted(&self) -> bool {
        !self.idxs.is_empty()
    }

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

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

impl<B, I> DetachedPosition<B, I>
where
    B: Clone,
{
    pub fn detached_at_branch(&self) -> Option<&B> {
        if !self.idxs.is_empty() {
            Some(&self.path[self.idxs.len()])
        } else {
            None
        }
    }
}