diff --git a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java index f8d4f921d7..f2ce52256d 100644 --- a/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java +++ b/buffer/src/main/java/io/netty/buffer/ByteBufUtil.java @@ -340,10 +340,19 @@ public final class ByteBufUtil { * is allocated via the {@link ByteBufAllocator}. */ public static ByteBuf encodeString(ByteBufAllocator alloc, CharBuffer src, Charset charset) { + return encodeString0(alloc, false, src, charset); + } + + static ByteBuf encodeString0(ByteBufAllocator alloc, boolean enforceHeap, CharBuffer src, Charset charset) { final CharsetEncoder encoder = CharsetUtil.getEncoder(charset); int length = (int) ((double) src.remaining() * encoder.maxBytesPerChar()); boolean release = true; - final ByteBuf dst = alloc.buffer(length); + final ByteBuf dst; + if (enforceHeap) { + dst = alloc.heapBuffer(length); + } else { + dst = alloc.buffer(length); + } try { final ByteBuffer dstBuf = dst.internalNioBuffer(0, length); final int pos = dstBuf.position(); diff --git a/buffer/src/main/java/io/netty/buffer/Unpooled.java b/buffer/src/main/java/io/netty/buffer/Unpooled.java index f9edbb38d9..ad707079ce 100644 --- a/buffer/src/main/java/io/netty/buffer/Unpooled.java +++ b/buffer/src/main/java/io/netty/buffer/Unpooled.java @@ -412,12 +412,7 @@ public final class Unpooled { public static ByteBuf copiedBuffer(ByteBuf buffer) { int readable = buffer.readableBytes(); if (readable > 0) { - ByteBuf copy; - if (buffer.isDirect()) { - copy = directBuffer(readable); - } else { - copy = buffer(readable); - } + ByteBuf copy = buffer(readable); copy.writeBytes(buffer, buffer.readerIndex(), readable); return copy; } else { @@ -637,6 +632,9 @@ public final class Unpooled { * {@code 0} and the length of the encoded string respectively. */ public static ByteBuf copiedBuffer(char[] array, Charset charset) { + if (array == null) { + throw new NullPointerException("array"); + } return copiedBuffer(array, 0, array.length, charset); } @@ -657,7 +655,7 @@ public final class Unpooled { } private static ByteBuf copiedBuffer(CharBuffer buffer, Charset charset) { - return ByteBufUtil.encodeString(ALLOC, buffer, charset); + return ByteBufUtil.encodeString0(ALLOC, true, buffer, charset); } /**