Skip to content

Commit 9b8f487

Browse files
committed
Add Singleton writing
1 parent f93688a commit 9b8f487

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

src/Writer.jl

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -22,6 +22,12 @@ end
2222
CompositeTypeWrapper(x, syms) = CompositeTypeWrapper(x, collect(syms))
2323
CompositeTypeWrapper(x) = CompositeTypeWrapper(x, propertynames(x))
2424

25+
struct SingletonTypeWrapper{T}
26+
wrapped::T
27+
end
28+
29+
SingletonTypeWrapper(::T) where {T} = SingletonTypeWrapper{T}()
30+
2531
"""
2632
lower(x)
2733
@@ -40,11 +46,11 @@ Note that the return value need not be *recursively* lowered—this function may
4046
for instance return an `AbstractArray{Any, 1}` whose elements are not JSON
4147
primitives.
4248
"""
43-
function lower(a)
44-
if nfields(a) > 0
45-
CompositeTypeWrapper(a)
49+
function lower(a::T) where {T}
50+
if Base.issingletontype(T)
51+
SingletonTypeWrapper(a)
4652
else
47-
error("Cannot serialize type $(typeof(a))")
53+
CompositeTypeWrapper(a)
4854
end
4955
end
5056

@@ -287,6 +293,8 @@ function show_json(io::SC, s::CS, x::CompositeTypeWrapper)
287293
end_object(io)
288294
end
289295

296+
show_json(io::SC, ::CS, x::SingletonTypeWrapper) = show_string(io, x.wrapped)
297+
290298
function show_json(io::SC, s::CS, x::Union{AbstractVector, Tuple})
291299
begin_array(io)
292300
for elt in x

test/serializer.jl

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -72,7 +72,11 @@ end
7272

7373
# test serializing a type without any fields
7474
struct SingletonType end
75-
@test_throws ErrorException json(SingletonType())
75+
@test json(SingletonType()) == "\"Main.TestSerializer.SingletonType()\""
76+
77+
struct ParamSingletonType{T} end
78+
@test json(ParamSingletonType{Float64}()) == "\"Main.TestSerializer.ParamSingletonType{Float64}()\""
79+
7680

7781
# test printing to stdout
7882
let filename = tempname()

0 commit comments

Comments
 (0)