public static int byteCount(CharSequence str, int offset, int length) {
        int count = 0;
        int barrier = offset + length;
        int i = offset;
        while (i < barrier) {
            int codePoint = (int) str.charAt(i);
            if (codePoint < 0x800) {
                if (codePoint < 0x80) {
                    ++count;
                } else {
                    count += 2;
                }
                ++i;
            } else {
                // bit masking to check (codePoint >= 0xd800 && codePoint <
                // 0xe000)
                if ((codePoint & 0xF800) == 0xD800) {
                    count += 4;
                    i += 2;
                } else {
                    count += 3;
                    ++i;
                }
            }
        }
        return count;
    }
Count the number of bytes needed to represent a given sequence of 16-bit
char values as a UTF-8 encoded array. This method is written to be cheap
to invoke.

Note: It is strongly assumed to character sequence is valid.
vespajlib/src/main/java/com/yahoo/text/Utf8.java