Skip to content

Commit 2e74620

Browse files
authored
Merge pull request #784 from johannes-fischer/circular_buffer_resize
Implement resize! for CircularBuffer
2 parents 99d214b + 347a37a commit 2e74620

File tree

2 files changed

+46
-0
lines changed

2 files changed

+46
-0
lines changed

src/circular_buffer.jl

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -225,3 +225,25 @@ Base.@propagate_inbounds function Base.last(cb::CircularBuffer)
225225
@boundscheck (cb.length == 0) && throw(BoundsError(cb, 1))
226226
return cb.buffer[_buffer_index(cb, cb.length)]
227227
end
228+
229+
"""
230+
resize!(cb::CircularBuffer, n)
231+
232+
Resize CircularBuffer to the maximum capacity of n elements.
233+
If n is smaller than the current buffer length, the first n elements will be retained.
234+
"""
235+
function Base.resize!(cb::CircularBuffer, n::Integer)
236+
if n != capacity(cb)
237+
buf_new = Vector{eltype(cb)}(undef, n)
238+
len_new = min(length(cb), n)
239+
for i in 1:len_new
240+
@inbounds buf_new[i] = cb[i]
241+
end
242+
243+
cb.capacity = n
244+
cb.first = 1
245+
cb.length = len_new
246+
cb.buffer = buf_new
247+
end
248+
return cb
249+
end

test/test_circular_buffer.jl

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -164,4 +164,28 @@
164164
@test Array(cb) == [21, 42, 42]
165165
end
166166
end
167+
168+
@testset "resize!" begin
169+
@testset "resize an empty buffer" begin
170+
cb = CircularBuffer{Int}(3)
171+
resize!(cb, 10)
172+
@test isempty(cb) && capacity(cb) == 10
173+
end
174+
@testset "resize a non empty buffer to smaller size" begin
175+
cb = CircularBuffer{Int}(10)
176+
append!(cb, -7:10)
177+
resize!(cb, 6)
178+
@test cb == 1:6
179+
append!(cb, 7:8)
180+
@test cb == 3:8
181+
end
182+
@testset "resize a non empty buffer to larger size" begin
183+
cb = CircularBuffer{Int}(10)
184+
append!(cb, -7:10)
185+
resize!(cb, 15)
186+
@test cb == 1:10
187+
append!(cb, 11:20)
188+
@test cb == 6:20
189+
end
190+
end
167191
end

0 commit comments

Comments
 (0)