view julia/cb.jl @ 3:c1db337c15be

Reorganize files
author Lewin Bormann <lbo@spheniscida.de>
date Tue, 14 Feb 2023 21:12:06 +0100
parents
children
line wrap: on
line source

mutable struct CircularBuffer{T}
    b::Vector{T}
    first::Int
    last::Int
    count::Int

    function CircularBuffer{T}(capacity::Integer) where {T}
        new(Vector{T}(undef, capacity), 1, 0, 0)
    end
end

function Base.push!(cb::CircularBuffer, item; overwrite::Bool=false)
    if !overwrite || (overwrite && cb.count < length(cb.b))
        if cb.count >= length(cb.b)
            error("buffer is full")
        end
        cb.last = cb.last%length(cb.b) + 1
        cb.b[cb.last] = item
        cb.count += 1
    else
        cb.b[cb.first] = item
        cb.first = cb.first%length(cb.b) + 1
    end
end

function Base.popfirst!(cb::CircularBuffer)
    if cb.count <= 0
        error("buffer is empty")
    end
    e = cb.b[cb.first]
    #cb.b[cb.first] = undef
    cb.first = cb.first%length(cb.b) + 1
    cb.count -= 1
    e
end

function Base.empty!(cb::CircularBuffer)
    cb.count = 0
    cb.first = 1
    cb.last = 0
end