Skip to content

Commit

Permalink
adding the square method to Stree::String
Browse files Browse the repository at this point in the history
  • Loading branch information
tenderlove committed Dec 16, 2009
1 parent 9c23ee8 commit 8d1fe49
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 2 deletions.
22 changes: 20 additions & 2 deletions ext/stree/stree_string.c
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -2,8 +2,9 @@


VALUE cStreeString; VALUE cStreeString;


static void dealloc(LST_String * ptr) static void dealloc(void * ptr)
{ {
lst_string_free((LST_String *)ptr);
} }


static VALUE allocate(VALUE klass) static VALUE allocate(VALUE klass)
Expand All @@ -17,7 +18,7 @@ static VALUE initialize(VALUE self, VALUE string)
LST_String * ptr; LST_String * ptr;


Data_Get_Struct(self, LST_String, ptr); Data_Get_Struct(self, LST_String, ptr);
lst_string_init(ptr, StringValuePtr(string), 1, RSTRING_LEN(string)); lst_string_init(ptr, StringValuePtr(string), sizeof(char), RSTRING_LEN(string));


return self; return self;
} }
Expand All @@ -30,11 +31,28 @@ static VALUE bytesize(VALUE self)
return INT2NUM(lst_string_get_length(ptr)); return INT2NUM(lst_string_get_length(ptr));
} }


static VALUE get(VALUE self, VALUE index)
{
LST_String * ptr;

Data_Get_Struct(self, LST_String, ptr);

void * item = lst_string_get_item(ptr, NUM2INT(index));

if(NULL == item) return Qnil;

char * c = ((char *)item)[0];

if(c) return INT2NUM(((char *)item)[0]);
return Qnil;
}

void Init_stree_string() void Init_stree_string()
{ {
cStreeString = rb_define_class_under(cStree, "String", rb_cObject); cStreeString = rb_define_class_under(cStree, "String", rb_cObject);
rb_define_alloc_func(cStreeString, allocate); rb_define_alloc_func(cStreeString, allocate);


rb_define_method(cStreeString, "initialize", initialize, 1); rb_define_method(cStreeString, "initialize", initialize, 1);
rb_define_method(cStreeString, "bytesize", bytesize, 0); rb_define_method(cStreeString, "bytesize", bytesize, 0);
rb_define_method(cStreeString, "[]", get, 1);
} }
15 changes: 15 additions & 0 deletions test/test_string.rb
Original file line number Original file line Diff line number Diff line change
Expand Up @@ -7,5 +7,20 @@ def test_bytesize
str = "foo" str = "foo"
assert_equal str.bytesize, Stree::String.new(str).bytesize assert_equal str.bytesize, Stree::String.new(str).bytesize
end end

def test_square
str = "foo"
sstr = Stree::String.new(str)

if str.respond_to?(:getbyte)
0.upto(str.bytesize) do |i|
assert_equal str.getbyte(i), sstr[i], "failed on #{i}"
end
else
0.upto(str.bytesize) do |i|
assert_equal str[i], sstr[i], "failed on #{i}"
end
end
end
end end
end end

0 comments on commit 8d1fe49

Please sign in to comment.