tree_arena 0.2.0

An arena allocated tree.
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
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
// Copyright 2024 the Xilem Authors
// SPDX-License-Identifier: Apache-2.0

//! The types defined in this module *still* don't implement an arena.
//! Items are stored in a hashmap (and then boxed!) instead of in a buffer.
//! A future version will likely use some kind of slotmap.

#![allow(unsafe_code, reason = "Purpose is unsafe abstraction")]
use std::cell::UnsafeCell;

use hashbrown::HashMap;

use crate::NodeId;

#[derive(Debug)]
struct TreeNode<T> {
    item: T,
    children: Vec<NodeId>,
}

/// Mapping of data for the Tree Arena
#[derive(Debug)]
struct DataMap<T> {
    /// The items in the tree
    items: HashMap<NodeId, Box<UnsafeCell<TreeNode<T>>>>,
    /// The parent of each node, or `None` if it is the root
    parents: HashMap<NodeId, Option<NodeId>>,
}

/// A container type for a tree of items.
///
/// This type is used to store zero, one or many trees of a given item type. It
/// will keep track of parent-child relationships, lets you efficiently find
/// an item anywhere in the tree hierarchy, and give you mutable access to this item
/// and its children.
#[derive(Debug)]
pub struct TreeArena<T> {
    /// The items in the tree
    data_map: DataMap<T>,
    /// The roots of the tree
    roots: Vec<NodeId>,
}

/// A reference type giving shared access to an arena item and its children.
///
/// When you borrow an item from a [`TreeArena`], it returns an [`ArenaRef`].
/// You can access its children to get access to child [`ArenaRef`] handles.
#[derive(Debug)]
pub struct ArenaRef<'arena, T> {
    /// Parent of the Node
    pub parent_id: Option<NodeId>,
    /// Item in the node
    pub item: &'arena T,
    /// Children of the node
    pub children: ArenaRefList<'arena, T>,
}

/// A handle giving shared access to a set of arena items.
///
/// See [`ArenaRef`] for more information.
#[derive(Debug)]
pub struct ArenaRefList<'arena, T> {
    /// The associated data arena
    parent_arena: &'arena DataMap<T>,
    /// The parent id for the items
    parent_id: Option<NodeId>,
}

/// A reference type giving mutable access to an arena item and its children.
///
/// When you borrow an item from a [`TreeArena`], it returns an `ArenaMut`.
/// This struct holds three fields:
///  - the id of its parent.
///  - a reference to the item itself.
///  - an [`ArenaMutList`] handle to access its children.
///
/// Because the latter two are disjoint references, you can mutate the node's value
/// and its children independently without invalidating the references.
///
/// You can iterate over its children to get access to child `ArenaMut` handles.
#[derive(Debug)]
pub struct ArenaMut<'arena, T> {
    /// Parent of the Node
    pub parent_id: Option<NodeId>,
    /// Item in the node
    pub item: &'arena mut T,
    /// Children of the node
    pub children: ArenaMutList<'arena, T>,
}

/// A handle giving mutable access to a set of arena items.
///
/// See [`ArenaMut`] for more information.
#[derive(Debug)]
pub struct ArenaMutList<'arena, T> {
    /// The associated data arena
    parent_arena: &'arena mut DataMap<T>,
    /// The parent id for these items
    parent_id: Option<NodeId>,
    /// Array of items
    child_arr: &'arena mut Vec<NodeId>,
}

impl<Item> Clone for ArenaRef<'_, Item> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Item> Copy for ArenaRef<'_, Item> {}

impl<T> Clone for ArenaRefList<'_, T> {
    fn clone(&self) -> Self {
        *self
    }
}

impl<Item> Copy for ArenaRefList<'_, Item> {}

impl<T> DataMap<T> {
    fn new() -> Self {
        Self {
            items: HashMap::new(),
            parents: HashMap::new(),
        }
    }

    fn find_node(&self, id: NodeId) -> Option<&TreeNode<T>> {
        let node_cell = self.items.get(&id)?;

        // SAFETY
        // We need there to be no mutable access to the node
        // Mutable access to the node would imply there is some &mut self
        // As we are taking &self, there can be no mutable access to the node
        // Thus this is safe

        Some(unsafe { node_cell.get().as_ref()? })
    }

