Skip to content

Commit 9563758

Browse files
authored
Merge pull request #5 from casperisfine/handle-nan-and-inf
Raise an error if trying to serialize NaN or Infinity
2 parents ce9bff6 + e43c433 commit 9563758

File tree

3 files changed

+36
-1
lines changed

3 files changed

+36
-1
lines changed

ext/rapidjson/encoder.hh

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -77,7 +77,13 @@ class RubyObjectEncoder {
7777

7878
void encode_float(VALUE v) {
7979
double f = rb_float_value(v);
80-
writer.Double(f);
80+
if (isinf(f)) {
81+
rb_raise(rb_eEncodeError, "Float::INFINITY is not allowed in JSON");
82+
} else if (isnan(f)) {
83+
rb_raise(rb_eEncodeError, "Float::NAN is not allowed in JSON");
84+
} else {
85+
writer.Double(f);
86+
}
8187
}
8288

8389
void encode_string(VALUE v) {

test/test_encoder.rb

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,4 +119,23 @@ def test_encode_false
119119
def test_encode_nil
120120
assert_equal "null", encode(nil)
121121
end
122+
123+
def test_encode_NaN
124+
error = assert_raises RapidJSON::EncodeError do
125+
encode(Float::NAN)
126+
end
127+
assert_match "Float::NAN is not allowed in JSON", error.message
128+
end
129+
130+
def test_encode_Infinity
131+
error = assert_raises RapidJSON::EncodeError do
132+
encode(Float::INFINITY)
133+
end
134+
assert_match "Float::INFINITY is not allowed in JSON", error.message
135+
136+
error = assert_raises RapidJSON::EncodeError do
137+
encode(-Float::INFINITY)
138+
end
139+
assert_match "Float::INFINITY is not allowed in JSON", error.message
140+
end
122141
end

test/test_parser.rb

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -78,4 +78,14 @@ def test_parse_too_deep
7878
assert parse("["*(max+1) + "]"*(max+1))
7979
end
8080
end
81+
82+
def test_parse_NaN_and_Infinity
83+
assert_raises RapidJSON::ParseError do
84+
parse("NaN")
85+
end
86+
87+
assert_raises RapidJSON::ParseError do
88+
parse("Infinity")
89+
end
90+
end
8191
end

0 commit comments

Comments
 (0)