String (final String str, EscapeInfoProvider p) { if (str == null) return null; int finalCount = calcFinalEscapedStringCount(str, p); if (str.length() == finalCount) return str; char[] resultChars = new char[finalCount]; int resultPos = 0; for (int i = 0; i < str.length(); i++) { char c = str.charAt(i); final char escaped = p.escape(c); if (escaped != 0) { resultChars[resultPos++] = p.escapeCharacter(); resultChars[resultPos++] = escaped; } else { resultChars[resultPos++] = c; } } if (resultPos != finalCount) { throw new RuntimeException("Incorrect escaping for '" + str + "'"); } return new String(resultChars); }