    /// Find an item in the tree.
    ///
    /// Returns a shared reference to the item if present.
    ///
    /// Time Complexity O(1)
    fn find_inner(&self, id: NodeId) -> Option<ArenaRef<'_, T>> {
        let parent_id = *self.parents.get(&id)?;

        let TreeNode { item, .. } = self.find_node(id)?;

        let children = ArenaRefList {
            parent_arena: self,
            parent_id: Some(id),
        };

        Some(ArenaRef {
            parent_id,
            item,
            children,
        })
    }

    /// Find an item in the tree.
    ///
    /// Returns a mutable reference to the item if present.
    ///
    /// Time Complexity O(1)
    fn find_mut_inner(&mut self, id: NodeId) -> Option<ArenaMut<'_, T>> {
        let parent_id = *self.parents.get(&id)?;
        let node_cell = self.items.get(&id)?;

        // SAFETY
        //
        // When using this on [`ArenaMutList`] associated with some node,
        // must ensure that `id` is a descendant of that node, otherwise can
        // obtain two mutable references to the same node
        //
        // Similarly we cannot take any other actions that would affect this node,
        // such as removing it or removing a parent (and thus this node) or violate
        // exclusivity by creating a shared reference to the node
        let TreeNode { item, children } = unsafe { node_cell.get().as_mut()? };

        let children = ArenaMutList {
            parent_arena: self,
            parent_id: Some(id),
            child_arr: children,
        };

        Some(ArenaMut {
            parent_id,
            item,
            children,
        })
    }

    /// Construct the path of items from the given item to the root of the tree.
    ///
    /// The path is in order from the bottom to the top, starting at the given item and ending at
    /// the root.
    ///
    /// If `start_id` is Some, the path ends just before that id instead; `start_id` is not included.
    ///
    /// If there is no path from `start_id` to id, returns the empty vector.
    fn get_id_path(&self, id: NodeId, start_id: Option<NodeId>) -> Vec<NodeId> {
        let mut path = Vec::new();

        if !self.parents.contains_key(&id) {
            return path;
        }

        let mut current_id = Some(id);
        while let Some(current) = current_id {
            path.push(current);
            current_id = *self.parents.get(&current).unwrap();
            if current_id == start_id {
                break;
            }
        }

        // current_id was the last parent node
        // as such if current id is not start_id
        // we have gone to the root and we empty the vec
        if current_id != start_id {
            path.clear();
        }
        path
    }
}

impl<T> TreeArena<T> {
    /// Create a new empty tree
    pub fn new() -> Self {
        Self {
            data_map: DataMap::new(),
            roots: Vec::new(),
        }
    }

