Merge pull request #6776 from dearblue/array-combination.3

Return nil if a number less than 1 is passed to `Array#__combination_init`
This commit is contained in:
Yukihiro "Matz" Matsumoto
2026-05-02 23:41:04 +09:00
committed by GitHub
2 changed files with 7 additions and 13 deletions
+1 -2
View File
@@ -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
+6 -11
View File
@@ -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) {