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

DictoVec: cleanup and add tests #63

Merged
merged 2 commits into from
Jan 1, 2020
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
131 changes: 73 additions & 58 deletions src/DictoVec.jl
Original file line number Diff line number Diff line change
@@ -1,53 +1,51 @@
function name2index(names::Vector{RString})
n2i = Dict{RString,Int64}()
i2n = Dict{Int64,RString}()
@inbounds for (i,k) in enumerate(names)
if k != ""
n2i[k] = i
i2n[i] = k
end
end
n2i, i2n
end

"""
Container that mimics R vector behaviour.
Elements could be accessed either by indices as a normal vector,
or (optionally) by string keys as a dictionary.
"""
struct DictoVec{T}
data::T
data::Vector{T}
name2index::Dict{RString, Int}
index2name::Dict{Int, RString}
index2name::Vector{Union{RString, Nothing}}

function (::Type{DictoVec})(data::T, names::Vector{RString} = Vector{RString}()) where T
n2i, i2n = name2index(names)
function DictoVec(data::AbstractVector{T}, names::AbstractVector{<:AbstractString} = Vector{RString}()) where T
if !isempty(names) && length(data) != length(names)
throw(DimensionMismatch("Lengths of data ($(length(data))) and element names ($(length(names))) differ"))
end
n2i = Dict{RString, Int}()
i2n = fill!(similar(data, Union{RString, Nothing}), nothing)
@inbounds for (i, k) in enumerate(names)
if k != "" && k !== nothing
n2i[k] = i
i2n[i] = k
else
i2n[i] = nothing
end
end
new{T}(data, n2i, i2n)
end
end

Base.eltype(::Type{DictoVec{T}}) where T = T
Base.eltype(dict::DictoVec) = eltype(typeof(dict))
Base.length(dict::DictoVec) = length(dict.data)
Base.isempty(dict::DictoVec) = isempty(dict.data)

# key-based indexing
Base.haskey(dict::DictoVec, key) = haskey(dict.name2index, key)

function Base.setindex!(dict::DictoVec, value, key)
ix = get(dict.name2index, key, 0)
if ix > 0
setindex!(dict.data, value, ix)
else
dict.name2index[key] = length(dict.data)+1
dict.index2name[ix] = key
push!(dict.data, value)
if ix > 0 # existing key
setindex!(dict.data, value, ix)
else # new key
_key = convert(keytype(dict.name2index), key) # throws if key is not compatible
push!(dict.data, value) # first try to add value (throws if it's not compatible)
push!(dict.index2name, _key)
dict.name2index[_key] = length(dict.data)
end
end

function Base.setindex!(dict::DictoVec, value, index::Int64)
setindex!(dict.data, value, index)
end

Base.getindex(dict::DictoVec, index::Int) = getindex(dict.data, index)

function Base.getindex(dict::DictoVec, key)
ix = get(dict.name2index, key, 0)
if ix > 0
Expand All @@ -57,56 +55,73 @@ function Base.getindex(dict::DictoVec, key)
end
end

Base.get(dict::DictoVec, index::Int, default) = get(dict.data, index, default)
# integer-based indexing (overrides key-based indexing)
Base.setindex!(dict::DictoVec, value, index::Integer) =
setindex!(dict.data, value, index)
Base.setindex!(dict::DictoVec, values, indices::AbstractVector{<:Integer}) =
setindex!(dict.data, values, indices)

Base.getindex(dict::DictoVec, index::Integer) = getindex(dict.data, index)
Base.getindex(dict::DictoVec, indices::AbstractVector{<:Integer}) = getindex(dict.data, indices)

Base.get(dict::DictoVec, index::Integer, default) = get(dict.data, index, default)
Base.get(f::Function, dict::DictoVec, index::Integer) = index ∈ eachindex(dict.data) ? dict.data[index] : f()

