Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
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
6 changes: 6 additions & 0 deletions spec/std/hash_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -323,6 +323,12 @@ describe "Hash" do
h1["bar"].should eq([2])
end

it "raises on initialize if set to a non-postive value" do
expect_raises ArgumentError, "Hash capacity must be positive" do
Hash(Int32, Int32).new(initial_capacity: -1) { 1234 }
end
end

it "initializes with default value" do
h = Hash(Int32, Int32).new(10)
h[0].should eq(10)
Expand Down
2 changes: 1 addition & 1 deletion src/hash.cr
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,8 @@ class Hash(K, V)

def initialize(block : (Hash(K, V), K -> V)? = nil, initial_capacity = nil)
initial_capacity ||= 11
initial_capacity = 11 if initial_capacity < 11
initial_capacity = initial_capacity.to_i
raise ArgumentError.new("Hash capacity must be positive") if initial_capacity <= 0
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I don't think it should raise if initial_capacity == 0

The user might want to create a Hash with initial capacity of 0. Even if it seems pointless, there might be some cases where it is usefull!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agree

@buckets = Pointer(Entry(K, V)?).malloc(initial_capacity)
@buckets_size = initial_capacity
@size = 0
Expand Down