Skip to content

Commit

Permalink
* struct.c: Support for Struct's enumerators #size
Browse files Browse the repository at this point in the history
  • Loading branch information
marcandre committed Oct 31, 2012
1 parent 539cddd commit 6a15b4f
Show file tree
Hide file tree
Showing 2 changed files with 13 additions and 3 deletions.
9 changes: 6 additions & 3 deletions struct.c
Expand Up @@ -429,6 +429,9 @@ rb_struct_new(VALUE klass, ...)
return rb_class_new_instance(size, mem, klass);
}

static VALUE
rb_struct_size(VALUE s);

/*
* call-seq:
* struct.each {|obj| block } -> struct
Expand All @@ -455,7 +458,7 @@ rb_struct_each(VALUE s)
{
long i;

RETURN_ENUMERATOR(s, 0, 0);
RETURN_SIZED_ENUMERATOR(s, 0, 0, rb_struct_size);
for (i=0; i<RSTRUCT_LEN(s); i++) {
rb_yield(RSTRUCT_PTR(s)[i]);
}
Expand Down Expand Up @@ -489,7 +492,7 @@ rb_struct_each_pair(VALUE s)
VALUE members;
long i;

RETURN_ENUMERATOR(s, 0, 0);
RETURN_SIZED_ENUMERATOR(s, 0, 0, rb_struct_size);
members = rb_struct_members(s);
for (i=0; i<RSTRUCT_LEN(s); i++) {
rb_yield_values(2, rb_ary_entry(members, i), RSTRUCT_PTR(s)[i]);
Expand Down Expand Up @@ -793,7 +796,7 @@ rb_struct_select(int argc, VALUE *argv, VALUE s)
long i;

rb_check_arity(argc, 0, 0);
RETURN_ENUMERATOR(s, 0, 0);
RETURN_SIZED_ENUMERATOR(s, 0, 0, rb_struct_size);
result = rb_ary_new();
for (i = 0; i < RSTRUCT_LEN(s); i++) {
if (RTEST(rb_yield(RSTRUCT_PTR(s)[i]))) {
Expand Down
7 changes: 7 additions & 0 deletions test/ruby/test_enumerator.rb
Expand Up @@ -456,6 +456,13 @@ def test_size_for_enum_created_from_env
end
end

def test_size_for_enum_created_from_struct
s = Struct.new(:foo, :bar, :baz).new(1, 2)
%i[each each_pair select].each do |method|
assert_equal 3, s.send(method).size
end
end

def check_consistency_for_combinatorics(method)
[ [], [:a, :b, :c, :d, :e] ].product([-2, 0, 2, 5, 6]) do |array, arg|
assert_equal array.send(method, arg).to_a.size, array.send(method, arg).size,
Expand Down

0 comments on commit 6a15b4f

Please sign in to comment.