Skip to content

Commit 7ea71f8

Browse files
Clarify _buffer_index behavior
1 parent 020a842 commit 7ea71f8

File tree

2 files changed

+29
-11
lines changed

2 files changed

+29
-11
lines changed

src/CircularArrayBuffers.jl

Lines changed: 28 additions & 10 deletions
Original file line numberDiff line numberDiff line change
@@ -76,24 +76,42 @@ capacity(cb::CircularArrayBuffer{T,N}) where {T,N} = size(cb.buffer, N)
7676
isfull(cb::CircularArrayBuffer) = cb.nframes == capacity(cb)
7777
Base.isempty(cb::CircularArrayBuffer) = cb.nframes == 0
7878

79+
"""
80+
_buffer_index(cb::CircularArrayBuffer, i::Int)
81+
82+
Return the index of the `i`-th element in the buffer.
83+
"""
7984
@inline function _buffer_index(cb::CircularArrayBuffer, i::Int)
80-
ind = (cb.first - 1) * cb.step_size + i
81-
if ind > length(cb.buffer)
82-
ind - length(cb.buffer)
85+
idx = (cb.first - 1) * cb.step_size + i
86+
return wrap_index(idx, length(cb.buffer))
87+
end
88+
@inline _buffer_index(cb::CircularArrayBuffer, I::AbstractVector{<:Integer}) = map(Base.Fix1(_buffer_index, cb), I)
89+
90+
"""
91+
wrap_index(idx, n)
92+
93+
Return the index of the `idx`-th element in the buffer, if index is one past the size, return 1, else error.
94+
"""
95+
function wrap_index(idx, n)
96+
if idx <= n
97+
return idx
98+
elseif idx <= 2n
99+
return idx - n
83100
else
84-
ind
101+
@info "oops! idx $(idx) > 2n $(2n)"
102+
return idx - n
85103
end
86104
end
87-
@inline _buffer_index(cb::CircularArrayBuffer, I::AbstractVector{<:Integer}) = map(Base.Fix1(_buffer_index, cb), I)
88105

106+
"""
107+
_buffer_frame(cb::CircularArrayBuffer, i::Int)
108+
109+
Return the index of the `i`-th frame in the buffer.
110+
"""
89111
@inline function _buffer_frame(cb::CircularArrayBuffer, i::Int)
90112
n = capacity(cb)
91113
idx = cb.first + i - 1
92-
if idx > n
93-
idx - n
94-
else
95-
idx
96-
end
114+
return wrap_index(idx, n)
97115
end
98116

99117
_buffer_frame(cb::CircularArrayBuffer, I::CartesianIndex) = CartesianIndex(map(i->_buffer_frame(cb, i), Tuple(I)))

test/runtests.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -231,7 +231,7 @@ if CUDA.functional()
231231
@test isempty(b) == true
232232
@test length(b) == 0
233233
@test size(b) == (0,)
234-
# element must has the exact same length with the element of buffer
234+
# element must have the exact same length with the element of buffer
235235
@test_throws Exception push!(b, [1, 2])
236236

237237
for x in 1:3

0 commit comments

Comments
 (0)