function Base.get(dict::DictoVec, key, default)
ix = get(dict.name2index, key, 0)
return ix > 0 ? dict.data[ix] : default
end

Base.get(f::Function, dict::DictoVec, index::Int) = get(f, dict.data, index)

function Base.get(f::Function, dict::DictoVec, key)
ix = get(dict.name2index, key, 0)
return ix > 0 ? dict.data[ix] : f()
return get(f, dict, ix)
end

function Base.keys(dict::DictoVec)
return keys(dict.name2index)
function Base.delete!(dict::DictoVec, key)
ix = pop!(dict.name2index, key, 0)
if ix > 0
deleteat!(dict.data, ix)
deleteat!(dict.index2name, ix)
if ix <= length(dict)
# update indices
for (k, oldix) in pairs(dict.name2index)
if oldix > ix
dict.name2index[k] = oldix - 1
end
end
end
end
return dict
end

function Base.values(dict::DictoVec)
return dict.data
end
Base.keys(dict::DictoVec) = keys(dict.name2index)

Base.values(dict::DictoVec) = dict.data

function Base.show(io::IO, dict::DictoVec)
if isempty(dict.name2index)
# no keys
show(dict.data)
else
first = true
print(io, "DictoVec(")
n = 0
for i in eachindex(dict.data)
first || print(io, ',')
first = false
k = get(dict.index2name, i, "")
if k != ""
show(io, k)
print(io, "=>")
end
show(io, dict.data[i])
n += 1
# limit && n >= 10 && (print(io, "…"); break)
first = true
print(io, typeof(dict), "(")
n = 0
for i in eachindex(dict.data)
first || print(io, ',')
first = false
k = dict.index2name[i]
if k !== nothing
show(io, k)
print(io, "=>")
end
print(io, ")")
show(io, dict.data[i])
n += 1
# limit && n >= 10 && (print(io, "…"); break)
end
print(io, ")")
end

function Base.convert(::Type{Dict{RString,Any}}, dv::DictoVec)
res = Dict{RString,Any}()
for (k,v) in dv.name2index
# elements that are only referenced by the index would not be in the result
for (k, v) in dv.name2index
res[k] = dv.data[v]
end
res
return res
end
147 changes: 147 additions & 0 deletions test/DictoVec.jl
Original file line number Diff line number Diff line change
@@ -0,0 +1,147 @@
module TestDictoVec
using Test
using RData

function show2string(dv::DictoVec)
iob = IOBuffer()
show(iob, dv)
return String(take!(iob))
end

@testset "RData DictoVec type" begin

@testset "Empty DictoVec" begin
@test_throws MethodError DictoVec(Symbol[], [:a])
@test_throws DimensionMismatch DictoVec(Symbol[], ["a"])
dv = DictoVec(Symbol[])

@test typeof(dv) === DictoVec{Symbol}
@test eltype(dv) === Symbol
@test length(dv) == 0
@test isempty(dv)
@test collect(keys(dv)) == RData.RString[]
@test values(dv) == Symbol[]
@test !haskey(dv, "a")
@test !haskey(dv, :a)
@test !haskey(dv, 1)
@test_throws BoundsError dv[1]
@test_throws KeyError dv["a"]
@test_throws KeyError dv[:a]

@test get(dv, 1, :x) == :x
@test get(() -> :y, dv, 1) == :y
@test get(dv, "a", :x) == :x
@test get(() -> :y, dv, "a") == :y
@test length(dv) == 0

@test convert(Dict{RData.RString, Any}, dv) == Dict{RData.RString, Any}()

@test show2string(dv) == "DictoVec{Symbol}()"

