From cfb9624460a295e4e1723301486d89058c228e07 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Thu, 11 Aug 2022 03:16:49 -0700 Subject: Fix Array#[] with ArithmeticSequence with negative steps (#5739) * Fix Array#[] with ArithmeticSequence with negative steps Previously, Array#[] when called with an ArithmeticSequence with a negative step did not handle all cases correctly, especially cases involving infinite ranges, inverted ranges, and/or exclusive ends. Fixes [Bug #18247] * Add Array#slice tests for ArithmeticSequence with negative step to test_array Add tests of rb_arithmetic_sequence_beg_len_step C-API function. * Fix ext/-test-/arith_seq/beg_len_step/depend * Rename local variables * Fix a variable name Co-authored-by: Kenta Murata <3959+mrkn@users.noreply.github.com> --- array.c | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) (limited to 'array.c') diff --git a/array.c b/array.c index b2ebf3c0e9..793a53f17b 100644 --- a/array.c +++ b/array.c @@ -1373,13 +1373,16 @@ ary_make_partial_step(VALUE ary, VALUE klass, long offset, long len, long step) const VALUE *values = RARRAY_CONST_PTR_TRANSIENT(ary); const long orig_len = len; - if ((step > 0 && step >= len) || (step < 0 && (step < -len))) { + if (step > 0 && step >= len) { VALUE result = ary_new(klass, 1); VALUE *ptr = (VALUE *)ARY_EMBED_PTR(result); RB_OBJ_WRITE(result, ptr, values[offset]); ARY_SET_EMBED_LEN(result, 1); return result; } + else if (step < 0 && step < -len) { + step = -len; + } long ustep = (step < 0) ? -step : step; len = (len + ustep - 1) / ustep; -- cgit v1.2.1