ByteBufUtil { public static int writeUtf8(ByteBuf buf, CharSequence seq) { if (buf == null) { throw new NullPointerException("buf"); } if (seq == null) { throw new NullPointerException("seq"); } final int len = seq.length(); final int maxSize = len * 3; buf.ensureWritable(maxSize); if (buf instanceof AbstractByteBuf) { AbstractByteBuf buffer = (AbstractByteBuf) buf; int oldWriterIndex = buffer.writerIndex; int writerIndex = oldWriterIndex; for (int i = 0; i < len; i++) { char c = seq.charAt(i); if (c < 0x80) { buffer._setByte(writerIndex++, (byte) c); } else if (c < 0x800) { buffer._setByte(writerIndex++, (byte) (0xc0 | (c >> 6))); buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f))); } else { buffer._setByte(writerIndex++, (byte) (0xe0 | (c >> 12))); buffer._setByte(writerIndex++, (byte) (0x80 | ((c >> 6) & 0x3f))); buffer._setByte(writerIndex++, (byte) (0x80 | (c & 0x3f))); } } buffer.writerIndex = writerIndex; return writerIndex - oldWriterIndex; } else { byte[] bytes = seq.toString().getBytes(CharsetUtil.UTF_8); buf.writeBytes(bytes); return bytes.length; } } private  ByteBufUtil(); static String hexDump(ByteBuf buffer); static String hexDump(ByteBuf buffer, int fromIndex, int length); static int hashCode(ByteBuf buffer); static boolean equals(ByteBuf bufferA, ByteBuf bufferB); static int compare(ByteBuf bufferA, ByteBuf bufferB); static int indexOf(ByteBuf buffer, int fromIndex, int toIndex, byte value); static short swapShort(short value); static int swapMedium(int value); static int swapInt(int value); static long swapLong(long value); static ByteBuf readBytes(ByteBufAllocator alloc, ByteBuf buffer, int length); static int writeUtf8(ByteBuf buf, CharSequence seq); static int writeAscii(ByteBuf buf, CharSequence seq); static ByteBuf encodeString(ByteBufAllocator alloc, CharBuffer src, Charset charset); static ByteBuf threadLocalDirectBuffer();  }
@Test public void testWriteUtf8() { String usAscii = "Some UTF-8 like äÄ∏ŒŒ"; ByteBuf buf = ReferenceCountUtil.releaseLater(Unpooled.buffer(16)); buf.writeBytes(usAscii.getBytes(CharsetUtil.UTF_8)); ByteBuf buf2 = ReferenceCountUtil.releaseLater(Unpooled.buffer(16)); ByteBufUtil.writeUtf8(buf2, usAscii); Assert.assertEquals(buf, buf2); }