JsonEscaper { public static int jsonEscapedSizeInBytes(CharSequence v) { boolean ascii = true; int escapingOverhead = 0; for (int i = 0, length = v.length(); i < length; i++) { char c = v.charAt(i); if (c == '\u2028' || c == '\u2029') { escapingOverhead += 5; } else if (c >= 0x80) { ascii = false; } else { String maybeReplacement = REPLACEMENT_CHARS[c]; if (maybeReplacement != null) escapingOverhead += maybeReplacement.length() - 1; } } if (ascii) return v.length() + escapingOverhead; return WriteBuffer.utf8SizeInBytes(v) + escapingOverhead; }  static int jsonEscapedSizeInBytes(CharSequence v); static void jsonEscape(CharSequence in, WriteBuffer out);  }
@Test public void testJsonEscapedSizeInBytes() { assertThat(jsonEscapedSizeInBytes(new String(new char[] {0, 'a', 1}))) .isEqualTo(13); assertThat(jsonEscapedSizeInBytes(new String(new char[] {'"', '\\', '\t', '\b'}))) .isEqualTo(8); assertThat(jsonEscapedSizeInBytes(new String(new char[] {'\n', '\r', '\f'}))) .isEqualTo(6); assertThat(jsonEscapedSizeInBytes("\u2028 and \u2029")) .isEqualTo(17); assertThat(jsonEscapedSizeInBytes("\"foo")) .isEqualTo(5); }