Skip to content

Commit

Permalink
Merge pull request #5 from sheroz/sheroz-patch
Browse files Browse the repository at this point in the history
converted tree node parents into weak references
  • Loading branch information
sheroz committed Aug 29, 2023
2 parents fc8463a + 6c7edd9 commit 3d58a9c
Show file tree
Hide file tree
Showing 2 changed files with 8 additions and 6 deletions.
3 changes: 2 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,12 @@ pub struct TreeNode {
pub uuid: Uuid,
pub number: u32,
pub text: String,
pub parent: Option<TreeNodeRef>,
pub parent: TreeNodeWeakRef,
pub children: Option<Vec<TreeNodeRef>>,
}

pub type TreeNodeRef = Rc<RefCell<TreeNode>>;
pub type TreeNodeWeakRef = Weak<RefCell<TreeNode>>;
```

## Sample methods
Expand Down
11 changes: 6 additions & 5 deletions src/tree.rs
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
use std::cell::RefCell;
use std::collections::VecDeque;
use std::rc::Rc;
use std::rc::{Rc, Weak};
use uuid::Uuid;

#[derive(Debug)]
Expand All @@ -13,11 +13,12 @@ pub struct TreeNode {
pub uuid: Uuid,
pub number: u32,
pub text: String,
pub parent: Option<TreeNodeRef>,
pub parent: TreeNodeWeakRef,
pub children: Option<Vec<TreeNodeRef>>,
}

pub type TreeNodeRef = Rc<RefCell<TreeNode>>;
pub type TreeNodeWeakRef = Weak<RefCell<TreeNode>>;

pub trait TreeNodeRefBuild {
fn build_from(item: TreeNode) -> TreeNodeRef;
Expand All @@ -35,7 +36,7 @@ impl TreeNode {
uuid: Uuid::new_v4(),
number: 0,
text: "".to_string(),
parent: None,
parent: Weak::new(),
children: None,
}
}
Expand All @@ -47,7 +48,7 @@ impl Tree {
}

pub fn add_child(&self, parent: TreeNodeRef, child: TreeNodeRef) {
child.as_ref().borrow_mut().parent = Some(parent.clone());
child.as_ref().borrow_mut().parent = Rc::downgrade(&parent);
let mut node = parent.as_ref().borrow_mut();
match node.children.as_mut() {
Some(children) => {
Expand Down Expand Up @@ -91,7 +92,7 @@ impl Tree {

pub fn remove(&mut self, uuid: Uuid) -> Option<TreeNodeRef> {
if let Some(node) = self.search(uuid) {
match node.as_ref().borrow().parent.as_ref() {
match node.as_ref().borrow().parent.upgrade() {
Some(parent_ref) => {
let parent = parent_ref.as_ref();
if let Some(children) = parent.borrow_mut().children.as_mut() {
Expand Down

0 comments on commit 3d58a9c

Please sign in to comment.