Skip to content
Merged
Changes from 2 commits
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
36 changes: 30 additions & 6 deletions src/deque.cr
Original file line number Diff line number Diff line change
Expand Up @@ -363,7 +363,7 @@ class Deque(T)
return unshift(value) if index == 0
return push(value) if index == @size

increase_capacity if @size >= @capacity
resize_if_cant_insert
rindex = @start + index
rindex -= @capacity if rindex >= @capacity

Expand Down Expand Up @@ -474,7 +474,7 @@ class Deque(T)
# a.push 3 # => Deque{1, 2, 3}
# ```
def push(value : T)
increase_capacity if @size >= @capacity
resize_if_cant_insert
index = @start + @size
index -= @capacity if index >= @capacity
@buffer[index] = value
Expand Down Expand Up @@ -556,7 +556,7 @@ class Deque(T)
# a.unshift 0 # => Deque{0, 1, 2}
# ```
def unshift(value : T) : self
increase_capacity if @size >= @capacity
resize_if_cant_insert
@start -= 1
@start += @capacity if @start < 0
@buffer[@start] = value
Expand All @@ -581,15 +581,39 @@ class Deque(T)
end
end

private def increase_capacity
private INITIAL_CAPACITY = 4

# behaves like `calculate_new_capacity(@capacity + 1)`
private def calculate_new_capacity
return INITIAL_CAPACITY if @capacity == 0

@capacity * 2
end
Comment thread
HertzDevil marked this conversation as resolved.

private def calculate_new_capacity(new_size)
new_capacity = @capacity == 0 ? INITIAL_CAPACITY : @capacity
while new_capacity < new_size
new_capacity *= 2
end
new_capacity
end

private def resize_if_cant_insert(insert_size = 1)
new_capacity = calculate_new_capacity(@size + insert_size)
if new_capacity > @capacity
resize_to_capacity(new_capacity)
end
end

private def resize_to_capacity(capacity)
unless @buffer
@capacity = 4
@capacity = capacity
@buffer = Pointer(T).malloc(@capacity)
return
end

old_capacity = @capacity
@capacity *= 2
@capacity = capacity
Comment thread
HertzDevil marked this conversation as resolved.
Outdated
@buffer = @buffer.realloc(@capacity)

finish = @start + @size
Expand Down