Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Iterators.reverse for MemoryView #4

Merged
merged 1 commit into from
Oct 24, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading