diff --git a/src/string.c b/src/string.c index c191fcbb7..d9b973866 100644 --- a/src/string.c +++ b/src/string.c @@ -2956,6 +2956,9 @@ str_bytesplice(mrb_state *mrb, mrb_value str, mrb_int idx1, mrb_int len1, mrb_va if (RSTR_LEN(s) < idx1 || idx1 < 0 || RSTRING_LEN(replace) < idx2 || idx2 < 0) { mrb_raise(mrb, E_INDEX_ERROR, "index out of string"); } + if (len1 < 0 || len2 < 0) { + mrb_raise(mrb, E_INDEX_ERROR, "negative length"); + } mrb_int n; if (mrb_int_add_overflow(idx1, len1, &n) || RSTR_LEN(s) < n) { len1 = RSTR_LEN(s) - idx1; diff --git a/test/t/string.rb b/test/t/string.rb index 0b9916b59..cb06be629 100644 --- a/test/t/string.rb +++ b/test/t/string.rb @@ -960,4 +960,7 @@ assert('String#bytesplice') do assert_equal "0ab3456789", "0123456789".bytesplice(-9, 2, "ab") assert_equal "ab23456789", "0123456789".bytesplice(-10, 2, "ab") assert_raise(IndexError) { "0123456789".bytesplice(-11, 2, "ab") } + + # check the negative length + assert_raise(IndexError) { "0123456789".bytesplice(3, -4, "ab") } end