Skip to content

Commit

Permalink
Add Singleton writing
Browse files Browse the repository at this point in the history
  • Loading branch information
Wynand committed Nov 19, 2021
1 parent f93688a commit 00e171f
Show file tree
Hide file tree
Showing 2 changed files with 15 additions and 5 deletions.
14 changes: 10 additions & 4 deletions src/Writer.jl
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,10 @@ end
CompositeTypeWrapper(x, syms) = CompositeTypeWrapper(x, collect(syms))
CompositeTypeWrapper(x) = CompositeTypeWrapper(x, propertynames(x))

struct SingletonTypeWrapper{T}
wrapped::T
end

"""
lower(x)
Expand All @@ -40,11 +44,11 @@ Note that the return value need not be *recursively* lowered—this function may
for instance return an `AbstractArray{Any, 1}` whose elements are not JSON
primitives.
"""
function lower(a)
if nfields(a) > 0
CompositeTypeWrapper(a)
function lower(a::T) where {T}
if Base.issingletontype(T)
SingletonTypeWrapper(a)
else
error("Cannot serialize type $(typeof(a))")
CompositeTypeWrapper(a)
end
end

Expand Down Expand Up @@ -287,6 +291,8 @@ function show_json(io::SC, s::CS, x::CompositeTypeWrapper)
end_object(io)
end

show_json(io::SC, ::CS, x::SingletonTypeWrapper) = show_string(io, x.wrapped)

function show_json(io::SC, s::CS, x::Union{AbstractVector, Tuple})
begin_array(io)
for elt in x
Expand Down
6 changes: 5 additions & 1 deletion test/serializer.jl
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,11 @@ end

# test serializing a type without any fields
struct SingletonType end
@test_throws ErrorException json(SingletonType())
@test json(SingletonType()) == "\"Main.TestSerializer.SingletonType()\""

struct ParamSingletonType{T} end
@test json(ParamSingletonType{Float64}()) == "\"Main.TestSerializer.ParamSingletonType{Float64}()\""


# test printing to stdout
let filename = tempname()
Expand Down

0 comments on commit 00e171f

Please sign in to comment.