public static ByteBuffer encode(String s, Charset cs, ByteBuffer bb) {
CharsetEncoder ce = ThreadLocalCoders.encoderFor(cs)
.onMalformedInput(CodingErrorAction.REPLACE)
.onUnmappableCharacter(CodingErrorAction.REPLACE);
CharBuffer cb = CharBuffer.wrap((char[])UNSAFE.getObject(s, STRING_CHAR_ARRAY_OFFSET));
ce.reset();
CoderResult rt = ce.encode(cb, bb, true);
if (rt == CoderResult.OVERFLOW) {
bb.flip();
ByteBuffer lbb = ByteBuffer.allocate((int)(s.length() * (double)ce.maxBytesPerChar()));
lbb.put(bb);