From 28316a1d951d8dd5a1c8b8eb31149f82dd29ff3b Mon Sep 17 00:00:00 2001 From: Eric Wong Date: Wed, 1 Sep 2010 18:03:13 -0700 Subject: tree-walking on empty trees no longer segfaults Patricia#num_nodes properly returns zero and Patricia#show_nodes displays nothing. --- ext/rpatricia/rpatricia.c | 18 ++++++++++-------- test/test_old_segfaults.rb | 12 ++++++++++++ 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 -- cgit v1.2.3-24-ge0c7