Skip to content

Commit

Permalink
Merge pull request #780 from robert-wright/master
Browse files Browse the repository at this point in the history
Proposed bug fix for bad state when using CircularBuffer push!
  • Loading branch information
oxinabox authored Feb 8, 2022
2 parents 2e74620 + 4503128 commit f90dd8c
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 2 deletions.
8 changes: 6 additions & 2 deletions src/circular_buffer.jl
Original file line number Diff line number Diff line change
Expand Up @@ -101,14 +101,18 @@ end
Add an element to the back and overwrite front if full.
"""
@inline function Base.push!(cb::CircularBuffer, data)
@inline function Base.push!(cb::CircularBuffer{T}, data) where T

# As per the behaviour of Base.push!
data_converted = convert(T, data)

# if full, increment and overwrite, otherwise push
if cb.length == cb.capacity
cb.first = (cb.first == cb.capacity ? 1 : cb.first + 1)
else
cb.length += 1
end
@inbounds cb.buffer[_buffer_index(cb, cb.length)] = data
@inbounds cb.buffer[_buffer_index(cb, cb.length)] = data_converted
return cb
end

Expand Down
9 changes: 9 additions & 0 deletions test/test_circular_buffer.jl
Original file line number Diff line number Diff line change
Expand Up @@ -165,6 +165,15 @@
end
end

@testset "Issue 754" begin
cb = CircularBuffer{Int}(5)
@test size(cb) == (0,)
@test_throws InexactError push!(cb, 1.5)
@test size(cb) == (0,)
push!(cb, 1.0)
@test size(cb) == (1,)
end

@testset "resize!" begin
@testset "resize an empty buffer" begin
cb = CircularBuffer{Int}(3)
Expand Down

0 comments on commit f90dd8c

Please sign in to comment.