diff --git a/src/Utilities/lazy_iterators.jl b/src/Utilities/lazy_iterators.jl index 432bc5f2a8..fe5860781c 100644 --- a/src/Utilities/lazy_iterators.jl +++ b/src/Utilities/lazy_iterators.jl @@ -1,7 +1,11 @@ struct EmptyVector{T} <: AbstractVector{T} end + Base.size(::EmptyVector) = (0,) + Base.isempty(::EmptyVector) = true + Base.eltype(::EmptyVector{T}) where {T} = T + Base.iterate(::EmptyVector) = nothing """ @@ -18,21 +22,28 @@ struct LazyMap{T,VT,F} f::F data::VT end + function LazyMap{T}(f, data) where {T} return LazyMap{T,typeof(data),typeof(f)}(f, data) end + Base.size(it::LazyMap) = size(it.data) + Base.length(it::LazyMap) = length(it.data) + function Base.iterate(it::LazyMap, args...) elem_state = iterate(it.data, args...) if elem_state === nothing - return nothing + return else return it.f(elem_state[1]), elem_state[2] end end + Base.IteratorSize(it::LazyMap) = Base.IteratorSize(it.data) + Base.eltype(::LazyMap{T}) where {T} = T + function Iterators.reverse(it::LazyMap{T}) where {T} return LazyMap{T}(it.f, Iterators.reverse(it.data)) end diff --git a/test/Utilities/lazy_iterators.jl b/test/Utilities/lazy_iterators.jl index 0b3db20412..9222bf6266 100644 --- a/test/Utilities/lazy_iterators.jl +++ b/test/Utilities/lazy_iterators.jl @@ -1,10 +1,23 @@ -using Test +module TestLazyIterators + using MathOptInterface +using Test + const MOI = MathOptInterface -const MOIU = MOI.Utilities -@testset "EmptyVector{$T}" for T in [Int, Float64] - v = MOIU.EmptyVector{T}() +function runtests() + for name in names(@__MODULE__; all = true) + if startswith("$(name)", "test_") + @testset "$(name)" begin + getfield(@__MODULE__, name)() + end + end + end + return +end + +function _test_EmptyVector(T) + v = MOI.Utilities.EmptyVector{T}() @test size(v) == (0,) @test length(v) == 0 @test isempty(v) @@ -13,10 +26,14 @@ const MOIU = MOI.Utilities c = collect(v) @test c isa Vector{T} @test isempty(c) + return end -@testset "LazyMap{$T}" for T in [Int, Float64] - v = MOIU.LazyMap{T}(x -> x^2, [2, 3]) +test_EmptyVector_Int() = _test_EmptyVector(Int) +test_EmptyVector_Float64() = _test_EmptyVector(Float64) + +function _test_LazyMap(T) + v = MOI.Utilities.LazyMap{T}(x -> x^2, [2, 3]) @test size(v) == (2,) @test length(v) == 2 @test !isempty(v) @@ -24,4 +41,12 @@ end c = collect(v) @test c isa Vector{T} @test c == [4, 9] + return end + +test_LazyMap_Int() = _test_LazyMap(Int) +test_LazyMap_Float64() = _test_LazyMap(Float64) + +end # module + +TestLazyIterators.runtests()