WriteBuffer { public static int utf8SizeInBytes(CharSequence string) { int sizeInBytes = 0; for (int i = 0, len = string.length(); i < len; i++) { char ch = string.charAt(i); if (ch < 0x80) { sizeInBytes++; while (i < len - 1) { ch = string.charAt(i + 1); if (ch >= 0x80) break; i++; sizeInBytes++; } } else if (ch < 0x800) { sizeInBytes += 2; } else if (ch < 0xd800 || ch > 0xdfff) { sizeInBytes += 3; } else { int low = i + 1 < len ? string.charAt(i + 1) : 0; if (ch > 0xdbff || low < 0xdc00 || low > 0xdfff) { sizeInBytes++; } else { sizeInBytes += 4; i++; } } } return sizeInBytes; } WriteBuffer(byte[] buf, int pos); static WriteBuffer wrap(byte[] bytes); static WriteBuffer wrap(byte[] bytes, int pos); void writeByte(int v); void write(byte[] v); void writeAscii(String v); void writeUtf8(CharSequence string); void writeUtf8(CharSequence string, int fromIndex, int toIndex); void writeAscii(long v); @Override String toString(); static int utf8SizeInBytes(CharSequence string); static int asciiSizeInBytes(long v);  }
@Test public void utf8SizeInBytes() { for (int codepoint = 0; codepoint <= 0x10FFFF; codepoint++) { if (codepoint == 0xD800) codepoint = 0xDFFF + 1; if (Character.isDefined(codepoint)) { String test = new String(Character.toChars(codepoint)); int expected = test.getBytes(UTF_8).length; int actual = WriteBuffer.utf8SizeInBytes(test); if (actual != expected) { throw new AssertionError(actual + " length != " + expected + " for " + codepoint); } } } }