utf8Bytes function

Uint8List utf8Bytes(
  1. String text
)

text as UTF-8 bytes. Same bytes as utf8.encode. An ASCII text is written straight into a list of the right size. utf8.encode first makes a list 3 times the text length, then copies the used part.

Implementation

Uint8List utf8Bytes(String text) {
  int length = text.length;
  for (int i = 0; i < length; i++) {
    if (text.codeUnitAt(i) > 0x7F) return utf8.encode(text);
  }
  Uint8List out = Uint8List(length);
  for (int i = 0; i < length; i++) {
    out[i] = text.codeUnitAt(i);
  }
  return out;
}