Skip to content

Commit

Permalink
Raise the correct exception in fast_serialize_string
Browse files Browse the repository at this point in the history
* Related to #344
  • Loading branch information
eregon committed Oct 21, 2024
1 parent f887daa commit 9c4d459
Show file tree
Hide file tree
Showing 2 changed files with 16 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/json/pure/generator.rb
Original file line number Diff line number Diff line change
Expand Up @@ -339,6 +339,7 @@ def generate(obj)
private def fast_serialize_string(string, buf) # :nodoc:
buf << '"'
string = string.encode(::Encoding::UTF_8) unless string.encoding == ::Encoding::UTF_8
raise GeneratorError, "source sequence is illegal/malformed utf-8" unless string.valid_encoding?

if /["\\\x0-\x1f]/n.match?(string)
buf << string.gsub(/["\\\x0-\x1f]/n, MAP)
Expand Down
15 changes: 15 additions & 0 deletions test/json/json_generator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,21 @@ def test_invalid_encoding_string
"\x82\xAC\xEF".to_json
end
assert_includes error.message, "source sequence is illegal/malformed utf-8"

error = assert_raise(JSON::GeneratorError) do
JSON.dump("\x82\xAC\xEF")
end
assert_includes error.message, "source sequence is illegal/malformed utf-8"

# These pass on the pure-Ruby generator but not with the native extension
# https://github.com/ruby/json/issues/634
# assert_raise(Encoding::UndefinedConversionError) do
# "\x82\xAC\xEF".b.to_json
# end
#
# assert_raise(Encoding::UndefinedConversionError) do
# JSON.dump("\x82\xAC\xEF".b)
# end
end

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

0 comments on commit 9c4d459

Please sign in to comment.