convert method

  1. @override
String convert(
  1. String data
)
inherited

Converts from HTML-escaped data to unescaped string.

Implementation

@override
String convert(String data) {
  // Return early if possible.
  if (!data.contains('&')) return data;

  final buf = StringBuffer();
  var offset = 0;

  while (true) {
    final nextAmp = data.indexOf('&', offset);
    if (nextAmp == -1) {
      // Rest of string.
      buf.write(data.substring(offset));
      break;
    }
    buf.write(data.substring(offset, nextAmp));
    offset = nextAmp;

    var chunk =
        data.substring(offset, min(data.length, offset + _chunkLength));

    // Try { and ÿ
    if (chunk.length > _minDecimalEscapeLength &&
        chunk.codeUnitAt(1) == _hashCodeUnit) {
      final nextSemicolon = chunk.indexOf(';');
      if (nextSemicolon != -1) {
        var hex = chunk.codeUnitAt(2) == _xCodeUnit;
        var str = chunk.substring(hex ? 3 : 2, nextSemicolon);
        final ord = int.tryParse(str, radix: hex ? 16 : 10) ?? -1;
        if (ord != -1) {
          buf.write(String.fromCharCode(ord));
          offset += nextSemicolon + 1;
          continue;
        }
      }
    }

    // Try  
    var replaced = false;
    for (var i = 0; i < keys.length; i++) {
      var key = keys[i];
      if (chunk.startsWith(key)) {
        var replacement = values[i];
        buf.write(replacement);
        offset += key.length;
        replaced = true;
        break;
      }
    }
    if (!replaced) {
      buf.write('&');
      offset += 1;
    }
  }

  return buf.toString();
}