Don't copy full transformed buf during every transform

The resulting modified buf is the exact same as before
This commit is contained in:
Nassim Jahnke 2024-11-04 22:09:53 +01:00
parent f0eab71644
commit 76db43cab3
No known key found for this signature in database
GPG Key ID: EF6771C01F6EF02F
2 changed files with 25 additions and 12 deletions

View File

@ -351,12 +351,25 @@ public class UserConnectionImpl implements UserConnection {
throw cancelSupplier.apply(ex);
}
ByteBuf transformed = wrapper.allocateOutputBuffer();
writeToBuffer(wrapper, buf);
}
private void writeToBuffer(final PacketWrapperImpl wrapper, final ByteBuf buf) {
// Instead of allocating a possible unnecessarily large buffer to write the wrapper contents to,
// only allocate the remaining bytes and write the rest to the original buf's head directly.
final int remainingBytes = buf.readableBytes();
final ByteBuf remainingBuf = buf.alloc().buffer(remainingBytes);
try {
wrapper.writeToBuffer(transformed);
buf.clear().writeBytes(transformed);
// Copy before modifying the buffer
remainingBuf.writeBytes(buf, remainingBytes);
// Reset indexes, write wrapper contents, then the unread bytes
buf.readerIndex(0);
buf.writerIndex(0);
wrapper.writeProcessedValues(buf);
buf.writeBytes(remainingBuf);
} finally {
transformed.release();
remainingBuf.release();
}
}

View File

@ -222,6 +222,13 @@ public class PacketWrapperImpl implements PacketWrapper {
@Override
public void writeToBuffer(ByteBuf buffer) throws InformativeException {
writeProcessedValues(buffer);
if (inputBuffer != null) {
buffer.writeBytes(inputBuffer);
}
}
public void writeProcessedValues(ByteBuf buffer) throws InformativeException {
if (id != -1) {
Types.VAR_INT.writePrimitive(buffer, id);
}
@ -238,7 +245,6 @@ public class PacketWrapperImpl implements PacketWrapper {
throw createInformativeException(e, packetValue.type(), i);
}
}
writeRemaining(buffer);
}
private InformativeException createInformativeException(final Exception cause, final Type<?> type, final int index) {
@ -264,12 +270,6 @@ public class PacketWrapperImpl implements PacketWrapper {
packetValues.clear();
}
private void writeRemaining(ByteBuf output) {
if (inputBuffer != null) {
output.writeBytes(inputBuffer);
}
}
@Override
public void send(Class<? extends Protocol> protocol, boolean skipCurrentPipeline) throws InformativeException {
send0(protocol, skipCurrentPipeline, true);
@ -386,7 +386,7 @@ public class PacketWrapperImpl implements PacketWrapper {
}
}
public ByteBuf allocateOutputBuffer() {
private ByteBuf allocateOutputBuffer() {
if (inputBuffer == null) {
return user().getChannel().alloc().buffer();
}