about summary refs log tree commit
diff options
context:
space:
mode:
authorEric Wong <normalperson@yhbt.net>2010-09-01 18:03:13 -0700
committerEric Wong <normalperson@yhbt.net>2010-09-01 18:04:21 -0700
commit28316a1d951d8dd5a1c8b8eb31149f82dd29ff3b (patch)
treee55aba4d0c61dc3eeeb8308960433443afa19b0d
parent742da1694d3202714f8f8534d907c51f1cdca514 (diff)
downloadrpatricia-28316a1d951d8dd5a1c8b8eb31149f82dd29ff3b.tar.gz
tree-walking on empty trees no longer segfaults
Patricia#num_nodes properly returns zero and
Patricia#show_nodes displays nothing.
-rw-r--r--ext/rpatricia/rpatricia.c18
-rw-r--r--test/test_old_segfaults.rb12
2 files changed, 22 insertions, 8 deletions
diff --git a/ext/rpatricia/rpatricia.c b/ext/rpatricia/rpatricia.c
index fcb544b..f395eea 100644
--- a/ext/rpatricia/rpatricia.c
+++ b/ext/rpatricia/rpatricia.c
@@ -136,7 +136,7 @@ p_num_nodes (VALUE self)
   patricia_tree_t *tree;
 
   Data_Get_Struct(self, patricia_tree_t, tree);
-  n = patricia_walk_inorder(tree->head, dummy);
+  n = tree->head ? patricia_walk_inorder(tree->head, dummy) : 0;
 
   return INT2NUM(n);
 }
@@ -162,13 +162,15 @@ p_print_nodes (VALUE self)
   patricia_node_t *node;
   Data_Get_Struct(self, patricia_tree_t, tree);
 
-  PATRICIA_WALK(tree->head, node) {
-    rb_str_resize(buf, 128);
-    cbuf = RSTRING_PTR(buf);
-    prefix_toa2x(node->prefix, cbuf, 1);
-    rb_str_set_len(buf, strlen(cbuf));
-    rb_funcall(rb_stdout, id_printf, 2, fmt, buf);
-  } PATRICIA_WALK_END;
+  if (tree->head) {
+    PATRICIA_WALK(tree->head, node) {
+      rb_str_resize(buf, 128);
+      cbuf = RSTRING_PTR(buf);
+      prefix_toa2x(node->prefix, cbuf, 1);
+      rb_str_set_len(buf, strlen(cbuf));
+      rb_funcall(rb_stdout, id_printf, 2, fmt, buf);
+    } PATRICIA_WALK_END;
+  }
   return Qtrue;
 }
 
diff --git a/test/test_old_segfaults.rb b/test/test_old_segfaults.rb
index 0814150..5e7ec3e 100644
--- a/test/test_old_segfaults.rb
+++ b/test/test_old_segfaults.rb
@@ -18,4 +18,16 @@ class TestOldSegfaults < Test::Unit::TestCase
       assert_raises(NoMethodError) { matched.destroy }
     end
   end
+
+  def test_empty_show_nodes
+    assert_nothing_raised do
+      t = Patricia.new
+      t.show_nodes
+    end
+  end
+
+  def test_empty_num_nodes
+    t = Patricia.new
+    assert_equal 0, t.num_nodes
+  end
 end