utf8Length function

int utf8Length(
  1. String s
)

The exact number of UTF-8 bytes s encodes to, without allocating the transcode buffer encodeUtf8Strict would.

This is what sizes a fixlen_word (and any buffer reservation) ahead of a string payload: the wire length of a string field is its UTF-8 byte length, not its Dart String length, and the two differ for anything above U+007F.

The walk is over code units, not runes: a surrogate pair is recognized and counted as the 4 bytes its code point encodes to, and no RuneIterator is allocated to find that out. An unpaired surrogate — the one thing a Dart String can hold that is not encodable at all, and for which encodeUtf8Strict returns null — is counted as 3 bytes here rather than reported: this answers "how large", and whether the string can be encoded is the encoder's answer to give.

Implementation

int utf8Length(String s) {
  final units = s.codeUnits;
  final n = units.length;
  var len = 0;
  var i = 0;
  while (i < n) {
    final c = units[i++];
    if (c < 0x80) {
      len += 1;
    } else if (c < 0x800) {
      len += 2;
    } else if (c >= 0xD800 && c <= 0xDBFF && i < n) {
      final c2 = units[i];
      if (c2 >= 0xDC00 && c2 <= 0xDFFF) {
        i++;
        len += 4; // surrogate pair: one code point above U+FFFF
      } else {
        len += 3; // unpaired high surrogate
      }
    } else {
      len += 3;
    }
  }
  return len;
}