From 574e8102b640cbf2e8aa68d7d81fb6cd2e94732f Mon Sep 17 00:00:00 2001 From: Andrey Mizurov Date: Tue, 31 Mar 2020 17:02:06 +0300 Subject: [PATCH] =?UTF-8?q?Fix=20allocate=20additional=20buffer=20for=20en?= =?UTF-8?q?coding=20stompFrame=20without=20readab=E2=80=A6=20(#10150)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Motivation: Not always STOMP frames contain any payload some times it just headers. So we wan't allocate additional buffer with NULL content for this situation. Modification: Modify StompSubframeEncoder to check if content is readable or not. If content is not readable just add NULL byte to encoded header buffer. Result: Less allocations --- .../handler/codec/stomp/StompSubframeEncoder.java | 11 ++++++++--- .../codec/stomp/StompSubframeEncoderTest.java | 14 ++++++++++++++ 2 files changed, 22 insertions(+), 3 deletions(-) diff --git a/codec-stomp/src/main/java/io/netty/handler/codec/stomp/StompSubframeEncoder.java b/codec-stomp/src/main/java/io/netty/handler/codec/stomp/StompSubframeEncoder.java index fd99f7b1cb..7b8dc4dcdf 100644 --- a/codec-stomp/src/main/java/io/netty/handler/codec/stomp/StompSubframeEncoder.java +++ b/codec-stomp/src/main/java/io/netty/handler/codec/stomp/StompSubframeEncoder.java @@ -34,9 +34,14 @@ public class StompSubframeEncoder extends MessageToMessageEncoder if (msg instanceof StompFrame) { StompFrame frame = (StompFrame) msg; ByteBuf frameBuf = encodeFrame(frame, ctx); - out.add(frameBuf); - ByteBuf contentBuf = encodeContent(frame, ctx); - out.add(contentBuf); + if (frame.content().isReadable()) { + out.add(frameBuf); + ByteBuf contentBuf = encodeContent(frame, ctx); + out.add(contentBuf); + } else { + frameBuf.writeByte(StompConstants.NUL); + out.add(frameBuf); + } } else if (msg instanceof StompHeadersSubframe) { StompHeadersSubframe frame = (StompHeadersSubframe) msg; ByteBuf buf = encodeFrame(frame, ctx); diff --git a/codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompSubframeEncoderTest.java b/codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompSubframeEncoderTest.java index 17d4ee684a..c792f73b34 100644 --- a/codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompSubframeEncoderTest.java +++ b/codec-stomp/src/test/java/io/netty/handler/codec/stomp/StompSubframeEncoderTest.java @@ -83,4 +83,18 @@ public class StompSubframeEncoderTest { assertTrue(fullFrame.release()); } + @Test + public void testOneBufferForStompFrameWithEmptyContent() { + StompFrame connectedFrame = new DefaultStompFrame(StompCommand.CONNECTED); + connectedFrame.headers().set(StompHeaders.VERSION, "1.2"); + + assertTrue(channel.writeOutbound(connectedFrame)); + + ByteBuf stompBuffer = channel.readOutbound(); + + assertNotNull(stompBuffer); + assertNull(channel.readOutbound()); + assertEquals("CONNECTED\nversion:1.2\n\n\0", stompBuffer.toString(CharsetUtil.UTF_8)); + assertTrue(stompBuffer.release()); + } }