Skip to content

Commit

Permalink
Make Array#pop and Array#shift raise when empty
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite committed Sep 18, 2013
1 parent d7765e0 commit 52700ad
Show file tree
Hide file tree
Showing 2 changed files with 34 additions and 16 deletions.
46 changes: 32 additions & 14 deletions bootstrap/spec/std/array_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -225,20 +225,6 @@ describe "Array" do
end
end

describe "shift" do
it "shifts when non empty" do
a = [1, 2, 3]
a.shift.should eq(1)
a.should eq([2, 3])
end

it "shifts when empty" do
a = [] of Int32
a.shift.should be_nil
a.should eq([] of Int32)
end
end

describe "unshift" do
assert do
a = [2, 3]
Expand Down Expand Up @@ -313,4 +299,36 @@ describe "Array" do
b = [1, 2, [3]]
a.hash.should eq(b.hash)
end

describe "pop" do
it "pops when non empty" do
a = [1, 2, 3]
a.pop.should eq(3)
a.should eq([1, 2])
end

it "raises when empty" do
begin
([] of Int32).pop
fail "expected to raise Array::IndexOutOfBounds"
rescue Array::IndexOutOfBounds
end
end
end

describe "shift" do
it "shifts when non empty" do
a = [1, 2, 3]
a.shift.should eq(1)
a.should eq([2, 3])
end

it "raises when empty" do
begin
([] of Int32).shift
fail "expected to raise Array::IndexOutOfBounds"
rescue Array::IndexOutOfBounds
end
end
end
end
4 changes: 2 additions & 2 deletions std/array.cr
Original file line number Diff line number Diff line change
Expand Up @@ -89,13 +89,13 @@ class Array(T)
end

def pop
return nil if @length == 0
raise IndexOutOfBounds.new if @length == 0
@length -= 1
@buffer[@length]
end

def shift
return nil if @length == 0
raise IndexOutOfBounds.new if @length == 0
value = @buffer[0]
@length -=1
@buffer.memmove(@buffer + 1, @length)
Expand Down

0 comments on commit 52700ad

Please sign in to comment.