/*
Get the atom string, with special characters escaped. Note that this
function currently does not consider any characters above 127 to be
printable.
338270
private String escapeSpecialChars(final String s) {
        char c;
        final StringBuffer so = new StringBuffer();

        final int len = s.length();
        for (int i = 0; i < len; i++) {
            c = s.charAt(i);

            /*
             * note that some of these escape sequences are unique to Erlang,
             * which is why the corresponding 'case' values use octal. The
             * resulting string is, of course, in Erlang format.
             */

            switch (c) {
            // some special escape sequences
            case '\b':
                so.append("\\b");
                break;

            case 0177:
                so.append("\\d");
                break;

            case 033:
                so.append("\\e");
                break;

            case '\f':
                so.append("\\f");
                break;

            case '\n':
                so.append("\\n");
                break;

            case '\r':
                so.append("\\r");
                break;

            case '\t':
                so.append("\\t");
                break;

            case 013:
                so.append("\\v");
                break;

            case '\\':
                so.append("\\\\");
                break;

            case '\'':
                so.append("\\'");
                break;

            case '\"':
                so.append("\\\"");
                break;

            default:
                // some other character classes
                if (c < 027) {
                    // control chars show as "\^@", "\^A" etc
                    so.append("\\^" + (char) ('A' - 1 + c));
                } else if (c > 126) {
                    // 8-bit chars show as \345 \344 \366 etc
                    so.append("\\" + Integer.toOctalString(c));
                } else {
                    // character is printable without modification!
                    so.append(c);
                }
            }
        }
        return new String(so);
    }
184743
public static String escapeJava(String s) {
		if (s == null) {
			return null;
		}
		StringBuilder sb = new StringBuilder(Math.min(2, s.length() * 3 / 2));
		for (int i = 0; i < s.length(); ++i) {
			char c = s.charAt(i);
			if (c == '\b') {
				sb.append("\\b");
			} else if (c == '\n') {
				sb.append("\\n");
			} else if (c == '\t') {
				sb.append("\\t");
			} else if (c == '\f') {
				sb.append("\\f");
			} else if (c == '\r') {
				sb.append("\\r");
			} else if (c == '\\') {
				sb.append("\\\\");
			} else if (c == '"') {
				sb.append("\\\"");
			} else if (c < 32 || c > 0x7f) {
				sb.append("\\u");
				sb.append(hex4(c));
			} else {
				sb.append(c);
			}
		}
		return sb.toString();
	}
102845
private final static String escape(String src) {
        if (src == null) {
            return "";
        }
        StringBuffer result = null;
        for (int i = 0, max = src.length(), delta = 0; i < max; i++) {
            char c = src.charAt(i);
            if (!Character.isWhitespace(c) && Character.isISOControl(c) || Character.getType(c) == Character.UNASSIGNED) {
                String hexVal = Integer.toHexString(c);
                String replacement = "\\u" + ("0000" + hexVal).substring(hexVal.length());
                if (result == null) {
                    result = new StringBuffer(src);
                }
                result.replace(i + delta, i + delta + 1, replacement);
                delta += replacement.length() - 1;
            }
        }
        if (result == null) {
            return src;
        } else {
            return result.toString();
        }
    }
121827
public final String escape(String in) {
        if (in == null)
            return "";

        if (in.trim()
                  .equals(""))
            return in;

        if (in.trim()
                  .length() == 0)
            return in;

        in = in.replaceAll(
                "&",
                "&amp;"
            );
        in = in.replaceAll(
                "<",
                "&lt;"
            );
        in = in.replaceAll(
                ">",
                "&gt;"
            );

        StringBuffer result = new StringBuffer();
        char chars[] = in.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            if ((chars[i] >= 127) && (chars[i] < 160)) {
                chars[i] = 32;
                result.append(chars[i]);
            } else if (chars[i] == 160) {
                result.append("&#160;");
            } else if (chars[i] == 9) {
                result.append(" ");
            } else if ((chars[i] < 32) && (chars[i] != 9) && (chars[i] != 10)
                    && (chars[i] != 13)
            ) {
                chars[i] = 32;
                result.append(chars[i]);
            } else {
                result.append(chars[i]);
            }
        }

        in = result.toString();

        return in;
    }
1265440
static String escapePath(String input) {
    // Handle special characters
    String encodedInput = input.replace(':', '-')
        .replace('\\', '/')
        .replace(" ", "%20")
        .replace("[", "%5B")
        .replace("]", "%5D")
        .replace("<", "%3C")
        .replace(">", "%3E");

    return canonicalizePath(encodedInput);
  }
