diff --git a/mrbgems/mruby-array-ext/mrblib/array.rb b/mrbgems/mruby-array-ext/mrblib/array.rb index 524d01658..d81838338 100644 --- a/mrbgems/mruby-array-ext/mrblib/array.rb +++ b/mrbgems/mruby-array-ext/mrblib/array.rb @@ -686,9 +686,8 @@ class Array i += 1 end else - if n > 0 + if state = __combination_init(n, permutation) # Use C iterator for complex cases - state = __combination_init(n, permutation) while tmp = __combination_next(state) yield tmp end diff --git a/mrbgems/mruby-array-ext/src/array.c b/mrbgems/mruby-array-ext/src/array.c index 100dce030..4ea183987 100644 --- a/mrbgems/mruby-array-ext/src/array.c +++ b/mrbgems/mruby-array-ext/src/array.c @@ -1551,6 +1551,10 @@ ary_combination_init(mrb_state *mrb, mrb_value self) } #endif + if (n < 1 || RARRAY_LEN(self) < 1) { + return mrb_nil_value(); + } + struct RData *d; struct mrb_combination_state *state; Data_Make_Struct(mrb, mrb->object_class, struct mrb_combination_state, @@ -1559,11 +1563,8 @@ ary_combination_init(mrb_state *mrb, mrb_value self) state->n = n; state->array_size = RARRAY_LEN(self); state->permutation = permutation; - state->finished = (n <= 0 && n != 0); - - if (n > 0) { - state->indices = (mrb_int*)mrb_calloc(mrb, n, sizeof(mrb_int)); - } + state->finished = FALSE; + state->indices = (mrb_int*)mrb_calloc(mrb, n, sizeof(mrb_int)); return mrb_obj_value(d); } @@ -1586,12 +1587,6 @@ ary_combination_next(mrb_state *mrb, mrb_value self) mrb_raise(mrb, E_RUNTIME_ERROR, "array modified during iteration"); } - /* Edge case: empty array */ - if (state->array_size == 0) { - state->finished = TRUE; - return mrb_nil_value(); - } - /* Validate current indices are still in bounds */ for (mrb_int i = 0; i < state->n; i++) { if (state->indices[i] >= state->array_size) {