    /// Returns a handle whose children are the roots, if any, of the tree.
    pub fn roots(&self) -> ArenaRefList<'_, T> {
        ArenaRefList {
            parent_arena: &self.data_map,
            parent_id: None,
        }
    }

    /// An iterator visiting all root ids in arbitrary order.
    pub fn root_ids(&self) -> impl Iterator<Item = NodeId> {
        self.roots.iter().copied()
    }

    /// Returns a handle whose children are the roots, if any, of the tree.
    ///
    /// Using [`insert`](ArenaMutList::insert) on this handle
    /// will add a new root to the tree.
    pub fn roots_mut(&mut self) -> ArenaMutList<'_, T> {
        // safe as the roots are derived from the arena itself (same as safety for find for non root nodes)
        let roots = &mut self.roots;
        ArenaMutList {
            parent_arena: &mut self.data_map,
            parent_id: None,
            child_arr: roots,
        }
    }

    /// Find an item in the tree.
    ///
    /// Returns a shared reference to the item if present.
    ///
    /// # Complexity
    ///
    /// O(1).
    pub fn find(&self, id: impl Into<NodeId>) -> Option<ArenaRef<'_, T>> {
        self.data_map.find_inner(id.into())
    }

    /// Find an item in the tree.
    ///
    /// Returns a mutable reference to the item if present.
    pub fn find_mut(&mut self, id: impl Into<NodeId>) -> Option<ArenaMut<'_, T>> {
        // safe as derived from the arena itself and has assoc lifetime with the arena
        self.data_map.find_mut_inner(id.into())
    }

    /// Construct the path of items from the given item to the root of the tree.
    ///
    /// The path is in order from the bottom to the top, starting at the given item and ending at
    /// the root.
    ///
    /// If the id is not in the tree, returns an empty vector.
    pub fn get_id_path(&self, id: impl Into<NodeId>) -> Vec<NodeId> {
        self.data_map.get_id_path(id.into(), None)
    }

    /// Moves the given child (along with all its children) to the new parent.
    ///
    /// # Panics
    ///
    /// Panics if the parent is actually a child of the to-be-reparented node, or
    /// if the to-be-reparented node is a root node, or
    /// if either node id cannot be found, or
    /// if both given ids are equal.
    pub fn reparent(&mut self, child: impl Into<NodeId>, new_parent: impl Into<NodeId>) {
        let child_id = child.into();
        let new_parent_id = new_parent.into();

        assert_ne!(
            child_id, new_parent_id,
            "expected child to be different from new_parent but both have id #{child_id}"
        );
        assert!(
            !self.get_id_path(new_parent_id).contains(&child_id),
            "cannot reparent because new_parent #{new_parent_id} is a child of the to-be-reparented node #{child_id}"
        );
        assert!(
            !self.roots.contains(&child_id),
            "reparenting of root nodes is currently not supported"
        );

        // ensure new parent id exists
        assert!(
            self.data_map.items.contains_key(&new_parent_id),
            "no node found for new_parent id #{new_parent_id}"
        );

        let old_parent_id = self
            .data_map
            .parents
            .get(&child_id)
            .unwrap_or_else(|| panic!("no node found for child id #{child_id}"))
            .unwrap();

        // Remove child from old parent's children.
        self.find_mut(old_parent_id)
            .unwrap()
            .children
            .child_arr
            .retain(|i| *i != child_id);

        // Update parent reference.
        self.data_map.parents.insert(child_id, Some(new_parent_id));

        // Add child to new parent's children.
        // Safe because we checked that the new parent exists and is not a child of the to-be-reparented node
        self.find_mut(new_parent_id)
            .unwrap_or_else(|| panic!("no node found for child id #{new_parent_id}"))
            .children
            .child_arr
            .push(child_id);
    }
}

impl<T> Default for TreeArena<T> {
    fn default() -> Self {
        Self::new()
    }
}

impl<T> ArenaRef<'_, T> {
    /// Id of the item this handle is associated with.
    pub fn id(&self) -> NodeId {
        self.children
            .parent_id
            .expect("ArenaRefList always has a parent_id when it's a member of ArenaRef")
    }

    /// An iterator visiting all child ids in arbitrary order.
    // NOTE: We're implementing child_ids for ArenaRef instead of ArenaRefList
    // because in an ArenaRefList the implementation for the root ids would be quite inefficient
    // (since the roots are stored in the TreeArena to which the ArenaRefList doesn't have access).
    pub fn child_ids(&self) -> impl IntoIterator<Item = NodeId> {
        self.children
            .parent_arena
            .find_node(self.id())
            .into_iter()
            .flat_map(|c: &TreeNode<T>| &c.children)
            .copied()
    }
}

impl<'arena, T> ArenaRefList<'arena, T> {
    /// Check if id is a descendant of self
    /// O(depth) and the limiting factor for find methods
    /// not from the root
    fn is_descendant(&self, id: NodeId) -> bool {
        if self.parent_arena.items.contains_key(&id) {
            // the id of the parent
            let parent_id = self.parent_id;

            // The arena is derived from the root, and the id is in the tree
            if parent_id.is_none() {
                return true;
            }

            // iff the path is empty, there is no path from id to self
            !self.parent_arena.get_id_path(id, parent_id).is_empty()
        } else {
            // if the id is not in the tree, it is not a descendant
            false
        }
    }

    /// Returns `true` if the list has an element with the given id.
    pub fn has(&self, id: impl Into<NodeId>) -> bool {
        let child_id = id.into();
        let parent_id = self.parent_id;
        self.parent_arena
            .parents
            .get(&child_id)
            .map(|parent| *parent == parent_id) // check if the parent of child is the same as the parent of the arena
            .unwrap_or_default()
    }

