Skip to content

Commit 3b0bfe7

Browse files
eregonbyroot
authored andcommitted
Raise the correct exception in fast_serialize_string
* Related to #344
1 parent ac68b8c commit 3b0bfe7

File tree

2 files changed

+18
-0
lines changed

2 files changed

+18
-0
lines changed

lib/json/pure/generator.rb

+1
Original file line numberDiff line numberDiff line change
@@ -339,6 +339,7 @@ def generate(obj)
339339
private def fast_serialize_string(string, buf) # :nodoc:
340340
buf << '"'
341341
string = string.encode(::Encoding::UTF_8) unless string.encoding == ::Encoding::UTF_8
342+
raise GeneratorError, "source sequence is illegal/malformed utf-8" unless string.valid_encoding?
342343

343344
if /["\\\x0-\x1f]/n.match?(string)
344345
buf << string.gsub(/["\\\x0-\x1f]/n, MAP)

test/json/json_generator_test.rb

+17
Original file line numberDiff line numberDiff line change
@@ -443,6 +443,23 @@ def test_invalid_encoding_string
443443
"\x82\xAC\xEF".to_json
444444
end
445445
assert_includes error.message, "source sequence is illegal/malformed utf-8"
446+
447+
error = assert_raise(JSON::GeneratorError) do
448+
JSON.dump("\x82\xAC\xEF")
449+
end
450+
assert_includes error.message, "source sequence is illegal/malformed utf-8"
451+
452+
# These pass on the pure-Ruby generator but not with the native extension
453+
# https://github.com/ruby/json/issues/634
454+
if defined?(JSON::Pure)
455+
assert_raise(Encoding::UndefinedConversionError) do
456+
"\x82\xAC\xEF".b.to_json
457+
end
458+
459+
assert_raise(Encoding::UndefinedConversionError) do
460+
JSON.dump("\x82\xAC\xEF".b)
461+
end
462+
end
446463
end
447464

448465
if defined?(JSON::Ext::Generator) and RUBY_PLATFORM != "java"

0 commit comments

Comments
 (0)