Created
February 1, 2015 19:03
-
-
Save thiagopnts/40ab4f8ea3e12c57c2f5 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct Tree { | |
root: *mut Node, | |
} | |
impl Tree { | |
fn new() -> Tree { | |
Tree { root: ptr::null_mut() } | |
} | |
pub fn insert(&mut self, value: i32) { | |
let mut root = self.root; | |
self.insert_node(&mut root, value); | |
} | |
fn insert_node(&mut self, n: &mut *mut Node, value: i32) { | |
assert!(*n == self.root); // both are 0x0 | |
if n.is_null() { | |
unsafe { | |
let mut node: *mut Node = mem::transmute(Box::new(Node { | |
left: ptr::null_mut(), | |
right: ptr::null_mut(), | |
value: value, | |
})); | |
mem::replace(n, node); | |
assert!(*n == node); | |
assert!(self.root == (*n)); // fails, self.root still points to 0x0 | |
} | |
} | |
} | |
} | |
struct Node { | |
left: *mut Node, | |
right: *mut Node, | |
value: i32, | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment