Debian Codegraph @

src/arena_tree.rs

raw
1 //! A DOM-like tree data structure based on `&Node` references.
2 //!
3 //! Included from <https://github.com/SimonSapin/rust-forest/blob/5783c8be8680b84c0438638bdee07d4e4aca40ac/arena-tree/lib.rs>.
4 //! MIT license (per Cargo.toml).
5 //!
6 //! Any non-trivial tree involves reference cycles
7 //! (e.g. if a node has a first child, the parent of the child is that node).
8 //! To enable this, nodes need to live in an arena allocator
9 //! such as `arena::TypedArena` distributed with rustc (which is `#[unstable]` as of this writing)
10 //! or [`typed_arena::Arena`](https://crates.io/crates/typed-arena).
11 //!
12 //! If you need mutability in the node’s `data`,
13 //! make it a cell (`Cell` or `RefCell`) or use cells inside of it.
14
15 use std::cell::{BorrowError, Cell, Ref, RefCell, RefMut};
16 use std::fmt;
17
18 /// A node inside a DOM-like tree.
19 pub struct Node<'a, T: 'a> {
20 parent: Cell<Option<&'a Node<'a, T>>>,
21 previous_sibling: Cell<Option<&'a Node<'a, T>>>,
22 next_sibling: Cell<Option<&'a Node<'a, T>>>,
23 first_child: Cell<Option<&'a Node<'a, T>>>,
24 last_child: Cell<Option<&'a Node<'a, T>>>,
25
26 /// The data held by the node.
27 pub data: T,
28 }
29
30 /// A simple Debug implementation that prints the children as a tree, without
31 /// looping through the various interior pointer cycles.
32 impl<'a, T: 'a> fmt::Debug for Node<'a, RefCell<T>>
33 where
34 T: fmt::Debug,
35 {
36 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
37 struct Children<'a, T>(Option<&'a Node<'a, RefCell<T>>>);
38 impl<T: fmt::Debug> fmt::Debug for Children<'_, T> {
39 fn fmt(&self, f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
40 f.debug_list()
41 .entries(std::iter::successors(self.0, |child| {
42 child.next_sibling.get()
43 }))
44 .finish()
45 }
46 }
47
48 match self.data.try_borrow() {
49 Ok(data) => {
50 write!(f, "{data:?}")?;
51 }
52 _ => {
53 write!(f, "!!mutably borrowed!!")?;
54 }
55 }
56 if let Some(first_child) = self.first_child.get() {
57 write!(f, " {:?}", &Children(Some(first_child)))?;
58 }
59 Ok(())
60 }
61 }
62
63 impl<'a, T> Node<'a, T> {
64 /// Create a new node from its associated data.
65 ///
66 /// Typically, this node needs to be moved into an arena allocator
67 /// before it can be used in a tree.
68 pub fn new(data: T) -> Node<'a, T> {
69 Node {
70 parent: Cell::new(None),
71 first_child: Cell::new(None),
72 last_child: Cell::new(None),
73 previous_sibling: Cell::new(None),
74 next_sibling: Cell::new(None),
75 data,
76 }
77 }
78
79 /// Return a reference to the parent node, unless this node is the root of the tree.
80 pub fn parent(&self) -> Option<&'a Node<'a, T>> {
81 self.parent.get()
82 }
83
84 /// Return a reference to the first child of this node, unless it has no child.
85 pub fn first_child(&self) -> Option<&'a Node<'a, T>> {
86 self.first_child.get()
87 }
88
89 /// Return a reference to the last child of this node, unless it has no child.
90 pub fn last_child(&self) -> Option<&'a Node<'a, T>> {
91 self.last_child.get()
92 }
93
94 /// Return a reference to the previous sibling of this node, unless it is a first child.
95 pub fn previous_sibling(&self) -> Option<&'a Node<'a, T>> {
96 self.previous_sibling.get()
97 }
98
99 /// Return a reference to the next sibling of this node, unless it is a last child.
100 pub fn next_sibling(&self) -> Option<&'a Node<'a, T>> {
101 self.next_sibling.get()
102 }
103
104 /// Returns whether two references point to the same node.
105 pub fn same_node(&self, other: &Node<'a, T>) -> bool {
106 std::ptr::eq(self, other)
107 }
108
109 /// Return an iterator of references to this node and its ancestors.
110 ///
111 /// Call `.next().unwrap()` once on the iterator to skip the node itself.
112 pub fn ancestors(&'a self) -> Ancestors<'a, T> {
113 Ancestors(Some(self))
114 }
115
116 /// Return an iterator of references to this node and the siblings before it.
117 ///
118 /// Call `.next().unwrap()` once on the iterator to skip the node itself.
119 pub fn preceding_siblings(&'a self) -> PrecedingSiblings<'a, T> {
120 PrecedingSiblings(Some(self))
121 }
122
123 /// Return an iterator of references to this node and the siblings after it.
124 ///
125 /// Call `.next().unwrap()` once on the iterator to skip the node itself.
126 pub fn following_siblings(&'a self) -> FollowingSiblings<'a, T> {
127 FollowingSiblings(Some(self))
128 }
129
130 /// Return an iterator of references to this node’s children.
131 pub fn children(&'a self) -> Children<'a, T> {
132 Children(self.first_child.get())
133 }
134
135 /// Return an iterator of references to this node’s children, in reverse order.
136 pub fn reverse_children(&'a self) -> ReverseChildren<'a, T> {
137 ReverseChildren(self.last_child.get())
138 }
139
140 /// Return an iterator of references to this `Node` and its descendants, in tree order.
141 ///
142 /// Parent nodes appear before the descendants.
143 /// Call `.next().unwrap()` once on the iterator to skip the node itself.
144 ///
145 /// *Similar Functions:* Use `traverse()` or `reverse_traverse` if you need
146 /// references to the `NodeEdge` structs associated with each `Node`
147 pub fn descendants(&'a self) -> Descendants<'a, T> {
148 Descendants(self.traverse())
149 }
150
151 /// Return an iterator of references to `NodeEdge` enums for each `Node` and its descendants,
152 /// in tree order.
153 ///
154 /// `NodeEdge` enums represent the `Start` or `End` of each node.
155 ///
156 /// *Similar Functions:* Use `descendants()` if you don't need `Start` and `End`.
157 pub fn traverse(&'a self) -> Traverse<'a, T> {
158 Traverse {
159 root: self,
160 next: Some(NodeEdge::Start(self)),
161 }
162 }
163
164 /// Return an iterator of references to `NodeEdge` enums for each `Node` and its descendants,
165 /// in *reverse* order.
166 ///
167 /// `NodeEdge` enums represent the `Start` or `End` of each node.
168 ///
169 /// *Similar Functions:* Use `descendants()` if you don't need `Start` and `End`.
170 pub fn reverse_traverse(&'a self) -> ReverseTraverse<'a, T> {
171 ReverseTraverse {
172 root: self,
173 next: Some(NodeEdge::End(self)),
174 }
175 }
176
177 /// Detach a node from its parent and siblings. Children are not affected.
178 pub fn detach(&self) {
179 let parent = self.parent.take();
180 let previous_sibling = self.previous_sibling.take();
181 let next_sibling = self.next_sibling.take();
182
183 if let Some(next_sibling) = next_sibling {
184 next_sibling.previous_sibling.set(previous_sibling);
185 } else if let Some(parent) = parent {
186 parent.last_child.set(previous_sibling);
187 }
188
189 if let Some(previous_sibling) = previous_sibling {
190 previous_sibling.next_sibling.set(next_sibling);
191 } else if let Some(parent) = parent {
192 parent.first_child.set(next_sibling);
193 }
194 }
195
196 /// Append a new child to this node, after existing children.
197 pub fn append(&'a self, new_child: &'a Node<'a, T>) {
198 new_child.detach();
199 new_child.parent.set(Some(self));
200 if let Some(last_child) = self.last_child.take() {
201 new_child.previous_sibling.set(Some(last_child));
202 debug_assert!(last_child.next_sibling.get().is_none());
203 last_child.next_sibling.set(Some(new_child));
204 } else {
205 debug_assert!(self.first_child.get().is_none());
206 self.first_child.set(Some(new_child));
207 }
208 self.last_child.set(Some(new_child));
209 }
210
211 /// Append multiple new children to this node, after existing children.
212 pub fn extend(&'a self, new_children: impl IntoIterator<Item = &'a Node<'a, T>>) {
213 for child in new_children.into_iter() {
214 self.append(child);
215 }
216 }
217
218 /// Prepend a new child to this node, before existing children.
219 pub fn prepend(&'a self, new_child: &'a Node<'a, T>) {
220 new_child.detach();
221 new_child.parent.set(Some(self));
222 if let Some(first_child) = self.first_child.take() {
223 debug_assert!(first_child.previous_sibling.get().is_none());
224 first_child.previous_sibling.set(Some(new_child));
225 new_child.next_sibling.set(Some(first_child));
226 } else {
227 debug_assert!(self.first_child.get().is_none());
228 self.last_child.set(Some(new_child));
229 }
230 self.first_child.set(Some(new_child));
231 }
232
233 /// Insert a new sibling after this node.
234 pub fn insert_after(&'a self, new_sibling: &'a Node<'a, T>) {
235 new_sibling.detach();
236 new_sibling.parent.set(self.parent.get());
237 new_sibling.previous_sibling.set(Some(self));
238 if let Some(next_sibling) = self.next_sibling.take() {
239 debug_assert!(std::ptr::eq(
240 next_sibling.previous_sibling.get().unwrap(),
241 self
242 ));
243 next_sibling.previous_sibling.set(Some(new_sibling));
244 new_sibling.next_sibling.set(Some(next_sibling));
245 } else if let Some(parent) = self.parent.get() {
246 debug_assert!(std::ptr::eq(parent.last_child.get().unwrap(), self));
247 parent.last_child.set(Some(new_sibling));
248 }
249 self.next_sibling.set(Some(new_sibling));
250 }
251
252 /// Insert a new sibling before this node.
253 pub fn insert_before(&'a self, new_sibling: &'a Node<'a, T>) {
254 new_sibling.detach();
255 new_sibling.parent.set(self.parent.get());
256 new_sibling.next_sibling.set(Some(self));
257 if let Some(previous_sibling) = self.previous_sibling.take() {
258 new_sibling.previous_sibling.set(Some(previous_sibling));
259 debug_assert!(std::ptr::eq(
260 previous_sibling.next_sibling.get().unwrap(),
261 self
262 ));
263 previous_sibling.next_sibling.set(Some(new_sibling));
264 } else if let Some(parent) = self.parent.get() {
265 debug_assert!(std::ptr::eq(parent.first_child.get().unwrap(), self));
266 parent.first_child.set(Some(new_sibling));
267 }
268 self.previous_sibling.set(Some(new_sibling));
269 }
270 }
271
272 macro_rules! axis_iterator {
273 (#[$attr:meta] $name:ident : $next:ident) => {
274 #[$attr]
275 pub struct $name<'a, T: 'a>(Option<&'a Node<'a, T>>);
276
277 impl<'a, T: 'a> fmt::Debug for $name<'a, RefCell<T>>
278 where
279 T: fmt::Debug,
280 {
281 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
282 f.debug_tuple(stringify!($name)).field(&self.0).finish()
283 }
284 }
285
286 impl<'a, T> Iterator for $name<'a, T> {
287 type Item = &'a Node<'a, T>;
288
289 fn next(&mut self) -> Option<&'a Node<'a, T>> {
290 match self.0.take() {
291 Some(node) => {
292 self.0 = node.$next.get();
293 Some(node)
294 }
295 None => None,
296 }
297 }
298 }
299 };
300 }
301
302 axis_iterator! {
303 #[doc = "An iterator of references to the ancestors a given node."]
304 Ancestors: parent
305 }
306
307 axis_iterator! {
308 #[doc = "An iterator of references to the siblings before a given node."]
309 PrecedingSiblings: previous_sibling
310 }
311
312 axis_iterator! {
313 #[doc = "An iterator of references to the siblings after a given node."]
314 FollowingSiblings: next_sibling
315 }
316
317 axis_iterator! {
318 #[doc = "An iterator of references to the children of a given node."]
319 Children: next_sibling
320 }
321
322 axis_iterator! {
323 #[doc = "An iterator of references to the children of a given node, in reverse order."]
324 ReverseChildren: previous_sibling
325 }
326
327 /// An iterator of references to a given node and its descendants, in tree order.
328 pub struct Descendants<'a, T: 'a>(Traverse<'a, T>);
329
330 impl<'a, T: 'a> fmt::Debug for Descendants<'a, RefCell<T>>
331 where
332 T: fmt::Debug,
333 {
334 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
335 f.debug_tuple("Descendants").field(&self.0).finish()
336 }
337 }
338
339 impl<'a, T> Iterator for Descendants<'a, T> {
340 type Item = &'a Node<'a, T>;
341
342 fn next(&mut self) -> Option<&'a Node<'a, T>> {
343 loop {
344 match self.0.next() {
345 Some(NodeEdge::Start(node)) => return Some(node),
346 Some(NodeEdge::End(_)) => {}
347 None => return None,
348 }
349 }
350 }
351 }
352
353 /// An edge of the node graph returned by a traversal iterator.
354 #[derive(Debug, Clone)]
355 pub enum NodeEdge<T> {
356 /// Indicates that start of a node that has children.
357 /// Yielded by `Traverse::next` before the node’s descendants.
358 /// In HTML or XML, this corresponds to an opening tag like `<div>`
359 Start(T),
360
361 /// Indicates that end of a node that has children.
362 /// Yielded by `Traverse::next` after the node’s descendants.
363 /// In HTML or XML, this corresponds to a closing tag like `</div>`
364 End(T),
365 }
366
367 macro_rules! traverse_iterator {
368 (#[$attr:meta] $name:ident : $first_child:ident, $next_sibling:ident) => {
369 #[$attr]
370 pub struct $name<'a, T: 'a> {
371 root: &'a Node<'a, T>,
372 next: Option<NodeEdge<&'a Node<'a, T>>>,
373 }
374
375 impl<'a, T: 'a> fmt::Debug for $name<'a, RefCell<T>>
376 where
377 T: fmt::Debug,
378 {
379 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
380 f.debug_struct(stringify!($name))
381 .field("root", &self.root)
382 .field("next", &self.next)
383 .finish()
384 }
385 }
386
387 impl<'a, T> Iterator for $name<'a, T> {
388 type Item = NodeEdge<&'a Node<'a, T>>;
389
390 fn next(&mut self) -> Option<NodeEdge<&'a Node<'a, T>>> {
391 match self.next.take() {
392 Some(item) => {
393 self.next = match item {
394 NodeEdge::Start(node) => match node.$first_child.get() {
395 Some(child) => Some(NodeEdge::Start(child)),
396 None => Some(NodeEdge::End(node)),
397 },
398 NodeEdge::End(node) => {
399 if node.same_node(self.root) {
400 None
401 } else {
402 match node.$next_sibling.get() {
403 Some(sibling) => Some(NodeEdge::Start(sibling)),
404 None => match node.parent.get() {
405 Some(parent) => Some(NodeEdge::End(parent)),
406 None => panic!("tree modified during iteration"),
407 },
408 }
409 }
410 }
411 };
412 Some(item)
413 }
414 None => None,
415 }
416 }
417 }
418 };
419 }
420
421 traverse_iterator! {
422 #[doc = "An iterator of the start and end edges of a given
423 node and its descendants, in tree order."]
424 Traverse: first_child, next_sibling
425 }
426
427 traverse_iterator! {
428 #[doc = "An iterator of the start and end edges of a given
429 node and its descendants, in reverse tree order."]
430 ReverseTraverse: last_child, previous_sibling
431 }
432
433 #[test]
434 fn it_works() {
435 struct DropTracker<'a>(&'a Cell<u32>);
436 impl Drop for DropTracker<'_> {
437 fn drop(&mut self) {
438 self.0.set(self.0.get() + 1);
439 }
440 }
441
442 let drop_counter = Cell::new(0);
443 {
444 let mut new_counter = 0;
445 let arena = typed_arena::Arena::new();
446 let mut new = || {
447 new_counter += 1;
448 arena.alloc(Node::new((new_counter, DropTracker(&drop_counter))))
449 };
450
451 let a = new(); // 1
452 a.append(new()); // 2
453 a.append(new()); // 3
454 a.prepend(new()); // 4
455 let b = new(); // 5
456 b.append(a);
457 a.insert_before(new()); // 6
458 a.insert_before(new()); // 7
459 a.insert_after(new()); // 8
460 a.insert_after(new()); // 9
461 let c = new(); // 10
462 b.append(c);
463
464 assert_eq!(drop_counter.get(), 0);
465 c.previous_sibling.get().unwrap().detach();
466 assert_eq!(drop_counter.get(), 0);
467
468 assert_eq!(
469 b.descendants().map(|node| node.data.0).collect::<Vec<_>>(),
470 [5, 6, 7, 1, 4, 2, 3, 9, 10]
471 );
472 }
473
474 assert_eq!(drop_counter.get(), 10);
475 }
476
477 impl<T> Node<'_, RefCell<T>> {
478 /// Shorthand for `node.data.borrow()`.
479 pub fn data(&self) -> Ref<'_, T> {
480 self.data.borrow()
481 }
482
483 /// Shorthand for `node.data.try_borrow()`.
484 pub fn try_data(&self) -> Result<Ref<'_, T>, BorrowError> {
485 self.data.try_borrow()
486 }
487
488 /// Shorthand for `node.data.borrow_mut()`.
489 pub fn data_mut(&self) -> RefMut<'_, T> {
490 self.data.borrow_mut()
491 }
492 }