From 6bb0afad12139f7781254cb04531801b2a0435fa Mon Sep 17 00:00:00 2001 From: Tobias Wackenhut Date: Sat, 11 Aug 2018 01:52:58 +0200 Subject: [PATCH] Fixes #429 When using pushfirst! in a situation where length != capacity and first != 1 the buffer content is shifted by one internally which results in an incorrect buffer state. This commit fixes this issue. --- src/circular_buffer.jl | 8 +++----- test/test_circular_buffer.jl | 10 ++++++++++ 2 files changed, 13 insertions(+), 5 deletions(-) diff --git a/src/circular_buffer.jl b/src/circular_buffer.jl index 8b6490d38..8e9e63ab4 100644 --- a/src/circular_buffer.jl +++ b/src/circular_buffer.jl @@ -118,13 +118,11 @@ and overwrite back if full. """ function pushfirst!(cb::CircularBuffer, data) # if full, decrement and overwrite, otherwise pushfirst - if length(cb) == cb.capacity - cb.first = (cb.first == 1 ? cb.capacity : cb.first - 1) - cb[1] = data - else + cb.first = (cb.first == 1 ? cb.capacity : cb.first - 1) + if length(cb) < cb.capacity cb.length += 1 - pushfirst!(cb.buffer, data) end + cb.buffer[cb.first] = data cb end diff --git a/test/test_circular_buffer.jl b/test/test_circular_buffer.jl index e2de8f726..603859ad2 100644 --- a/test/test_circular_buffer.jl +++ b/test/test_circular_buffer.jl @@ -57,6 +57,16 @@ end end + @testset "Issue 429" begin + cb = CircularBuffer{Int}(5) + map(x -> pushfirst!(cb, x), 1:8) + pop!(cb) + pushfirst!(cb, 9) + @test length(cb.buffer) == cb.capacity + arr = convert(Array, cb) + @test arr == Int[9, 8, 7, 6, 5] + end + @testset "Issue 379" begin cb = CircularBuffer{Int}(5) pushfirst!(cb, 1)