From 52700ad5925fbe093771a114e829595e386c9a01 Mon Sep 17 00:00:00 2001 From: Ary Borenszweig Date: Wed, 18 Sep 2013 11:51:53 -0300 Subject: [PATCH] Make Array#pop and Array#shift raise when empty --- bootstrap/spec/std/array_spec.cr | 46 ++++++++++++++++++++++---------- std/array.cr | 4 +-- 2 files changed, 34 insertions(+), 16 deletions(-) diff --git a/bootstrap/spec/std/array_spec.cr b/bootstrap/spec/std/array_spec.cr index e40f5353924d..b0479d003801 100755 --- a/bootstrap/spec/std/array_spec.cr +++ b/bootstrap/spec/std/array_spec.cr @@ -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] @@ -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 diff --git a/std/array.cr b/std/array.cr index 12d9516b8e3a..e420e7c8d9a9 100644 --- a/std/array.cr +++ b/std/array.cr @@ -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)