Skip to content

Instantly share code, notes, and snippets.

@thiagopnts
Created February 1, 2015 19:03
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save thiagopnts/40ab4f8ea3e12c57c2f5 to your computer and use it in GitHub Desktop.
Save thiagopnts/40ab4f8ea3e12c57c2f5 to your computer and use it in GitHub Desktop.
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