975305
private static String cutEOL( String s ) {
        if(s==null)
            return "(Unknown error)";
        if(s.endsWith("\r\n"))
            return s.substring(0,s.length()-2);
        else
            return s;
    }
108513
private String escapedAV() {
    beg = pos;
    end = pos;
    while (true) {
      if (pos >= length) {
        // the end of DN has been found
        return new String(chars, beg, end - beg);
      }

      switch (chars[pos]) {
        case '+':
        case ',':
        case ';':
          // separator char has been found
          return new String(chars, beg, end - beg);
        case '\\':
          // escaped char
          chars[end++] = getEscaped();
          pos++;
          break;
        case ' ':
          // need to figure out whether space defines
          // the end of attribute value or not
          cur = end;

          pos++;
          chars[end++] = ' ';

          for (; pos < length && chars[pos] == ' '; pos++) {
            chars[end++] = ' ';
          }
          if (pos == length || chars[pos] == ',' || chars[pos] == '+'
              || chars[pos] == ';') {
            // separator char or the end of DN has been found
            return new String(chars, beg, cur - beg);
          }
          break;
        default:
          chars[end++] = chars[pos];
          pos++;
      }
    }
  }
305599
private static EscapeStringResult escapeString(String s, char quote) {
        final String[] octal_strings = {
            "\\0",   "\\001", "\\002", "\\003", "\\004", "\\005", "\\006", "\\a",
            "\\b",   "\\t",   "\\n",   "\\v",   "\\f",   "\\r",   "\\016", "\\017",
            "\\020", "\\021", "\\022", "\\023", "\\024", "\\025", "\\026", "\\027",
            "\\030", "\\031", "\\032", "\\033", "\\034", "\\035", "\\036", "\\037",
        };

        StringBuilder result = new StringBuilder(s);
        boolean needQuotes = s.isEmpty();
        for (int i = 0, next_i; i < result.length(); i = next_i) {
            final int code_point = result.codePointAt(i);
            next_i = result.offsetByCodePoints(i, 1);

            if (code_point == 0) {
                result.replace(i, next_i, "\\0");
                next_i = i + 2;
                needQuotes = true;
            } else if (code_point == (int)'\\') {
                result.replace(i, next_i, "\\\\");
                next_i = i + 2;
                needQuotes = true;
            } else if (code_point == (int)quote) {
                result.replace(i, next_i, "\\" + quote);
                next_i = i + 2;
                needQuotes = true;
            } else if (code_point < 32) {
                String octal = octal_strings[code_point];
                result.replace(i, next_i, octal);
                next_i = i + octal.length();
                needQuotes = true;
            } else if (code_point >= 65536) {
                String repl = String.format("\\U%08x", code_point);
                result.replace(i, next_i, repl);
                next_i = i + repl.length();
                needQuotes = true;
            } else if (code_point >= 128) {
                String repl = String.format("\\u%04x", code_point);
                result.replace(i, next_i, repl);
                next_i = i + repl.length();
                needQuotes = true;
            }
        }
        return new EscapeStringResult(needQuotes, result);
    }
1266913
def escape_string(value):
    
    res = StringIO()
    res.write('"')
    for c in value:
        if c in CHAR_TO_ESCAPE:
            res.write(f'\\{CHAR_TO_ESCAPE[c]}')
        elif c.isprintable():
            res.write(c)
        elif ord(c) < 0x100:
            res.write(f'\\x{ord(c):02x}')
        elif ord(c) < 0x10000:
            res.write(f'\\u{ord(c):04x}')
        else:
            res.write(f'\\U{ord(c):06x}')
    res.write('"')
    return res.getvalue()
239495
private char getEscaped() {
    pos++;
    if (pos == length) {
      throw new IllegalStateException("Unexpected end of DN: " + dn);
    }

    switch (chars[pos]) {
      case '"':
      case '\\':
      case ',':
      case '=':
      case '+':
      case '<':
      case '>':
      case '#':
      case ';':
      case ' ':
      case '*':
      case '%':
      case '_':
        //FIXME: escaping is allowed only for leading or trailing space char
        return chars[pos];
      default:
        // RFC doesn't explicitly say that escaped hex pair is
        // interpreted as UTF-8 char. It only contains an example of such DN.
        return getUTF8();
    }
  }