    /// Get a shared handle to the element of the list with the given id.
    ///
    /// Return a new [`ArenaRef`]
    pub fn item(&self, id: impl Into<NodeId>) -> Option<ArenaRef<'_, T>> {
        let id = id.into();
        if self.has(id) {
            self.parent_arena.find_inner(id)
        } else {
            None
        }
    }

    /// Get a shared handle to the element of the list with the given id.
    ///
    /// This is the same as [`item`](Self::item), except it consumes the
    /// handle. This is sometimes necessary to accommodate the borrow checker.
    pub fn into_item(self, id: impl Into<NodeId>) -> Option<ArenaRef<'arena, T>> {
        let id = id.into();
        if self.has(id) {
            self.parent_arena.find_inner(id)
        } else {
            None
        }
    }

    /// Find an arena item among the list's items and their descendants.
    ///
    /// Returns a shared reference to the item if present.
    ///
    /// # Complexity
    ///
    /// O(Depth). except access from root which is O(1).
    pub fn find(self, id: impl Into<NodeId>) -> Option<ArenaRef<'arena, T>> {
        // the id to search for
        let id: NodeId = id.into();

        if self.is_descendant(id) {
            self.parent_arena.find_inner(id)
        } else {
            None
        }
    }
}

impl<T> ArenaMut<'_, T> {
    /// Id of the item this handle is associated with
    pub fn id(&self) -> NodeId {
        self.children
            .parent_id
            .expect("ArenaMutList always has a parent_id when it's a member of ArenaMut")
    }

    /// Returns a shared reference equivalent to this one.
    pub fn reborrow(&mut self) -> ArenaRef<'_, T> {
        ArenaRef {
            parent_id: self.parent_id,
            item: self.item,
            children: self.children.reborrow(),
        }
    }

    /// Returns a mutable reference equivalent to this one.
    ///
    /// This is sometimes useful to work with the borrow checker.
    pub fn reborrow_mut(&mut self) -> ArenaMut<'_, T> {
        ArenaMut {
            parent_id: self.parent_id,
            item: self.item,
            children: self.children.reborrow_mut(),
        }
    }
}

impl<'arena, T> ArenaMutList<'arena, T> {
    /// Check if id is a descendant of self
    /// O(depth) and the limiting factor for find methods
    /// not from the root
    fn is_descendant(&self, id: NodeId) -> bool {
        self.reborrow().is_descendant(id)
    }

    /// Returns `true` if the list has an element with the given id.
    pub fn has(&self, id: impl Into<NodeId>) -> bool {
        self.reborrow().has(id)
    }

