encodeText method

String encodeText(
  1. String text
)

Encodes the specified text in Modified UTF7 format. text specifies the text to be encoded.

Implementation

String encodeText(String text) {
  final encoded = StringBuffer();
  var shifted = false;
  var bits = 0, u = 0;

  for (var index = 0; index < text.length; index++) {
    var character = text[index];
    var codeUnit = character.codeUnitAt(0);
    if (codeUnit >= 0x20 && codeUnit < 0x7f) {
      // characters with octet values 0x20-0x25 and 0x27-0x7e
      // represent themselves while 0x26 ("&") is represented
      // by the two-octet sequence "&-"

      if (shifted) {
        _utf7ShiftOut(encoded, u, bits);
        shifted = false;
        bits = 0;
      }

      if (codeUnit == 0x26) {
        encoded.write('&-');
      } else {
        encoded.write(character);
      }
    } else {
      // base64 encode
      if (!shifted) {
        encoded.write('&');
        shifted = true;
      }

      u = (u << 16) | (codeUnit & 0xffff);
      bits += 16;

      while (bits >= 6) {
        final x = (u >> (bits - 6)) & 0x3f;
        encoded.write(_utf7Alphabet[x]);
        bits -= 6;
      }
    }
  }

  if (shifted) {
    _utf7ShiftOut(encoded, u, bits);
  }

  return encoded.toString();
}