dsa_rust/hierarchies/unsafe_linked_general_tree.rs
1#![allow(unused)]
2/*! An unsafe, linked, n-ary tree implementation
3
4# About
5Following classical DSA curricula, this implementation relies primarily on pointers for the structure's composition and navigation.
6
7See the module's companion [MD tree](`crate::hierarchies::unsafe_linked_general_tree::md_tree`) tool, which takes a Markdown document and prints a hierarchical tree diagram of its heading contents.
8
9# Design
10The base [GenTree] structure only contains basic operations for constructors and metadata retrieval. Most of the magic happens in the [CursorMut] struct. Both structs rely on a [Position] struct, which provides a safe handle to all the raw pointers required to make the tree go brrr.
11
12The design makes heavy use of `unsafe` code via raw pointers. The module represents a two-fold exercise: writing recursive traversal functions and understanding Rust's ownership model well enough to avoid falling back on tricks such as reference counting ([std::rc::Rc]/[std::sync::Arc]) or arena-like allocation with safe indexing ([Vec]) to manage the structure's operations safely.
13
14Notably, this structure enforces strict lifetime constraints on cursors and positions to lock them to the base tree allocation, utilizing Rust's variance rules to systematically prevent pointer dangling, cross-tree pointer smuggling, and use-after-free errors.
15
16In addition to leveraging lifetimes for safety bounds, the module also uses [Cell] for interior mutability on [CursorMut]. This allows cursor navigation methods to retain immutable `&self` borrows for a more ergonomic API.
17*/
18
19use std::marker::PhantomData;
20use std::ptr::NonNull;
21
22/// Represents the actual data structure. Currently this struct only
23/// has constructor methods to create a new tree and create new cursor
24/// handles which provide the lion's share of tree operations.
25///
26/// See [module-level documentation](`crate::hierarchies::unsafe_linked_general_tree`)
27/// for more details.
28pub struct GenTree<T> {
29 root: NonNull<Node<T>>, // Private for safety reasons
30}
31impl<T> Default for GenTree<T> {
32 fn default() -> Self {
33 Self::new()
34 }
35}
36impl<T> GenTree<T> {
37 /// Instantiates a new Tree with a default root
38 pub fn new() -> GenTree<T> {
39 // Allocate the root node on the heap and get a raw pointer to it
40 // SAFETY: Box::into_raw is guaranteed to return a valid,
41 // non-null pointer because Box::new panics rather than
42 // returning null on allocation failure.
43 let root_node = unsafe {
44 NonNull::new_unchecked(Box::into_raw(Box::new(Node {
45 //parent: std::ptr::null_mut(),
46 parent: None,
47 children: Vec::new(),
48 data: None, // Root starts empty
49 })))
50 };
51
52 GenTree { root: root_node }
53 }
54
55 pub fn is_empty(&self) -> bool {
56 // SAFETY: Even empty trees have an initialized root
57 unsafe { (*self.root.as_ptr()).children.len() == 0 }
58 }
59
60 /// Creates a `CursorMut<T>` starting at the tree's root
61 /// NOTE: The lifetime 'a is implicitly tied from `&'a mut self`
62 /// to the returned `CursorMut<'a, T>`
63 pub fn cursor_mut(&mut self) -> CursorMut<'_, T> {
64 // Safety: self.root was allocated in GenTree::new() and is guaranteed not to be null
65 //let non_null_root = unsafe { NonNull::new_unchecked(self.root) };
66 let non_null_root = self.root;
67
68 CursorMut {
69 node: Cell::new(non_null_root),
70 //tree: self,
71 _marker: PhantomData,
72 }
73 }
74
75 // SAFETY: Allows critical use-after-free errors!!
76 //pub fn cursor_mut_from(&mut self, node: NonNull<Node<T>>) -> CursorMut<'_, T> {
77 // // Safety: self.root was allocated in GenTree::new() and is guaranteed not to be null
78 // //let non_null_root = unsafe { NonNull::new_unchecked(self.root) };
79 // let non_null_root = node;
80
81 // CursorMut {
82 // node: Cell::new(non_null_root),
83 // tree: self,
84 // _marker: PhantomData,
85 // }
86 //}
87
88 /** Exposes a read-only Position at the root node */
89 fn root(&self) -> Position<'_, T> {
90 // Safety: self.root is guaranteed valid
91 //let non_null_root = unsafe { NonNull::new_unchecked(self.root) };
92 let non_null_root = self.root;
93 Position {
94 node: non_null_root,
95 _marker: PhantomData,
96 }
97 }
98}
99// Required because Rust doesn't automatically drop heap allocations for
100// raw pointers (NonNull<Node<T>>)
101impl<T> Drop for GenTree<T> {
102 fn drop(&mut self) {
103 // self.root: NonNull<Node<T>>
104 let mut stack = vec![];
105 let mut node = unsafe { Box::from_raw(self.root.as_ptr()) };
106 stack.append(&mut node.children);
107
108 // self.root: *mut T
109 //if self.root.is_null() {
110 // return;
111 //}
112
113 //// Use an iterative stack-based teardown to prevent stack
114 //// overflows on deep trees
115 //let mut stack = vec![self.root];
116
117 while let Some(node_ptr) = stack.pop() {
118 unsafe {
119 // 1. Snatch the children vector out of the
120 // node before destroying it
121 //let mut current_node = Box::from_raw(node_ptr);
122 let mut current_node = Box::from_raw(node_ptr.as_ptr());
123
124 // 2. Push all child pointers onto our teardown stack
125 stack.append(&mut current_node.children);
126
127 // 3. current_node naturally goes out of scope
128 // here, freeing its allocation
129 // and dropping its inner data (T) safely.
130 }
131 }
132 }
133}
134
135/// Has no methods, but `Position` has methods to derive and create `Node`s.
136///
137/// See [module-level documentation](`crate::hierarchies::unsafe_linked_general_tree`)
138/// for more details.
139#[derive(Clone)]
140pub struct Node<T> {
141 parent: Option<NonNull<Node<T>>>,
142 children: Vec<NonNull<Node<T>>>,
143 data: Option<T>,
144}
145
146/// The `Position` struct serves as the module's safe public handle to
147/// individual nodes in the tree. This struct requires a shared
148/// lifetime 'a tied to the underlying tree.
149///
150/// See [module-level documentation](`crate::hierarchies::unsafe_linked_general_tree`)
151/// for more details.
152struct Position<'a, T> {
153 node: NonNull<Node<T>>,
154 _marker: PhantomData<&'a GenTree<T>>,
155}
156impl<'a, T> Position<'a, T> {
157 pub fn get_data(&self) -> Option<&T> {
158 unsafe { self.node.as_ref().data.as_ref() }
159 }
160
161 pub fn get_children(&self) -> Vec<Position<'a, T>> {
162 unsafe {
163 let v = &self.node.as_ref().children;
164 v.iter().map(|x| Position::from_ptr(*x)).collect()
165 }
166 }
167
168 // Internal utility for iterator
169 fn get_children_iter(&self) -> Vec<Position<'a, T>> {
170 unsafe {
171 let v = &self.node.as_ref().children;
172 v.iter().map(|x| Position::from_ptr(*x)).collect()
173 }
174 }
175
176 // Private for safety; aint nobody should have a NonNull ptr!
177 fn from_ptr(ptr: NonNull<Node<T>>) -> Position<'a, T> {
178 Position {
179 node: ptr,
180 _marker: PhantomData,
181 }
182 }
183
184 // SAFETY: Enables pointer smuggling
185 // A safe way to expose the underlying pointer for assert_eq!
186 //pub fn as_ptr(&self) -> NonNull<Node<T>> {
187 // self.node
188 //}
189}
190// Implement Clone so "let curr = cursor.current().clone();" works
191impl<'a, T> Clone for Position<'a, T> {
192 fn clone(&self) -> Self {
193 Position {
194 node: self.node,
195 _marker: PhantomData,
196 }
197 }
198}
199
200use std::cell::Cell;
201
202/// CursorMut takes 'a to tie it to the tree's lifetime
203/// which prevents dangling pointers by gating scopes
204///
205/// See [module-level documentation](`crate::hierarchies::unsafe_linked_general_tree`)
206/// for more details.
207pub struct CursorMut<'a, T> {
208 node: Cell<NonNull<Node<T>>>,
209 //tree: &'a mut GenTree<T>,
210 _marker: std::marker::PhantomData<&'a mut &'a ()>,
211}
212impl<'a, T> CursorMut<'a, T> {
213 // Utilities
214 ////////////
215
216 pub fn get_data(&self) -> Option<&T> {
217 //unsafe { self.node.as_ref().data.as_ref() }
218 unsafe { self.node.get().as_ref().data.as_ref() }
219 }
220
221 pub fn is_none(&self) -> bool {
222 //unsafe { self.node.as_ref().data.is_none() }
223 unsafe { self.node.get().as_ref().data.is_none() }
224 }
225
226 pub fn is_some(&self) -> bool {
227 !self.is_none()
228 }
229
230 pub fn num_children(&self) -> usize {
231 //unsafe { self.node.as_ref().children.len() }
232 unsafe { self.node.get().as_ref().children.len() }
233 }
234
235 fn current(&self) -> Position<'a, T> {
236 Position {
237 //node: self.node,
238 node: self.node.get(),
239 _marker: PhantomData,
240 }
241 }
242
243 //fn children(&self) -> Vec<Position<'a, T>> {
244 // // SAFETY: All nodes should have a valid node.children()
245 // unsafe {
246 // //self.node.as_ref().children.iter()
247 // self.node
248 // .get()
249 // .as_ref()
250 // .children
251 // .iter()
252 // .map(|&ptr| Position {
253 // //node: NonNull::new_unchecked(ptr),
254 // node: ptr,
255 // _marker: PhantomData,
256 // })
257 // .collect()
258 // }
259 //}
260
261 // SAFETY: Breaks uniqueness invariants
262 //pub fn get_tree(&mut self) -> &mut GenTree<T> {
263 // self.tree
264 //}
265
266 // Navigation
267 /////////////
268
269 // /// Uses Cell for interior mutability in order to retain signature semantics
270 // /// such that navigation methods retain &self borrows.
271 //pub fn jump(&self, pos: &Position<'a, T>) {
272 // //self.node = pos.node;
273 // self.node.update(|_| pos.node);
274 //}
275 // Updates to take mutable reference, for safety :)
276 //pub fn jump(&mut self, pos: &Position<'a, T>) {
277 // //self.node = pos.node;
278 // self.node.update(|_| pos.node);
279 //}
280
281 pub fn children_iter(&self) -> ChildIter<'a, T> {
282 ChildIter {
283 parent_ptr: self.node.get(),
284 index: 0,
285 _marker: PhantomData,
286 }
287 }
288
289 /// Uses Cell for interior mutability in order to retain signature semantics
290 /// such that navigation methods retain &self borrows.
291 //pub fn ascend(&self) -> Result<(), &str> {
292 pub fn ascend(&mut self) -> Result<(), &str> {
293 unsafe {
294 //let parent_ptr = self.node.as_ref().parent;
295 let parent_ptr = self.node.get().as_ref().parent;
296 //if parent_ptr.is_none() {
297 // Err("Cannot ascend past root")
298 //} else {
299 // //self.node = NonNull::new_unchecked(parent_ptr);
300 // //self.node = parent_ptr.unwrap();
301 // self.node.update(|_| parent_ptr.unwrap());
302 // Ok(())
303 //}
304 if let Some(val) = parent_ptr {
305 self.node.update(|_| val);
306 Ok(())
307 } else {
308 Err("Cannot ascend past root")
309 }
310 }
311 }
312
313 /// Uses a closure to descend to the correct child node.
314 /// Ex:
315 /// ```rust
316 /// ```
317 pub fn descend<F>(&mut self, predicate: F) -> Result<(), &str>
318 where
319 F: Fn(&T) -> bool,
320 T: 'a,
321 {
322 // 1. Get the iterator of children
323 // 2. Find the first child that satisfies the predicate
324 // 3. Update 'self' (the cursor) to point to that child
325
326 let target_child = self.children_iter().find(|&child| predicate(child));
327
328 if let Some(node) = target_child {
329 // Here you update your internal cursor state.
330 // Assuming your cursor stores a pointer or reference:
331 //self.node = node;
332 Ok(())
333 } else {
334 Err("No child found matching the criteria")
335 }
336 }
337 // Mutation
338 ///////////
339
340 /// Creates and adds a child `Node` to the position of the cursor,
341 /// then moves the cursor to the new child `Node`.
342 pub fn add_child(&mut self, data: T) {
343 unsafe {
344 //let current_ptr = self.node.as_ptr();
345 let current_ptr = self.node.get();
346 //let new_node = Box::into_raw(Box::new(Node {
347 let new_node = NonNull::new_unchecked(Box::into_raw(Box::new(Node {
348 //parent: Some(current_ptr),
349 parent: Some(current_ptr),
350 children: Vec::new(),
351 data: Some(data),
352 })));
353 //self.node.as_mut().children.push(new_node);
354 self.node.get().as_mut().children.push(new_node);
355
356 // Sets the cursor to the new child node
357 self.node.set(new_node);
358 }
359 }
360
361 pub fn delete(&mut self) -> Option<T> {
362 unsafe {
363 //let current_ptr = self.node.as_ptr();
364 let current_ptr = self.node.get();
365 //let parent_ptr = self.node.as_ref().parent;
366 let parent_ptr = self.node.get().as_ref().parent;
367
368 //if parent_ptr.is_null() {
369 //if parent_ptr.is_none() {
370 // return None;
371 //}
372 parent_ptr?;
373
374 //let parent = &mut *parent_ptr;
375 let parent = parent_ptr.unwrap().as_mut();
376
377 if let Some(pos) = parent.children.iter().position(|&x| x == current_ptr) {
378 parent.children.remove(pos);
379
380 //let mut orphans = std::mem::take(&mut self.node.as_mut().children);
381 let mut orphans = std::mem::take(&mut self.node.get().as_mut().children);
382 for &orphan in &orphans {
383 //(*orphan).parent = parent_ptr;
384 (*orphan.as_ptr()).parent = parent_ptr;
385 }
386 parent.children.append(&mut orphans);
387 }
388
389 //self.node = NonNull::new_unchecked(parent_ptr);
390 //self.node = parent_ptr.unwrap();
391 self.node = Cell::new(parent_ptr.unwrap());
392
393 //let boxed_node = Box::from_raw(current_ptr);
394 let boxed_node = Box::from_raw(current_ptr.as_ptr());
395 boxed_node.data
396 }
397 }
398}
399pub struct ChildIter<'a, T> {
400 // pub struct Node<T> {
401 // parent: Option<NonNull<Node<T>>>,
402 // children: Vec<NonNull<Node<T>>>,
403 // data: Option<T>,
404 //}
405 parent_ptr: NonNull<Node<T>>,
406 index: usize,
407 // Ensures correct lifetime tracking
408 _marker: std::marker::PhantomData<&'a T>,
409}
410impl<'a, T> Iterator for ChildIter<'a, T> {
411 // Yields raw mutable pointers to the children so you can use them to move the cursor
412 type Item = &'a T;
413
414 fn next(&mut self) -> Option<Self::Item> {
415 unsafe {
416 let parent_ref = self.parent_ptr.as_ref();
417 let child = parent_ref.children.get(self.index).copied();
418 match child {
419 Some(val) => {
420 self.index += 1;
421 Some(val.as_ref().data.as_ref().unwrap())
422 }
423 None => None,
424 }
425 }
426 }
427}
428
429#[cfg(test)]
430mod tests {
431
432 use super::*;
433
434 #[test]
435 /** Creates this tree to test properties
436 []
437 ├── Landlocked
438 │ ├── Switzerland
439 │ │ └── Geneva
440 │ │ └── Old Town
441 │ │ └── Cathédrale Saint-Pierre
442 │ └── Bolivia
443 │ └── []
444 │ └── []
445 │ ├── Puerta del Sol
446 │ └── Puerta de la Luna
447 └── Islands
448 ├── Marine
449 │ └── Australia
450 └── Fresh Water
451 */
452 fn basic() {
453 //use super::{md_tree, md_tree::Heading, GenTree, Position};
454 use crate::hierarchies::unsafe_linked_general_tree::{md_tree, md_tree::Heading};
455 use crate::hierarchies::unsafe_linked_general_tree::{GenTree, Position};
456 let tree_vec = vec![
457 Heading {
458 level: 2,
459 title: "Landlocked".to_string(),
460 },
461 Heading {
462 level: 3,
463 title: "Switzerland".to_string(),
464 },
465 Heading {
466 level: 4,
467 title: "Geneva".to_string(),
468 },
469 Heading {
470 level: 5,
471 title: "Old Town".to_string(),
472 },
473 Heading {
474 level: 6,
475 title: "Cathédrale Saint-Pierre".to_string(),
476 },
477 Heading {
478 level: 3,
479 title: "Bolivia".to_string(),
480 },
481 Heading {
482 level: 6,
483 title: "Puerta del Sol".to_string(),
484 },
485 Heading {
486 level: 6,
487 title: "Puerta de la Luna".to_string(),
488 },
489 Heading {
490 level: 2,
491 title: "Islands".to_string(),
492 },
493 Heading {
494 level: 3,
495 title: "Marine".to_string(),
496 },
497 Heading {
498 level: 4,
499 title: "Australia".to_string(),
500 },
501 Heading {
502 level: 3,
503 title: "Fresh Water".to_string(),
504 },
505 ];
506
507 // Constructs tree ignoring the first heading
508 let mut tree: GenTree<Heading> = md_tree::construct(1, tree_vec);
509
510 ////////////////////////////
511 // TESTS CURSOR FUNCTIONS //
512 ////////////////////////////
513
514 // let mut cursor = tree.cursor_mut();
515 // // Tests that root is empty with is_some() and is_none()
516 // assert!(!cursor.is_some());
517 // assert!(cursor.is_none());
518 // // Tests root() -> Position<T>
519 // assert_eq!(cursor.node.as_ptr().ok(), tree.root().as_ptr().ok());
520 // assert_eq!(cursor.node.as_ptr().ok(), tree.root().as_ptr().ok());
521 //
522 // // Tests num_children()
523 // assert_eq!(cursor.num_children(), 2); // Root has [Landlocked, Islands]
524 //
525 // // Tests children(), jump(), and get_data()
526 // let kids = cursor.children();
527 // let mut kids_iter = kids.iter();
528 // let root: Option<&Heading> = cursor.children_iter().next();
529 // assert_eq!(*root.unwrap().title, "Landlocked".to_string());
530 //
531 // //cursor.jump(kids_iter.next().unwrap()); // Moves to first child
532 // let curr: Position<Heading> = cursor.current().clone(); // Passes the torch
533 // let data = cursor.get_data().unwrap();
534 // assert_eq!(*data.title, "Islands".to_string());
535 //
536 // // Jumps down a generation to [Marine, Fresh Water]
537 // cursor.jump(&curr);
538 // let new_kids = cursor.children();
539 // let mut kids_iter = new_kids.iter();
540 // cursor.jump(kids_iter.next().unwrap()); // Moves to first child
541 // let data = cursor.get_data().unwrap();
542 // assert_eq!(*data.title, "Marine".to_string());
543 //
544 // // Jumps down a generation, for fun
545 // let new_kids = cursor.children(); // Gets cursor's chidlren
546 // let mut kids_iter = new_kids.iter(); // Creates an iterator
547 // cursor.jump(kids_iter.next().unwrap()); // Moves to first child
548 // let data = cursor.get_data().unwrap();
549 // assert_eq!(*data.title, "Australia".to_string());
550 //
551 // // Tests ascend()
552 // assert!(cursor.ascend().is_ok()); // Marine
553 // assert!(cursor.ascend().is_ok()); // Islands
554 // let data = cursor.get_data().unwrap();
555 // assert_eq!(*data.title, "Islands".to_string());
556 // assert!(cursor.ascend().is_ok()); // []
557 // assert!(cursor.ascend().is_err()); // Cannot ascend() past root
558 // //assert!(cursor.is_root()); // Double checks, just in case
559 //
560 // // Descends to Islands to test delete()
561 // let kids = cursor.children(); // Gets cursor's chidlren
562 // let mut kids_iter = kids.iter(); // Creates an iterator
563 // cursor.jump(kids_iter.next().unwrap()); // Moves to Landlocked
564 // cursor.jump(kids_iter.next().unwrap()); // Moves to Islands
565 // let data = cursor.get_data().unwrap();
566 // assert_eq!(*data.title, "Islands".to_string());
567 //
568 // // Tests delete()
569 // // Creates placeholder Heading
570 // let mut deleted = Heading {
571 // title: String::new(),
572 // level: 0,
573 // };
574 // // Iterates through the child position's under the cursor
575 // // looking for a matching Heading; Once found, jumps to that position,
576 // // and deletes the Heading; The delete() operation automatically jumps
577 // // the cursor to the parent of the deleted position
578 // for position in cursor.children() {
579 // if position.get_data().unwrap().title == "Marine" {
580 // //cursor.jump(&position);
581 // deleted = cursor.delete().unwrap();
582 // }
583 // }
584 // // Tests that the correct Heading was deleted
585 // assert_eq!(deleted.level, 3);
586 // assert_eq!(deleted.title, "Marine".to_string());
587 //
588 // // Tests that the cursor got bumped up to Islands
589 // let data = cursor.get_data().unwrap();
590 // assert_eq!(data.title, "Islands".to_string());
591 //
592 // // Tests that the Islands node has the correct children
593 // let mut kids = Vec::new();
594 // assert_eq!(cursor.children().len(), 2);
595 // for child in cursor.children() {
596 // let title = child.get_data().unwrap().title.clone();
597 // kids.push(title)
598 // }
599 // assert_eq!(kids, ["Fresh Water".to_string(), "Australia".to_string()]);
600
601 // Print debug, uncomment panic to print
602 md_tree::pretty_print("TEST", &tree);
603 //panic!();
604 }
605
606 // Pointer smuggling & (lifetime) covariance holes
607 //////////////////////////////////////////////////
608
609 #[test]
610 #[allow(unused)]
611 fn test_use_after_free() {
612 // 1)
613 // This test verifies that the `_marker: PhantomData<&'a mut &'a ()>`
614 // successfully enforces invariance on CursorMut.
615 // If your invariance fix works perfectly, THIS TEST MUST FAIL TO COMPILE.
616 use crate::hierarchies::unsafe_linked_general_tree::{md_tree, md_tree::Heading};
617 use crate::hierarchies::unsafe_linked_general_tree::{GenTree, Position};
618 let one = vec![
619 Heading {
620 level: 1,
621 title: "Landlocked".to_string(),
622 },
623 Heading {
624 level: 2,
625 title: "Switzerland".to_string(),
626 },
627 ];
628 let two = vec![
629 Heading {
630 level: 1,
631 title: "Bolivia".to_string(),
632 },
633 Heading {
634 level: 2,
635 title: "Zimbabwe".to_string(),
636 },
637 ];
638
639 let mut outer_tree: GenTree<Heading> = md_tree::construct(0, one);
640 let cursor = outer_tree.cursor_mut();
641 {
642 //let inner_tree: GenTree<String> = GenTree::new();
643 let inner_tree: GenTree<Heading> = md_tree::construct(0, two);
644 // COMPILER ERROR EXPECTED HERE:
645 // inner_tree does not live long enough. Invariance stops the compiler
646 // from shrinking `cursor`'s lifetime to match `inner_tree`.
647 let inner_pos = inner_tree.root();
648 //cursor.jump(&inner_pos); // Illegal with multiple mutable borrows
649 }
650 // If it compiled, this would be a use-after-free,
651 // but its illegal because CursorMut is invariant
652 cursor.get_data();
653
654 // CRITICAL ERROR: solved
655 let mut tree1: GenTree<&str> = GenTree::new();
656 let mut tree2: GenTree<&str> = GenTree::new();
657 let pos1: Position<'_, _> = tree1.cursor_mut().current();
658 //let ptr = pos1.as_ptr(); // Allows pointer smuggling
659 drop(tree1);
660 //let pos2 = tree2.cursor_mut_from(ptr); // Illegal pointer smuggling
661 let pos2 = tree2.cursor_mut(); // Legal
662 let _ = pos2.get_data(); // Avoided use-after-free
663
664 // CRITICAL ERROR: pending
665 let mut tree: GenTree<i32> = GenTree::new();
666 let mut cursor = tree.cursor_mut();
667 cursor.add_child(42);
668 // Navigate to child and capture its Position
669 //let child_pos = cursor.children()[0].clone();
670 //cursor.jump(&child_pos);
671 // Assert data is there
672 assert_eq!(cursor.get_data(), Some(&42));
673 //assert_eq!(child_pos.get_data(), Some(&42));
674 // Now drop/delete the current node using &mut self mutation
675 let deleted_data = cursor.delete();
676 assert_eq!(deleted_data, Some(42));
677 // cursor.delete() must internally reset cursor.node to a safe fallback
678 // such as the parent node or the tree's root. Otherwise this triggers UB
679 // by pointing to the freed node.
680 cursor.get_data();
681 // SAFETY: The borrow checker cannot protect child_pos from becoming stale
682 // because it has the same lifetime as the cursor and the tree itself.
683 // This is an inherent risk of keeping long-lived Positions.
684 // Consider removing Position or adding some reference counting?
685 //let _ = child_pos.get_data(); // Expected Miri error if unhandled
686 }
687
688 #[test]
689 fn test_ascend_past_deleted_parent() {
690 // Illegal out-of-bounds indexing!
691 //let i: usize = Vec::new()[0];
692 //assert_eq!(i, 0);
693
694 let mut tree: GenTree<&str> = GenTree::new();
695 let mut cursor = tree.cursor_mut();
696
697 cursor.add_child("parent");
698 //let parent_pos = cursor.children()[0].clone();
699 //cursor.jump(&parent_pos);
700
701 cursor.add_child("child");
702 //let child_pos = cursor.children()[0].clone();
703
704 // Delete parent node while cursor is aware
705 //cursor.jump(&parent_pos);
706 cursor.delete();
707
708 // Reposition cursor to the child (if it was preserved/re-linked)
709 // Verify that ascend safely handles situations where raw pointers are invalidated
710 //cursor.jump(&child_pos);
711 if let Err(e) = cursor.ascend() {
712 assert_eq!(e, "Cannot ascend past root"); // Or your custom orphan error handler
713 }
714 }
715
716 // Null pointer dereferences & bounds testing
717 /////////////////////////////////////////////
718
719 #[test]
720 fn test_ascend_past_root_error_handling() {
721 let mut tree: GenTree<f64> = GenTree::new();
722 let mut cursor = tree.cursor_mut();
723
724 // Verify root node has no parent and safely returns Err instead of null deref
725 let result = cursor.ascend(); // Illegal multiple mutable borrow
726 assert!(result.is_err());
727 assert_eq!(result.unwrap_err(), "Cannot ascend past root");
728 }
729
730 #[test]
731 fn test_empty_root_data_handling() {
732 let tree: GenTree<i32> = GenTree::new();
733 let root_pos = tree.root();
734
735 // Verify the un-initialized data option returns None safely without a null deref
736 assert_eq!(root_pos.get_data(), None);
737 }
738
739 // Memory aliasing & vector invalidations
740 /////////////////////////////////////////
741
742 #[test]
743 fn test_children_vector_reallocation_aliasing() {
744 let mut tree: GenTree<usize> = GenTree::new();
745 let mut cursor = tree.cursor_mut();
746
747 // Collect positions of children
748 cursor.add_child(1);
749 //let first_child_pos = cursor.children()[0].clone();
750
751 // Mass-push items to force the internal Vec<NonNull<Node<T>>> to reallocate
752 // its capacity, moving its backing buffer elsewhere in memory.
753 for i in 2..100 {
754 cursor.add_child(i);
755 }
756
757 // Verify that tracking pointers remain valid or that the tree layout
758 // does not break parental pointer linkage due to backing array growth.
759 //cursor.jump(&first_child_pos);
760 //assert_eq!(cursor.get_data(), Some(&1));
761 assert_eq!(cursor.get_data(), Some(&99));
762 }
763
764 #[test]
765 fn test_mut_exclusivity() {
766 // Enforces that structural adjustments cannot happen if read-only structures
767 // are actively interacting across restricted blocks.
768 let mut tree: GenTree<char> = GenTree::new();
769
770 {
771 let mut cursor = tree.cursor_mut();
772 cursor.add_child('A');
773 } // cursor drops here, relinquishing exclusive access to tree
774
775 let root_pos = tree.root();
776 assert_eq!(root_pos.get_data(), None);
777
778 // This line would fail to compile if root_pos held a mutable borrow,
779 // confirming that shared read-only states don't collide with subsequent allocations.
780 let mut _cursor_two = tree.cursor_mut();
781 }
782}
783
784pub mod md_tree {
785 /*! A handy little tool to create tree diagrams from MD headings
786
787 # About
788 This module sits on top of the [GenTree](`crate::hierarchies::unsafe_linked_general_tree`) structure and contains five functions:
789 - A top-level [navigator] function that takes a [Path] and a level setting to indicate the level that the output drawing should start at
790 - A [parse] function that takes a [Path] and outputs a list of headings
791 - A [construct] function that builds the `GenTree`
792 - A [pretty_print] function that traverses the tree and prints the contents to terminal
793
794 The overall output should look something like this,
795 ```text
796 📄 /document.md
797 │
798 ├── Landlocked
799 │ ├── Switzerland
800 │ │ └── Geneva
801 │ │ └── Old Town
802 │ │ └── Cathédrale Saint-Pierre
803 │ └── Bolivia
804 │ └── []
805 │ └── []
806 │ ├── Puerta del Sol
807 │ └── Puerta de la Luna
808 └── Islands
809 ├── Fresh Water
810 └── Australia
811 ```
812
813 # Design
814 This is mostly just an excuse to write recursive tree traversal functions. All functions but the parsing function utilize recursion.
815
816 **/
817
818 use regex::Regex;
819 use std::fs::File;
820 use std::io::{BufRead, BufReader};
821
822 //use crate::hierarchies::unsafe_linked_general_tree::{CursorMut, GenTree};
823 use crate::hierarchies::unsafe_linked_general_tree::{GenTree, Position};
824 use std::path::Path;
825
826 #[derive(Debug, PartialEq)]
827 pub struct Heading {
828 pub level: usize,
829 pub title: String,
830 }
831 impl Heading {
832 /** Just a humble Heading md_tree */
833 fn new(title: String, level: usize) -> Heading {
834 Heading { level, title }
835 }
836 }
837
838 /** Takes a path to a Markdown file, parses it for title and headings,
839 and returns a tuple containing the document title and a vector of
840 headings.
841
842 Note: The document title portion of the tuple is specifically
843 designed for the Astro-formatted frontmatter of each MD document. */
844 fn parse(root: &Path) -> (String, Vec<Heading>) {
845 // Regex for capturing the title from front matter
846 let t = Regex::new(r"(?ms)^---.*?^title:\s*(.+?)\s*$.*?^---").unwrap();
847 let mut doc_title = String::new();
848 // Regex for capturing headings H1-H6 as #-######
849 let h = Regex::new(r"^(#{1,6})\s+(.*)").unwrap();
850 let mut headings: Vec<Heading> = Vec::new();
851
852 // Read input
853 let file_path = root;
854 let file = File::open(file_path).unwrap(); // TODO: Fix lazy error handling
855 let reader = BufReader::new(file);
856
857 // Read the entire file into a single string
858 // Imperative style
859 let mut content = String::new();
860 for line_result in reader.lines() {
861 let line = line_result.unwrap();
862 if !content.is_empty() {
863 content.push('\n');
864 }
865 content.push_str(&line);
866 }
867 // Functional style
868 //let content: String = reader
869 // .lines()
870 // .map(|l| l.unwrap())
871 // .collect::<Vec<_>>()
872 // .join("\n");
873
874 // Extract the document title
875 if let Some(captures) = t.captures(&content) {
876 let title = captures.get(1).unwrap().as_str();
877 doc_title.push_str(title);
878 }
879
880 // Parse headings line by line
881 for line in content.lines() {
882 if let Some(captures) = h.captures(line) {
883 let level = captures.get(1).unwrap().as_str().len();
884 let text = captures.get(2).unwrap().as_str().to_string();
885 headings.push(Heading { level, title: text });
886 }
887 }
888
889 (doc_title, headings)
890 }
891
892 /** Constructs a tree of Heading types */
893 pub fn construct(mut cur_level: usize, data: Vec<Heading>) -> GenTree<Heading> {
894 let mut tree: GenTree<Heading> = GenTree::<Heading>::new();
895 let mut cursor = tree.cursor_mut();
896
897 for node in data {
898 let data_level = node.level;
899
900 // Case 1: Add child directly (level increases by 1)
901 if data_level == cur_level + 1 {
902 cursor.add_child(node);
903
904 // Move the cursor to the new child
905 //let kids = cursor.children();
906 //cursor.jump(kids.last().unwrap());
907 cur_level += 1;
908 }
909 // Case 2: Add child for multi-generational skip downwards
910 // (level increses by n)
911 else if data_level > cur_level {
912 let diff = data_level - cur_level;
913 for _ in 1..diff {
914 let empty = Heading::new("[]".to_string(), 0);
915 cursor.add_child(empty);
916
917 //let kids = cursor.children();
918 //cursor.jump(kids.last().unwrap());
919 cur_level += 1;
920 }
921 cursor.add_child(node);
922
923 //let kids = cursor.children();
924 //cursor.jump(kids.last().unwrap());
925 cur_level += 1;
926 }
927 // Case 3: Add sibling (level does not change)
928 else if data_level == cur_level {
929 cursor.ascend().ok(); // Back to parent
930 cursor.add_child(node);
931
932 // Move into new sibling to prepare for possible nested children
933 //let kids = cursor.children();
934 //cursor.jump(kids.last().unwrap());
935 }
936 // Case 4: Add child for multi-generational skip upwards
937 // (level decreases by n)
938 else {
939 let diff = cur_level - data_level;
940 // Ascend to the appropriate parent level (+1 for the current node itself)
941 for _ in 0..=diff {
942 cursor.ascend().ok();
943 cur_level -= 1;
944 }
945 cursor.add_child(node);
946
947 //let kids = cursor.children();
948 //cursor.jump(kids.last().unwrap());
949 cur_level += 1;
950 }
951 }
952 tree
953 }
954
955 // Dictates the print spacing for the tree drawing used in pretty_print
956 // and its recursive helper function
957 const SPACE: &str = " ";
958
959 /// A wrapper for a recursive preorder(ish) traversal function;
960 /// Contains logic to print [] on empty trees for more appealing presentation
961 /// Takes a reference to the GenTree and pretty-prints its contents.
962 pub fn pretty_print(title: &str, tree: &GenTree<Heading>) {
963 // Grab a shared reference to the Position at the root node
964 let root_pos = tree.root();
965
966 if tree.is_empty() {
967 println!("📄 {title}\n{SPACE}[]\n"); // Empty trees
968 } else {
969 println!("📄 {title}\n{SPACE}│");
970 // Recursive helper function call
971 preorder(&root_pos, "");
972 println!();
973 }
974 }
975 /// Modified preorder traversal function that walks the tree
976 /// recursively printing each node's title and children with
977 /// appropriate box drawing components.
978 fn preorder(pos: &Position<'_, Heading>, prefix: &str) {
979 // Safely collect child positions. Because Position is Clone,
980 // this creates an array of independent pointers bound to the
981 // same tree lifetime.
982 let children = pos.get_children();
983
984 for (index, child_pos) in pos.get_children().iter().enumerate() {
985 if let Some(child_data) = child_pos.get_data() {
986 let (marker, next_prefix) = if index == children.len() - 1 {
987 ("└── ", format!("{prefix}{SPACE}"))
988 } else {
989 ("├── ", format!("{prefix}│{SPACE}"))
990 };
991 // Print the current node layout
992 println!("{SPACE}{}{}{}", prefix, marker, child_data.title);
993 // Safely recurse! No mutable re-borrows, no raw pointer
994 // smuggling. The compiler tracks the shared tree
995 // lifetime across the entire call stack.
996 preorder(child_pos, &next_prefix);
997 }
998 }
999 }
1000
1001 /** A recursive function that chains the module's utility functions to
1002 pretty-print a table of contents for each Markdown file in the specified
1003 directory; The is_file() path contains logic to build a tree from filtered
1004 values, skipping headers above the user-supplied level argument;
1005 The function also substitues the file name (if any) for all MD files
1006 not formatted with Astro's frontmatter */
1007 pub fn navigator(level: usize, path: &Path) {
1008 if path.is_dir() {
1009 for component in path.read_dir().expect("read_dir call failed") {
1010 let entry = component.expect("failure to deconstruct value");
1011 navigator(level, &entry.path()); // Recursive call
1012 }
1013 } else if path.is_file() {
1014 if let Some(ext) = path.extension() {
1015 match ext.to_str() {
1016 Some("md") | Some("mdx") => {
1017 println!("{}", path.display());
1018 let parsed = parse(path);
1019 let mut name: String = parsed.0;
1020 if name.is_empty() {
1021 if let Some(n) = path
1022 .file_name()
1023 .expect("Error extracting file name")
1024 .to_str()
1025 {
1026 name = n.to_string()
1027 }
1028 }
1029 let filtered = parsed.1.into_iter().filter(|h| h.level > level).collect();
1030 let tree = construct(level, filtered);
1031 pretty_print(&name, &tree);
1032 }
1033 _ => (),
1034 }
1035 }
1036 }
1037 }
1038}