Skip to content

Commit 7f8cc2b

Browse files
Merge branch 'master' into master
2 parents a928965 + 2e74620 commit 7f8cc2b

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
@@ -229,3 +229,25 @@ Base.@propagate_inbounds function Base.last(cb::CircularBuffer)
229229
@boundscheck (cb.length == 0) && throw(BoundsError(cb, 1))
230230
return cb.buffer[_buffer_index(cb, cb.length)]
231231
end
232+
233+
"""
234+
resize!(cb::CircularBuffer, n)
235+
236+
Resize CircularBuffer to the maximum capacity of n elements.
237+
If n is smaller than the current buffer length, the first n elements will be retained.
238+
"""
239+
function Base.resize!(cb::CircularBuffer, n::Integer)
240+
if n != capacity(cb)
241+
buf_new = Vector{eltype(cb)}(undef, n)
242+
len_new = min(length(cb), n)
243+
for i in 1:len_new
244+
@inbounds buf_new[i] = cb[i]
245+
end
246+
247+
cb.capacity = n
248+
cb.first = 1
249+
cb.length = len_new
250+
cb.buffer = buf_new
251+
end
252+
return cb
253+
end

test/test_circular_buffer.jl

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -174,4 +174,28 @@
174174
@test size(cb) == (1,)
175175
end
176176

177+
@testset "resize!" begin
178+
@testset "resize an empty buffer" begin
179+
cb = CircularBuffer{Int}(3)
180+
resize!(cb, 10)
181+
@test isempty(cb) && capacity(cb) == 10
182+
end
183+
@testset "resize a non empty buffer to smaller size" begin
184+
cb = CircularBuffer{Int}(10)
185+
append!(cb, -7:10)
186+
resize!(cb, 6)
187+
@test cb == 1:6
188+
append!(cb, 7:8)
189+
@test cb == 3:8
190+
end
191+
@testset "resize a non empty buffer to larger size" begin
192+
cb = CircularBuffer{Int}(10)
193+
append!(cb, -7:10)
194+
resize!(cb, 15)
195+
@test cb == 1:10
196+
append!(cb, 11:20)
197+
@test cb == 6:20
198+
end
199+
end
200+
177201
end

0 commit comments

Comments
 (0)