Skip to content

Commit

Permalink
Deque: let new with block infer the element type
Browse files Browse the repository at this point in the history
  • Loading branch information
asterite committed Dec 20, 2016
1 parent df2890a commit 7f0182c
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 12 deletions.
2 changes: 1 addition & 1 deletion spec/std/deque_spec.cr
Expand Up @@ -102,7 +102,7 @@ describe "Deque" do
end

it "creates with default value in block" do
deq = Deque(Int32).new(5) { |i| i * 2 }
deq = Deque.new(5) { |i| i * 2 }
deq.should eq(Deque{0, 2, 4, 6, 8})
end

Expand Down
20 changes: 9 additions & 11 deletions src/deque.cr
Expand Up @@ -19,6 +19,8 @@ class Deque(T)
# (this Deque has 5 items, each equal to their index)

@start = 0
protected setter size
protected getter buffer

# Creates a new empty Deque
def initialize
Expand Down Expand Up @@ -74,23 +76,19 @@ class Deque(T)
# value in that index.
#
# ```
# Deque(Int32).new(3) { |i| (i + 1) ** 2 } # => Deque{1, 4, 9}
# Deque.new(3) { |i| (i + 1) ** 2 } # => Deque{1, 4, 9}
# ```
def initialize(size : Int, &block : Int32 -> T)
def self.new(size : Int, &block : Int32 -> T)
if size < 0
raise ArgumentError.new("negative deque size: #{size}")
end
@size = size.to_i
@capacity = size.to_i

if @capacity == 0
@buffer = Pointer(T).null
else
@buffer = Pointer(T).malloc(@capacity)
(0...@size).each do |i|
@buffer[i] = yield i
end
deque = Deque(T).new(size)
deque.size = size
size.to_i.times do |i|
deque.buffer[i] = yield i
end
deque
end

# Creates a new Deque that copies its items from an Array.
Expand Down

0 comments on commit 7f0182c

Please sign in to comment.