escape function

String escape(
  1. String string, [
  2. String encode(
    1. int charCode
    )?
])

Returns an escaped string.

Example: print(escape("Hello 'world' \n")); => Hello 'world' \n

Implementation

String escape(String string, [String Function(int charCode)? encode]) {
  if (string.isEmpty) {
    return string;
  }

  encode ??= toUnicode;
  final sb = StringBuffer();
  final characters = Characters(string);
  for (final s in characters) {
    final runes = s.runes;
    if (runes.length == 1) {
      final c = runes.first;
      if (c >= _C0_START && c <= _C0_END) {
        switch (c) {
          case 9:
            sb.write('\\t');
            break;
          case 10:
            sb.write('\\n');
            break;
          case 13:
            sb.write('\\r');
            break;
          default:
            sb.write(encode(c));
        }
      } else if (c >= _ASCII_START && c <= _ASCII_END) {
        switch (c) {
          case 34:
            sb.write('\\\"');
            break;
          case 36:
            sb.write('\\\$');
            break;
          case 39:
            sb.write("\\\'");
            break;
          case 92:
            sb.write('\\\\');
            break;
          default:
            sb.write(s);
        }
      } else if (_isPrintable(c)) {
        sb.write(s);
      } else {
        sb.write(encode(c));
      }
    } else {
      // Experimental: Assuming that all clusters does not need to be escaped
      sb.write(s);
    }
  }

  return sb.toString();
}