class JsonEscaper {

  public static void jsonEscape(CharSequence in, WriteBuffer out) {
    int length = in.length();
    if (length == 0) return;

    int afterReplacement = 0;
    for (int i = 0; i < length; i++) {
      char c = in.charAt(i);
      String replacement;
      if (c < 0x80) {
        replacement = REPLACEMENT_CHARS[c];
        if (replacement == null) continue;
      } else if (c == '\u2028') {
        replacement = U2028;
      } else if (c == '\u2029') {
        replacement = U2029;
      } else {
        continue;
      }
      if (afterReplacement < i) { // write characters between the last replacement and now
        out.writeUtf8(in, afterReplacement, i);
      }
      out.writeUtf8(replacement, 0, replacement.length());
      afterReplacement = i + 1;
    }

    if (afterReplacement < length) {
      out.writeUtf8(in, afterReplacement, length);
    }
  }

}