From 4bfd993c3039fca23176896eac6e21688ce2d8a0 Mon Sep 17 00:00:00 2001 From: Jan Zajic Date: Sat, 9 Nov 2019 21:12:23 +0100 Subject: [PATCH] change byte_slice(Int) ArgumentError->IndexError when out of range --- spec/std/string_spec.cr | 12 ++++++++++++ src/string.cr | 6 ++++-- 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/spec/std/string_spec.cr b/spec/std/string_spec.cr index 8ace564ab67f..ececca3c7766 100644 --- a/spec/std/string_spec.cr +++ b/spec/std/string_spec.cr @@ -229,6 +229,18 @@ describe "String" do it "gets byte_slice with negative index" do "hello".byte_slice(-2, 3).should eq("lo") end + + it "gets byte_slice(Int) with with start out of bounds" do + expect_raises(IndexError) do + "hello".byte_slice(10) + end + end + + it "gets byte_slice(Int) with with start out of bounds" do + expect_raises(IndexError) do + "hello".byte_slice(-10) + end + end end describe "to_i" do diff --git a/src/string.cr b/src/string.cr index dac1b98bf53f..7dd2e1b18c86 100644 --- a/src/string.cr +++ b/src/string.cr @@ -953,8 +953,10 @@ class String end end - def byte_slice(start : Int) - byte_slice start, bytesize - start + def byte_slice(start : Int) : String + count = bytesize - start + raise IndexError.new if start > 0 && count < 0 + byte_slice start, count end # Returns a substring starting from the *start* byte.