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 authored and byroot committed Oct 22, 2024
1 parent ac68b8c commit 3b0bfe7
Show file tree
Hide file tree
Showing 2 changed files with 18 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
17 changes: 17 additions & 0 deletions test/json/json_generator_test.rb
Original file line number Diff line number Diff line change
Expand Up @@ -443,6 +443,23 @@ 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
if defined?(JSON::Pure)
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
end

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

0 comments on commit 3b0bfe7

Please sign in to comment.