static String decodeString(ByteBuffer src, Charset charset) { final CharsetDecoder decoder = CharsetUtil.getDecoder(charset); final CharBuffer dst = CharBuffer.allocate((int) ((double) src.remaining() * decoder.maxCharsPerByte())); try { CoderResult cr = decoder.decode(src, dst, true); if (!cr.isUnderflow()) { cr.throwException(); } cr = decoder.flush(dst); if (!cr.isUnderflow()) { cr.throwException(); } } catch (CharacterCodingException x) { throw new IllegalStateException(x); } return dst.flip().toString(); }
static ByteBuffer encodeString(CharBuffer src, Charset charset) { final CharsetEncoder encoder = CharsetUtil.getEncoder(charset); final ByteBuffer dst = ByteBuffer.allocate((int) ((double) src.remaining() * encoder.maxBytesPerChar())); try { CoderResult cr = encoder.encode(src, dst, true); if (!cr.isUnderflow()) { cr.throwException(); } cr = encoder.flush(dst); if (!cr.isUnderflow()) { cr.throwException(); } } catch (CharacterCodingException x) { throw new IllegalStateException(x); } dst.flip(); return dst; }
@Override public String toUtf8() { if (!buffer.hasRemaining()) { return ""; } final CharsetDecoder decoder = CharsetUtil.getDecoder(Charsets.UTF_8); final CharBuffer dst = CharBuffer.allocate((int) ((double) buffer.remaining() * decoder.maxCharsPerByte())); try { CoderResult cr = decoder.decode(buffer, dst, true); if (!cr.isUnderflow()) { cr.throwException(); } cr = decoder.flush(dst); if (!cr.isUnderflow()) { cr.throwException(); } } catch (CharacterCodingException x) { throw new IllegalStateException(x); } return dst.flip().toString(); }