From 57489fb71a78b7d009bc88a2f95675fb0076515f Mon Sep 17 00:00:00 2001 From: Dimitris Mandalidis Date: Fri, 4 Sep 2020 11:14:34 +0300 Subject: [PATCH] Fix misaligned buffer allocation method #1367 --- src/main/java/io/lettuce/core/codec/StringCodec.java | 12 ++++++++++-- .../io/lettuce/core/codec/StringCodecUnitTests.java | 3 ++- 2 files changed, 12 insertions(+), 3 deletions(-) diff --git a/src/main/java/io/lettuce/core/codec/StringCodec.java b/src/main/java/io/lettuce/core/codec/StringCodec.java index 61946e281f..52fe139500 100644 --- a/src/main/java/io/lettuce/core/codec/StringCodec.java +++ b/src/main/java/io/lettuce/core/codec/StringCodec.java @@ -192,9 +192,17 @@ public void encode(String str, ByteBuf target) { int sizeOf(String value, boolean estimate) { if (estimate) { - return (int) (averageBytesPerChar * value.length()); + return (int) averageBytesPerChar * value.length(); } - return (int) (maxBytesPerChar * value.length()); + if (utf8) { + return ByteBufUtil.utf8MaxBytes(value); + } + + if (ascii) { + return value.length(); + } + + return (int) maxBytesPerChar * value.length(); } } diff --git a/src/test/java/io/lettuce/core/codec/StringCodecUnitTests.java b/src/test/java/io/lettuce/core/codec/StringCodecUnitTests.java index 62c73bf6ed..34ef77a4f3 100644 --- a/src/test/java/io/lettuce/core/codec/StringCodecUnitTests.java +++ b/src/test/java/io/lettuce/core/codec/StringCodecUnitTests.java @@ -23,6 +23,7 @@ import org.junit.jupiter.api.Test; import io.netty.buffer.ByteBuf; +import io.netty.buffer.ByteBufUtil; import io.netty.buffer.Unpooled; /** @@ -124,7 +125,7 @@ void estimateSize() { void sizeOf() { assertThat(new StringCodec(StandardCharsets.UTF_8).sizeOf(teststring, false)) - .isEqualTo(teststring.length() * 3); + .isEqualTo(ByteBufUtil.utf8MaxBytes(teststring)); assertThat(new StringCodec(StandardCharsets.US_ASCII).sizeOf(teststring, false)) .isEqualTo(teststring.length()); assertThat(new StringCodec(StandardCharsets.ISO_8859_1).sizeOf(teststring, false))