Skip to content

Commit

Permalink
Implement Iterators.reverse for MemoryView (#4)
Browse files Browse the repository at this point in the history
  • Loading branch information
jakobnissen authored Oct 24, 2024
1 parent d148281 commit 18da69e
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 2 deletions.
18 changes: 18 additions & 0 deletions src/basic.jl
Original file line number Diff line number Diff line change
Expand Up @@ -191,3 +191,21 @@ function Base.reverse(mem::MemoryView)
end
cp
end

struct ReverseMemoryView{T}
# I can't think of a reason to allow mutable memory views here
mem::ImmutableMemoryView{T}
end

function Iterators.reverse(mem::MemoryView{T}) where {T}
ReverseMemoryView{T}(ImmutableMemoryView(mem))
end
Iterators.reverse(x::ReverseMemoryView) = x.mem

Base.length(x::ReverseMemoryView) = length(x.mem)
Base.eltype(::Type{ReverseMemoryView{T}}) where {T} = T

function Base.iterate(x::ReverseMemoryView, state=length(x))
iszero(state) && return nothing
(@inbounds(x.mem[state]), state - 1)
end
14 changes: 12 additions & 2 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ end
@test first(mem) == UInt8('a')
@test last(mem) == UInt8('c')

memory = Memory{Float32}(undef, 6)
memory = Float32[0.1, -119.2, 150.3, Inf, -Inf]
mem = MemoryView(memory)
@test all(i == j for (i, j) in zip(mem, memory))
@test all(i === j for (i, j) in zip(mem, memory))
@test length(mem) == length(memory)
@test mem == memory

Expand Down Expand Up @@ -399,6 +399,16 @@ end
end
end

@testset "Iterators.reverse" begin
for v in Any[AbstractString["abc", "def", ""], Char['a', 'b'], UInt32[], Int16[9, 2, 1]]
mem = MemoryView(v)
it = Iterators.reverse(mem)
@test length(it) == length(mem)
@test collect(it) == reverse(mem)
@test Iterators.reverse(it) === ImmutableMemoryView(mem)
end
end

@testset "Equality" begin
v = rand(UInt, 10)
m1 = MemoryView(v)
Expand Down

0 comments on commit 18da69e

Please sign in to comment.