Skip to content

Avoid fast-path IO writes when IO has ext enc #759

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 10, 2025
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
34 changes: 33 additions & 1 deletion java/src/json/ext/Generator.java
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
*/
package json.ext;

import org.jcodings.Encoding;
import org.jcodings.specific.UTF8Encoding;
import org.jruby.Ruby;
import org.jruby.RubyArray;
Expand All @@ -15,6 +16,7 @@
import org.jruby.RubyFixnum;
import org.jruby.RubyFloat;
import org.jruby.RubyHash;
import org.jruby.RubyIO;
import org.jruby.RubyString;
import org.jruby.RubySymbol;
import org.jruby.runtime.Helpers;
Expand Down Expand Up @@ -81,11 +83,41 @@ static <T extends IRubyObject> RubyString generateJson(ThreadContext context, T
return handler.generateNew(context, session, object);
}

BufferedOutputStream buffer = new BufferedOutputStream(new IOOutputStream(io), IO_BUFFER_SIZE);
BufferedOutputStream buffer =
new BufferedOutputStream(
new PatchedIOOutputStream(io, UTF8Encoding.INSTANCE),
IO_BUFFER_SIZE);
handler.generateToBuffer(context, session, object, buffer);
return io;
}

/**
* A version of IOOutputStream hacked to avoid fast-path RubyIO calls when the target IO has an external encoding.
*
* All calls to the underlying IO will be done dynamically and all incoming bytes wrapped in RubyString instances.
* This avoids bugs in the fast-path logic in JRuby 9.4.12.0 and earlier that fails to properly handle writing bytes
* when the source and target destination are the same.
*
* See https://github.com/jruby/jruby/issues/8682
*/
private static class PatchedIOOutputStream extends IOOutputStream {
public PatchedIOOutputStream(IRubyObject io, Encoding encoding) {
super(io, encoding);
}

@Override
public RubyIO getRealIO(IRubyObject io) {
RubyIO realIO = super.getRealIO(io);

// if the real IO has an external encoding, don't use fast path
if (realIO == null || realIO.getEnc() != null) {
return null;
}

return realIO;
}
}

/**
* Returns the best serialization handler for the given object.
*/
Expand Down