Skip to content

Commit b8d9793

Browse files
sairus7oxinabox
authored andcommitted
CircularBuffer: Added first/last methods that slightly improve performance (JuliaCollections#543)
* Added first/last methods that slightly improve performance * Added reset! for circular buffer * vestion+ * Revert "Added reset! for circular buffer" This reverts commit e43b3b2.
1 parent b0b4373 commit b8d9793

File tree

3 files changed

+28
-1
lines changed

3 files changed

+28
-1
lines changed

Project.toml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
name = "DataStructures"
22
uuid = "864edb3b-99cc-5e75-8d2d-829cb0a9cfe8"
3-
version = "0.17.2"
3+
version = "0.17.3"
44

55
[deps]
66
InteractiveUtils = "b77e0a4c-d291-57a0-90e8-8db25a27a240"

src/circular_buffer.jl

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -193,3 +193,26 @@ capacity(cb::CircularBuffer) = cb.capacity
193193
Test whether the buffer is full.
194194
"""
195195
isfull(cb::CircularBuffer) = length(cb) == cb.capacity
196+
197+
"""
198+
first(cb)
199+
200+
Get the first element of CircularBuffer.
201+
"""
202+
Base.@propagate_inbounds function Base.first(cb::CircularBuffer)
203+
@boundscheck if cb.length == 0
204+
throw(BoundsError(cb, 1))
205+
end
206+
cb.buffer[cb.first]
207+
end
208+
"""
209+
last(cb)
210+
211+
Get the last element of CircularBuffer.
212+
"""
213+
Base.@propagate_inbounds function Base.last(cb::CircularBuffer)
214+
@boundscheck if cb.length == 0
215+
throw(BoundsError(cb, 1))
216+
end
217+
cb.buffer[_buffer_index(cb, cb.length)]
218+
end

test/test_circular_buffer.jl

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66
@test length(cb) == 0
77
@test capacity(cb) == 5
88
@test_throws BoundsError first(cb)
9+
@test_throws BoundsError last(cb)
910
@test isempty(cb) == true
1011
@test isfull(cb) == false
1112
@test eltype(cb) == Int
@@ -17,6 +18,7 @@
1718
@test length(cb) == 1
1819
@test capacity(cb) == 5
1920
@test isfull(cb) == false
21+
@test first(cb) == last(cb)
2022
end
2123

2224
@testset "Appending many elements" begin
@@ -38,6 +40,8 @@
3840
@test_throws BoundsError cb[3:6]
3941
@test cb[3:4] == Int[6,7]
4042
@test cb[[1,5]] == Int[4,8]
43+
@test first(cb) == 4
44+
@test last(cb) == 8
4145
end
4246

4347
@testset "setindex" begin

0 commit comments

Comments
 (0)