Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Array: fix range assignment index out of bounds #8347

Merged
merged 2 commits into from
Oct 18, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
24 changes: 24 additions & 0 deletions spec/std/array_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -379,6 +379,30 @@ describe "Array" do
a[nil..2] = [6, 7]
a.should eq([6, 7, 4, 5])
end

it "replaces entire range with a value for empty array (#8341)" do
a = [] of Int32
a[..] = 6
a.should eq([6])
end

it "pushes a new value with []=(...)" do
a = [1, 2, 3]
a[3..] = 4
a.should eq([1, 2, 3, 4])
end

it "replaces entire range with an array for empty array (#8341)" do
a = [] of Int32
a[..] = [1, 2, 3]
a.should eq([1, 2, 3])
end

it "concats a new array with []=(...)" do
a = [1, 2, 3]
a[3..] = [4, 5, 6]
a.should eq([1, 2, 3, 4, 5, 6])
end
end

describe "values_at" do
Expand Down
16 changes: 14 additions & 2 deletions src/array.cr
Original file line number Diff line number Diff line change
Expand Up @@ -400,7 +400,13 @@ class Array(T)
def []=(index : Int, count : Int, value : T)
raise ArgumentError.new "Negative count: #{count}" if count < 0

index = check_index_out_of_bounds index
index += size if index < 0

# We allow index == size because the range to replace
# can start at exactly the end of the array.
# So, we can't use check_index_out_of_bounds.
raise IndexError.new unless 0 <= index <= size
straight-shoota marked this conversation as resolved.
Show resolved Hide resolved

count = index + count <= size ? count : size - index

case count
Expand Down Expand Up @@ -456,7 +462,13 @@ class Array(T)
def []=(index : Int, count : Int, values : Array(T))
raise ArgumentError.new "Negative count: #{count}" if count < 0

index = check_index_out_of_bounds index
index += size if index < 0

# We allow index == size because the range to replace
# can start at exactly the end of the array.
# So, we can't use check_index_out_of_bounds.
raise IndexError.new unless 0 <= index <= size

count = index + count <= size ? count : size - index
diff = values.size - count

Expand Down