code: private static String truncateAsJson(String s, int maxSerializedLength) {
      int resultLength = 0;
      int spaceLeft = maxSerializedLength - 2; // enclosing quotes always consume 2 slots
  
      for (char c : s.toCharArray()) {
        final boolean charNeedsEscape = c == '\\' || c == '"' || c == '\t';
  
        spaceLeft -= charNeedsEscape ? 2 : 1;
        if (spaceLeft < 0) {
          break;
        }
        resultLength++;
      }
  
      return truncate(s, resultLength);
    }
docs: Returns the given string truncated so its JSON representation does not exceed the given length.
  <p>
  Assumes the input contains only printable characters, with whitespace restricted to spaces and horizontal tabs.