From c40a330ac121abbf211a955fb86701793fef1611 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Thu, 24 Oct 2024 15:45:41 +0900 Subject: [PATCH 1/2] Use `String#b` --- lib/json/pure/generator.rb | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/json/pure/generator.rb b/lib/json/pure/generator.rb index 517d4e27..1fc9ba09 100644 --- a/lib/json/pure/generator.rb +++ b/lib/json/pure/generator.rb @@ -50,8 +50,7 @@ module JSON # Convert a UTF8 encoded Ruby string _string_ to a JSON string, encoded with # UTF16 big endian characters as \u????, and return it. def utf8_to_json(string, script_safe = false) # :nodoc: - string = string.dup - string.force_encoding(::Encoding::ASCII_8BIT) + string = string.b if script_safe string.gsub!(SCRIPT_SAFE_ESCAPE_PATTERN) { SCRIPT_SAFE_MAP[$&] || $& } else @@ -62,8 +61,7 @@ def utf8_to_json(string, script_safe = false) # :nodoc: end def utf8_to_json_ascii(string, script_safe = false) # :nodoc: - string = string.dup - string.force_encoding(::Encoding::ASCII_8BIT) + string = string.b map = script_safe ? SCRIPT_SAFE_MAP : MAP string.gsub!(/[\/"\\\x0-\x1f]/n) { map[$&] || $& } string.gsub!(/( From 7efa2c3a8be170aadec49f0deefd25502d7f38a2 Mon Sep 17 00:00:00 2001 From: Nobuyoshi Nakada Date: Thu, 24 Oct 2024 15:46:26 +0900 Subject: [PATCH 2/2] Use `String#+` It is available since ruby 2.3. --- lib/json/pure/generator.rb | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/json/pure/generator.rb b/lib/json/pure/generator.rb index 1fc9ba09..c2268cc3 100644 --- a/lib/json/pure/generator.rb +++ b/lib/json/pure/generator.rb @@ -407,16 +407,14 @@ def json_shift(state) def json_transform(state) delim = ",#{state.object_nl}" - result = "{#{state.object_nl}" - result = result.dup if result.frozen? # RUBY_VERSION < 3.0 + result = +"{#{state.object_nl}" depth = state.depth += 1 first = true indent = !state.object_nl.empty? each { |key, value| result << delim unless first result << state.indent * depth if indent - result = "#{result}#{key.to_s.to_json(state)}#{state.space_before}:#{state.space}" - result = result.dup if result.frozen? # RUBY_VERSION < 3.0 + result = +"#{result}#{key.to_s.to_json(state)}#{state.space_before}:#{state.space}" if state.strict? && !(false == value || true == value || nil == value || String === value || Array === value || Hash === value || Integer === value || Float === value) raise GeneratorError, "#{value.class} not allowed in JSON" elsif value.respond_to?(:to_json)