Skip to content

Commit 8933f2e

Browse files
authored
Supporting reading dictionaries of specific types (#23)
1 parent b598f68 commit 8933f2e

3 files changed

Lines changed: 48 additions & 4 deletions

File tree

src/reader.jl

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -383,16 +383,16 @@ function read_field_(reader::BSONReader, ::Type{BSONCodeWithScope})
383383
end
384384
end
385385

386-
function read_field_(reader::AbstractBSONReader, ::Type{T}) where T <: AbstractDict{String, Any}
386+
function read_field_(reader::AbstractBSONReader, ::Type{T}) where {X, T <: AbstractDict{String, X}}
387387
foldxl(reader; init = T()) do state, x
388-
state[String(x.first)] = x.second[Any]
388+
state[String(x.first)] = x.second[X]
389389
state
390390
end
391391
end
392392

393-
function read_field_(reader::AbstractBSONReader, ::Type{T}) where T <: AbstractDict{Symbol, Any}
393+
function read_field_(reader::AbstractBSONReader, ::Type{T}) where {X, T <: AbstractDict{Symbol, X}}
394394
foldxl(reader; init = T()) do state, x
395-
state[Symbol(x.first)] = x.second[Any]
395+
state[Symbol(x.first)] = x.second[X]
396396
state
397397
end
398398
end

test/dict_tests.jl

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,43 @@
1+
@testset "dict" begin
2+
3+
@testset "string -> any" begin
4+
buf = UInt8[]
5+
writer = BSONWriter(buf)
6+
x = Dict{String, Any}("a" => 1, "b" => "b")
7+
writer[] = x
8+
close(writer)
9+
reader = BSONReader(buf)
10+
@test reader[Dict{String, Any}] == x
11+
end
12+
13+
@testset "string -> int" begin
14+
buf = UInt8[]
15+
writer = BSONWriter(buf)
16+
x = Dict{String, Int32}("a" => 1, "b" => 2)
17+
writer[] = x
18+
close(writer)
19+
reader = BSONReader(buf)
20+
@test reader[Dict{String, Int32}] == x
21+
end
22+
23+
@testset "symbol -> any" begin
24+
buf = UInt8[]
25+
writer = BSONWriter(buf)
26+
x = Dict{Symbol, Any}(:a => 1, :b => "b")
27+
writer[] = x
28+
close(writer)
29+
reader = BSONReader(buf)
30+
@test reader[Dict{Symbol, Any}] == x
31+
end
32+
33+
@testset "symbol -> int" begin
34+
buf = UInt8[]
35+
writer = BSONWriter(buf)
36+
x = Dict{Symbol, Int32}(:a => 1, :b => 2)
37+
writer[] = x
38+
close(writer)
39+
reader = BSONReader(buf)
40+
@test reader[Dict{Symbol, Int32}] == x
41+
end
42+
43+
end

test/runtests.jl

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,6 +17,7 @@ struct EmptyStruct end
1717
include("indexed_reader_tests.jl")
1818
include("write_buffer_tests.jl")
1919
include("writer_tests.jl")
20+
include("dict_tests.jl")
2021
include("struct_tests.jl")
2122
include("corpus_tests.jl")
2223
include("object_id_tests.jl")

0 commit comments

Comments
 (0)