static ByteBuffer encode(
            final ByteBuffer buffer, final CharBuffer in, final CharsetEncoder encoder) throws CharacterCodingException {

        final int capacity = (int) (in.remaining() * encoder.averageBytesPerChar());
        ByteBuffer out = ensureFreeCapacity(buffer, capacity);
        while (in.hasRemaining()) {
            CoderResult result = encoder.encode(in, out, true);
            if (result.isError()) {
                result.throwException();
            }
            if (result.isUnderflow()) {
                result = encoder.flush(out);
            }
            if (result.isUnderflow()) {
                break;
            }
            if (result.isOverflow()) {
                out = ensureFreeCapacity(out, capacity);
            }
        }
        return out;
    }
Builder class for sequences of bytes.

@since 5.0
httpclient5/src/main/java/org/apache/hc/client5/http/utils/ByteArrayBuilder.java