decodeText method

String decodeText(
  1. String text, [
  2. Encoding codec = utf8
])

Decodes the specified text

codec the optional character encoding (charset, defaults to utf-8)

Implementation

String decodeText(String text, [Encoding codec = utf8]) {
  var decoded = StringBuffer();
  var shifted = false;
  var bits = 0, v = 0;
  var index = 0;
  String c;

  while (index < text.length) {
    c = text[index++];

    if (shifted) {
      final codeUnit = c.codeUnitAt(0);
      if (c == '-') {
        // shifted back out of modified UTF-7
        shifted = false;
        bits = v = 0;
      } else if (codeUnit > 127) {
        // invalid UTF-7
        return text;
      } else {
        final rank = _utf7Rank[codeUnit];

        if (rank == 0xff) {
          // invalid UTF-7
          return text;
        }

        v = (v << 6) | rank;
        bits += 6;

        if (bits >= 16) {
          var u = ((v >> (bits - 16)) & 0xffff);
          decoded.write(String.fromCharCode(u));
          bits -= 16;
        }
      }
    } else if (c == '&' && index < text.length) {
      if (text[index] == '-') {
        decoded.write('&');
        index++;
      } else {
        // shifted into modified UTF-7
        shifted = true;
      }
    } else {
      decoded.write(c);
    }
  }

  return decoded.toString();
}