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

Methods for growing and shrinking an array #11485

Open
wants to merge 10 commits into
base: master
Choose a base branch
from
14 changes: 14 additions & 0 deletions spec/std/array_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -2041,4 +2041,18 @@ describe "Array" do
ary.skip(-1)
end
end

it "#resize" do
beta-ziliani marked this conversation as resolved.
Show resolved Hide resolved
ary = [1, 2, 3]
ary.resize(3).should eq([1, 2, 3])
ary.resize(4).should eq([1, 2, 3])
ary.remaining_capacity.should eq(4)
ary.shift
ary.resize(3).should eq([2, 3])
ary.remaining_capacity.should eq(2)

expect_raises(ArgumentError, "Insufficient capacity: 2 cannot hold 2 elements with an offset of 1") do
beta-ziliani marked this conversation as resolved.
Show resolved Hide resolved
ary.resize(2)
end
end
end
12 changes: 12 additions & 0 deletions src/array.cr
Original file line number Diff line number Diff line change
Expand Up @@ -2029,6 +2029,18 @@ class Array(T)
@capacity - @offset_to_buffer
end

# Resizes the internal buffer to hold `capacity - @offset_to_buffer` items.
# This method is intended for expert users that needs to manually grow or
# shrink arrays.
def resize(capacity) : self
if capacity - @offset_to_buffer >= @size
resize_to_capacity capacity
else
raise ArgumentError.new("Insufficient capacity: #{capacity} cannot hold #{@size} elements with an offset of #{@offset_to_buffer}")
end
self
end

private def double_capacity
resize_to_capacity(@capacity == 0 ? 3 : (@capacity * 2))
end
Expand Down