From 9b8f48757a7ee0478ec02828573294995991feca Mon Sep 17 00:00:00 2001 From: Wynand Badenhorst Date: Fri, 19 Nov 2021 16:20:47 -0600 Subject: [PATCH] Add Singleton writing --- src/Writer.jl | 16 ++++++++++++---- test/serializer.jl | 6 +++++- 2 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/Writer.jl b/src/Writer.jl index 6ebea04..fa043f6 100644 --- a/src/Writer.jl +++ b/src/Writer.jl @@ -22,6 +22,12 @@ end CompositeTypeWrapper(x, syms) = CompositeTypeWrapper(x, collect(syms)) CompositeTypeWrapper(x) = CompositeTypeWrapper(x, propertynames(x)) +struct SingletonTypeWrapper{T} + wrapped::T +end + +SingletonTypeWrapper(::T) where {T} = SingletonTypeWrapper{T}() + """ lower(x) @@ -40,11 +46,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 @@ -287,6 +293,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 diff --git a/test/serializer.jl b/test/serializer.jl index 87927fe..fa7399a 100644 --- a/test/serializer.jl +++ b/test/serializer.jl @@ -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()