# add an element
@test_throws MethodError (dv[1] = "xx") # incompatible value
@test length(dv) == 0
@test_throws BoundsError (dv[1] = :xx) # cannot create new elements by integer index
@test length(dv) == 0
@test_throws MethodError (dv[:a] = "xx") # incompatible key
@test length(dv) == 0
@test_throws MethodError (dv["a"] = "xx") # incompatible value
@test length(dv) == 0
dv["a"] = :xx
@test !isempty(dv)
@test length(dv) == 1
@test haskey(dv, "a")
@test dv["a"] == :xx
@test dv[1] == :xx
@test collect(keys(dv)) == ["a"]
@test values(dv) == [:xx]

@test show2string(dv) == "DictoVec{Symbol}(\"a\"=>:xx)"

# reassign element
dv[1] = :yy
@test length(dv) == 1
@test dv[1] == :yy
@test dv["a"] == :yy

# deleting an element by key
@test delete!(dv, 1) === dv
@test length(dv) == 1
delete!(dv, "b")
@test length(dv) == 1
delete!(dv, "a")
@test length(dv) == 0
@test !haskey(dv, "a")
@test_throws BoundsError dv[1]
end

@testset "Nameless DictoVec" begin
dv = DictoVec([2.0, 5.0, 4.0])
@test typeof(dv) === DictoVec{Float64}
@test eltype(dv) === Float64
@test length(dv) == 3
@test !isempty(dv)
@test !haskey(dv, 1)
@test !haskey(dv, "a")
@test !haskey(dv, :a)
@test show2string(dv) == "DictoVec{Float64}(2.0,5.0,4.0)"
@test collect(keys(dv)) == RData.RString[]
@test values(dv) == [2.0, 5.0, 4.0]

@test_throws BoundsError dv[0]
@test_throws BoundsError dv[4]
@test dv[1] == 2.0
@test dv[[1, 3]] == [2.0, 4.0]
@test_throws KeyError dv["a"]
@test_throws KeyError dv[:a]

# add new element by name
dv["a"] = 3
@test haskey(dv, "a")
@test length(dv) == 4
@test dv["a"] === 3.0
@test dv[4] === 3.0
@test show2string(dv) == "DictoVec{Float64}(2.0,5.0,4.0,\"a\"=>3.0)"

@test delete!(dv, "a") === dv
@test length(dv) == 3
@test !haskey(dv, "a")
end

@testset "DictoVec with names" begin
dv = DictoVec([2.0, 5.0, 4.0], ["a", "b", "c"])
@test typeof(dv) === DictoVec{Float64}
@test eltype(dv) === Float64
@test length(dv) == 3
@test !isempty(dv)
@test !haskey(dv, 1)
@test haskey(dv, "a")
@test !haskey(dv, :a)
@test sort!(collect(keys(dv))) == ["a", "b", "c"]
@test values(dv) == [2.0, 5.0, 4.0]
@test show2string(dv) == "DictoVec{Float64}(\"a\"=>2.0,\"b\"=>5.0,\"c\"=>4.0)"

@test dv[1] === 2.0
@test dv["a"] === 2.0
@test dv[[1, 3]] == [2.0, 4.0]
@test_throws KeyError dv[:a]

# reassign element by name
dv["a"] = 6
@test haskey(dv, "a")
@test length(dv) == 3
@test dv["a"] === 6.0
@test dv[1] === 6.0
@test show2string(dv) == "DictoVec{Float64}(\"a\"=>6.0,\"b\"=>5.0,\"c\"=>4.0)"

# deleting an element from the middle
@test delete!(dv, "b") === dv
@test length(dv) == 2
@test !haskey(dv, "b")
@test dv[2] == 4.0 # indices has updated
@test show2string(dv) == "DictoVec{Float64}(\"a\"=>6.0,\"c\"=>4.0)"
end

end

end # TestDictoVec
1 change: 1 addition & 0 deletions test/runtests.jl
Original file line number Diff line number Diff line change
Expand Up @@ -4,5 +4,6 @@ using Test
include("decompression.jl")
include("errors.jl")
include("basic.jl")
include("DictoVec.jl")
include("RDA.jl")
include("RDS.jl")