Skip to content

Commit 7f0182c

Browse files
author
Ary Borenszweig
committedDec 20, 2016
Deque: let new with block infer the element type
1 parent df2890a commit 7f0182c

File tree

2 files changed

+10
-12
lines changed

2 files changed

+10
-12
lines changed
 

‎spec/std/deque_spec.cr

+1-1
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ describe "Deque" do
102102
end
103103

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

‎src/deque.cr

+9-11
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,8 @@ class Deque(T)
1919
# (this Deque has 5 items, each equal to their index)
2020

2121
@start = 0
22+
protected setter size
23+
protected getter buffer
2224

2325
# Creates a new empty Deque
2426
def initialize
@@ -74,23 +76,19 @@ class Deque(T)
7476
# value in that index.
7577
#
7678
# ```
77-
# Deque(Int32).new(3) { |i| (i + 1) ** 2 } # => Deque{1, 4, 9}
79+
# Deque.new(3) { |i| (i + 1) ** 2 } # => Deque{1, 4, 9}
7880
# ```
79-
def initialize(size : Int, &block : Int32 -> T)
81+
def self.new(size : Int, &block : Int32 -> T)
8082
if size < 0
8183
raise ArgumentError.new("negative deque size: #{size}")
8284
end
83-
@size = size.to_i
84-
@capacity = size.to_i
8585

86-
if @capacity == 0
87-
@buffer = Pointer(T).null
88-
else
89-
@buffer = Pointer(T).malloc(@capacity)
90-
(0...@size).each do |i|
91-
@buffer[i] = yield i
92-
end
86+
deque = Deque(T).new(size)
87+
deque.size = size
88+
size.to_i.times do |i|
89+
deque.buffer[i] = yield i
9390
end
91+
deque
9492
end
9593

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

0 commit comments

Comments
 (0)
Please sign in to comment.