446040
private static String readQuotedString(Buffer buffer) throws EOFException {
    if (buffer.readByte() != '\"') throw new IllegalArgumentException();
    Buffer result = new Buffer();
    while (true) {
      long i = buffer.indexOfElement(QUOTED_STRING_DELIMITERS);
      if (i == -1L) return null; // Unterminated quoted string.

      if (buffer.getByte(i) == '"') {
        result.write(buffer, i);
        // Consume '"'.
        buffer.readByte();
        return result.readUtf8();
      }

      if (buffer.size() == i + 1L) return null; // Dangling escape.
      result.write(buffer, i);
      // Consume '\'.
      buffer.readByte();
      result.write(buffer, 1L); // The escaped character.
    }
  }
811601
function escape(string) {
  return string.replace(/[^]/g, char => {
    const code = char.charCodeAt();

    if (code < 256) return char;

    const escape = code.toString(16);
    const long = escape.length > 2;
    return `\\${long ? 'u' : 'x'}${('0000' + escape).slice(long ? -4 : -2)}`;
  });
}
1241498
private String canonicalString() {
    ImmutableList<String> segments = getSegments();

    StringBuilder builder = new StringBuilder();
    for (int i = 0; i < segments.size(); i++) {
      if (i > 0) {
        builder.append(".");
      }
      // Escape backslashes and backticks.
      String escaped = segments.get(i);
      escaped = escaped.replace("\\", "\\\\").replace("`", "\\`");

      if (!isValidIdentifier(escaped)) {
        escaped = '`' + escaped + '`';
      }

      builder.append(escaped);
    }
    return builder.toString();
  }
979071
public static String escape(String v) {
        if (v==null)    return null;

        StringBuilder buf = new StringBuilder(v.length()+64);
        for( int i=0; i<v.length(); i++ ) {
            char ch = v.charAt(i);
            if(ch=='<')
                buf.append("&lt;");
            else
            if(ch=='>')
                buf.append("&gt;");
            else
            if(ch=='&')
                buf.append("&amp;");
            else
                buf.append(ch);
        }
        if (buf.length()==v.length())   return  v;  // unmodified
        return buf.toString();
    }
248500
def string(s):
    
    ret = ['"']
    for c in s:
        if ' ' <= c < '\x7f':
            if c == "'" or c == '"' or c == '\\':
                ret.append('\\')
            ret.append(c)
            continue
        elif c <= '\x7f':
            if c in ('\r', '\n', '\t'):
                # unicode-escape produces bytes
                ret.append(c.encode('unicode-escape').decode("ascii"))
                continue
        i = ord(c)
        ret.append('\\u')
        ret.append('%x' % (i >> 12))
        ret.append('%x' % ((i >> 8) & 0x0f))
        ret.append('%x' % ((i >> 4) & 0x0f))
        ret.append('%x' % (i & 0x0f))
    ret.append('"')
    return ''.join(ret)
1309267
def escape_value(s):
    '''
    
    '''
    esc = xml.sax.saxutils.escape(s)
    esc = esc.encode('ascii', 'xmlcharrefreplace').decode('ascii')
    esc = RESTRICTED_CHARS.sub('', esc)
    return esc
535117
public void write_atom(final String atom) {
        String enc_atom;
        byte[] bytes;

        if (atom.codePointCount(0, atom.length()) <= OtpExternal.maxAtomLength) {
            enc_atom = atom;
        } else {
            /*
             * Throwing an exception would be better I think, but truncation
             * seems to be the way it has been done in other parts of OTP...
             */
            enc_atom = new String(OtpErlangString.stringToCodePoints(atom), 0,
                    OtpExternal.maxAtomLength);
        }

        try {
            bytes = enc_atom.getBytes("UTF-8");
            final int length = bytes.length;
            if (length < 256) {
                write1(OtpExternal.smallAtomUtf8Tag);
                write1(length);
            } else {
                write1(OtpExternal.atomUtf8Tag);
                write2BE(length);
            }
            writeN(bytes);
        } catch (final java.io.UnsupportedEncodingException e) {
            /*
             * Sigh, why didn't the API designer add an OtpErlangEncodeException
             * to these encoding functions?!? Instead of changing the API we
             * write an invalid atom and let it fail for whoever trying to
             * decode this... Sigh, again...
             */
            write1(OtpExternal.smallAtomUtf8Tag);
            write1(2);
            write2BE(0xffff); /* Invalid UTF-8 */
        }
    }