Bläddra i källkod

refactor(crate): turn crate into a library

Danilo Gómez 1 år sedan
förälder
incheckning
c619170549
2 ändrade filer med 29 tillägg och 12 borttagningar
  1. 1 0
      src/lib.rs
  2. 28 12
      src/main.rs

+ 1 - 0
src/lib.rs

@@ -0,0 +1 @@
+mod node;

+ 28 - 12
src/main.rs

@@ -5,7 +5,7 @@ use std::{
 };
 
 #[derive(Debug)]
-struct Node<T: Ord> {
+pub struct Node<T: Ord> {
     value: T,
     height: i32,
     left: Option<Box<Node<T>>>,
@@ -13,7 +13,7 @@ struct Node<T: Ord> {
 }
 
 impl<T: Ord> Node<T> {
-    fn new(value: T) -> Self {
+    pub fn new(value: T) -> Self {
         Node {
             value,
             height: 1,
@@ -70,7 +70,7 @@ impl<T: Ord> Node<T> {
         }
     }
 
-    fn insert(&mut self, value: T) -> bool {
+    pub fn insert(&mut self, value: T) -> bool {
         let ret_val = match value.cmp(&self.value) {
             Ordering::Less => {
                 if let Some(ref mut left) = self.left {
@@ -97,13 +97,29 @@ impl<T: Ord> Node<T> {
     }
 }
 
-fn main() {
-    let mut root = Node::new(5);
-    root.insert(3);
-    root.insert(7);
-    root.insert(1);
-    root.insert(4);
-    root.insert(6);
-    root.insert(9);
-    println!("{:#?}", root);
+#[cfg(test)]
+mod tests {
+    use super::*;
+
+    #[test]
+    fn is_sorted() {
+        let mut values = vec![5, 3, 7, 1, 4, 6, 9];
+        let mut root = Node::new(values[0]);
+        for v in values[1..].iter() {
+            root.insert(*v);
+        }
+        let mut items = Vec::<i32>::new();
+        fn traverse(node: &Node<i32>, items: &mut Vec<i32>) {
+            if let Some(ref left) = node.left {
+                traverse(left, items);
+            }
+            items.push(node.value);
+            if let Some(ref right) = node.right {
+                traverse(right, items);
+            }
+        }
+        traverse(&root, &mut items);
+        values.sort();
+        assert_eq!(items, values);
+    }
 }