Skip to content

Commit 168b757

Browse files
author
Evgeny Tankhilevich
committed
Allow bypassing the json spec by serializing infinite floats
1 parent 38a6efd commit 168b757

File tree

4 files changed

+9
-6
lines changed

4 files changed

+9
-6
lines changed

.gitignore

+1
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
.DS_Store
2+
Manifest.toml
23
docs/build/
34
docs/site/
45
*.jl.cov

Project.toml

-2
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,6 @@ authors = ["Jacob Quinn <[email protected]>"]
44
version = "1.0.1"
55

66
[deps]
7-
Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
87
Parsers = "69de0a69-1ddd-5017-9359-2bf0b02dc9f0"
98
StructTypes = "856f2bd8-1eba-4b0a-8007-ebc267875bd4"
109
Mmap = "a63ad114-7e13-5084-954f-fe012c677804"
@@ -21,4 +20,3 @@ Test = "8dfed614-e22c-5e08-85e1-65c5234f0b40"
2120

2221
[targets]
2322
test = ["Test"]
24-

src/write.jl

+4-4
Original file line numberDiff line numberDiff line change
@@ -171,8 +171,8 @@ function write(::NumberType, buf, pos, len, y::Integer; kw...)
171171
end
172172

173173
write(::NumberType, buf, pos, len, x::T; kw...) where {T} = write(NumberType(), buf, pos, len, StructTypes.numbertype(T)(x); kw...)
174-
function write(::NumberType, buf, pos, len, x::AbstractFloat; kw...)
175-
isfinite(x) || error("$x not allowed to be written in JSON spec")
174+
function write(::NumberType, buf, pos, len, x::AbstractFloat; allow_inf::Bool=false, kw...)
175+
isfinite(x) || allow_inf || error("$x not allowed to be written in JSON spec")
176176
bytes = codeunits(Base.string(x))
177177
sz = sizeof(bytes)
178178
@check sz
@@ -183,8 +183,8 @@ function write(::NumberType, buf, pos, len, x::AbstractFloat; kw...)
183183
return buf, pos, len
184184
end
185185

186-
@inline function write(::NumberType, buf, pos, len, x::T; kw...) where {T <: Base.IEEEFloat}
187-
isfinite(x) || error("$x not allowed to be written in JSON spec")
186+
@inline function write(::NumberType, buf, pos, len, x::T; allow_inf::Bool=false, kw...) where {T <: Base.IEEEFloat}
187+
isfinite(x) || allow_inf || error("$x not allowed to be written in JSON spec")
188188
@check Parsers.neededdigits(T)
189189
pos = Parsers.writeshortest(buf, pos, x)
190190
return buf, pos, len

test/json.jl

+4
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,10 @@ end
3232
@testset "Floats" begin
3333
@test_throws ErrorException JSON3.write([NaN])
3434
@test_throws ErrorException JSON3.write([Inf])
35+
@test JSON3.write([NaN], allow_inf=true) == "[NaN]"
36+
@test JSON3.write([Inf], allow_inf=true) == "[Inf]"
37+
@test JSON3.read("[Inf]", Vector{Float64}) == [Inf]
38+
@test JSON3.read("[nan]", Vector{Float64}) == [NaN]
3539
end
3640

3741
@testset "Char" begin

0 commit comments

Comments
 (0)