    /// Get a shared handle to the element of the list with the given id.
    ///
    /// Returns a tuple of a mutable reference to the child and a handle to access
    /// its children.
    pub fn item(&self, id: impl Into<NodeId>) -> Option<ArenaRef<'_, T>> {
        let id = id.into();
        if self.has(id) {
            self.parent_arena.find_inner(id)
        } else {
            None
        }
    }

    /// Get a mutable handle to the element of the list with the given id.
    ///
    /// Returns a tuple of a mutable reference to the child and a handle to access
    /// its children.
    pub fn item_mut(&mut self, id: impl Into<NodeId>) -> Option<ArenaMut<'_, T>> {
        let id = id.into();
        if self.has(id) {
            // safe as we check the node is a direct child node
            self.parent_arena.find_mut_inner(id)
        } else {
            None
        }
    }

    /// Get a shared handle to the element of the list with the given id.
    ///
    /// This is the same as [`item`](Self::item), except it consumes the
    /// handle. This is sometimes necessary to accommodate the borrow checker.
    pub fn into_item(self, id: impl Into<NodeId>) -> Option<ArenaRef<'arena, T>> {
        let id = id.into();
        if self.has(id) {
            self.parent_arena.find_inner(id)
        } else {
            None
        }
    }

    /// Get a mutable handle to the element of the list with the given id.
    ///
    /// This is the same as [`item_mut`](Self::item_mut), except it consumes
    /// the handle. This is sometimes necessary to accommodate the borrow checker.
    pub fn into_item_mut(self, id: impl Into<NodeId>) -> Option<ArenaMut<'arena, T>> {
        let id = id.into();
        if self.has(id) {
            // safe as we check the node is a direct child node
            self.parent_arena.find_mut_inner(id)
        } else {
            None
        }
    }

    // TODO - Remove the child_id argument once creation of widgets is figured out.
    // Return the id instead.
    // TODO - Add #[must_use]
    /// Insert a child into the tree under the common parent of this list's items.
    ///
    /// If this list was returned from [`TreeArena::roots_mut()`], create a new tree root.
    ///
    /// The new child will have the given id.
    ///
    /// Returns a handle to the new child.
    ///
    /// # Panics
    ///
    /// If the arena already contains an item with the given id.
    pub fn insert(&mut self, child_id: impl Into<NodeId>, value: T) -> ArenaMut<'_, T> {
        let child_id: NodeId = child_id.into();
        assert!(
            !self.parent_arena.parents.contains_key(&child_id),
            "Key already present"
        );

        self.parent_arena.parents.insert(child_id, self.parent_id);

        self.child_arr.push(child_id);

        let node = TreeNode {
            item: value,
            children: Vec::new(),
        };

        self.parent_arena
            .items
            .insert(child_id, Box::new(UnsafeCell::new(node)));

        self.parent_arena.find_mut_inner(child_id).unwrap()
    }

    // TODO - How to handle when a subtree is removed?
    // Move children to the root?
    // Should this be must use?
    /// Remove the item with the given id from the arena.
    ///
    /// If the id isn't in the list (even if it's e.g. a descendant), does nothing
    /// and returns `None`.
    ///
    /// Else, returns the removed item.
    ///
    /// This will also silently remove any recursive grandchildren of this item.
    #[must_use]
    pub fn remove(&mut self, child_id: impl Into<NodeId>) -> Option<T> {
        let child_id: NodeId = child_id.into();
        if self.has(child_id) {
            fn remove_children<T>(id: NodeId, data_map: &mut DataMap<T>) -> T {
                let node = data_map.items.remove(&id).unwrap().into_inner();
                for child_id in node.children.into_iter() {
                    remove_children(child_id, data_map);
                }
                data_map.parents.remove(&id);
                node.item
            }
            self.child_arr.retain(|i| *i != child_id);
            Some(remove_children(child_id, self.parent_arena))
        } else {
            None
        }
    }

    /// Returns a shared handle equivalent to this one.
    pub fn reborrow(&self) -> ArenaRefList<'_, T> {
        ArenaRefList {
            parent_arena: self.parent_arena,
            parent_id: self.parent_id,
        }
    }

    /// Returns a mutable handle equivalent to this one.
    ///
    /// This is sometimes useful to work with the borrow checker.
    pub fn reborrow_mut(&mut self) -> ArenaMutList<'_, T> {
        ArenaMutList {
            parent_arena: self.parent_arena,
            parent_id: self.parent_id,
            child_arr: self.child_arr,
        }
    }

    /// Find an arena item among the list's items and their descendants.
    ///
    /// Returns a shared reference to the item if present.
    ///
    /// # Complexity
    ///
    /// O(Depth). except access from root which is O(1).
    pub fn find(&self, id: impl Into<NodeId>) -> Option<ArenaRef<'_, T>> {
        self.reborrow().find(id)
    }

    /// Find an arena item among the list's items and their descendants.
    ///
    /// Returns a shared reference to the item if present.
    ///
    /// # Complexity
    ///
    /// O(Depth). except access from root which is O(1).
    pub fn find_mut(self, id: impl Into<NodeId>) -> Option<ArenaMut<'arena, T>> {
        let id = id.into();
        if self.is_descendant(id) {
            // safe as we check the node is a descendant
            self.parent_arena.find_mut_inner(id)
        } else {
            None
        }
    }

    /// Used in tests to simulate a call to `Self::insert` or `Self::remove` that
    /// triggers a realloc.
    ///
    /// This is an unstable API which can only be used in tests of the `tree_arena` crate itself,
    /// and may change in any release.
    /// It is used to surface potential Use-After-Free (UAF) errors in the code.
    #[doc(hidden)]
    pub fn realloc_inner_storage(&mut self) {
        // By doubling the required capacity (plus a small constant for small capacities),
        // we hopefully guarantee that a reallocation will happen no matter the original capabity.
        let capacity = self.parent_arena.items.capacity();
        let capacity = std::hint::black_box(capacity);
        self.parent_arena.items.reserve(capacity + 32);

        // We try to discard the extra memory.
        // We use black_box to hide the fact that the above call to reserve could be elided.
        if std::hint::black_box(true) {
            self.parent_arena.items.shrink_to_fit();
        }
    }
}