Skip to content

Commit

Permalink
Save intermediate text encoded buffer copies
Browse files Browse the repository at this point in the history
  • Loading branch information
franz1981 committed Oct 10, 2024
1 parent 3ca72f8 commit 9a0f516
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 1 deletion.
15 changes: 14 additions & 1 deletion src/main/java/io/vertx/core/http/impl/WebSocketImplBase.java
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,7 @@
import javax.net.ssl.SSLPeerUnverifiedException;
import javax.net.ssl.SSLSession;
import javax.security.cert.X509Certificate;
import java.nio.charset.StandardCharsets;
import java.security.cert.Certificate;
import java.util.List;
import java.util.UUID;
Expand Down Expand Up @@ -308,7 +309,19 @@ public final S writeBinaryMessage(Buffer data, Handler<AsyncResult<Void>> handle

@Override
public Future<Void> writeTextMessage(String text) {
return writePartialMessage(WebSocketFrameType.TEXT, Buffer.buffer(text), 0);
byte[] utf8Bytes = text.getBytes(StandardCharsets.UTF_8);
boolean isFinal = utf8Bytes.length <= maxWebSocketFrameSize;
if (isFinal) {
// ALTERNATIVE A: we create a copy wasting the previous one, but we don't introduce a new buffer type
// ByteBuf copiedBuffer = VertxByteBufAllocator.DEFAULT.heapBuffer(utf8Bytes.length);
// copiedBuffer.writeBytes(utf8Bytes);
// don't make the frame to be wrapped in an unreleasable buffer, again
// return writeFrame(new WebSocketFrameImpl(WebSocketFrameType.TEXT, copiedBuffer, true, false));
// ALTERNATIVE B: we reuse the byte[] wrapping it into a new buffer,
// but we introduce a new buffer type which requires to be released i.e. reference counting isn't free!
return writeFrame(new WebSocketFrameImpl(WebSocketFrameType.TEXT, utf8Bytes, true));
}
return writePartialMessage(WebSocketFrameType.TEXT, Buffer.buffer(utf8Bytes), 0);
}

@Override
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -79,6 +79,15 @@ public WebSocketFrameImpl(String textData) {
this(textData, true);
}

/**
* Creates a new raw frame from with the specified encoded content.
*/
public WebSocketFrameImpl(WebSocketFrameType type, byte[] utf8TextData, boolean isFinalFrame) {
this.type = type;
this.isFinalFrame = isFinalFrame;
this.binaryData = Unpooled.wrappedBuffer(utf8TextData);
}

/**
* Creates a new text frame from with the specified string.
*/
Expand Down

0 comments on commit 9a0f516

Please sign in to comment.