Skip to content

Commit

Permalink
change byte_slice(Int) ArgumentError->IndexError when out of range
Browse files Browse the repository at this point in the history
  • Loading branch information
jan-zajic committed Apr 8, 2020
1 parent 4025c52 commit 4bfd993
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 2 deletions.
12 changes: 12 additions & 0 deletions spec/std/string_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 4 additions & 2 deletions src/string.cr
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down

0 comments on commit 4bfd993

Please sign in to comment.