writeString method

void writeString(
  1. String text, [
  2. int? maxLength,
  3. int elementOffset = 0
])

Writes text into a buffer field at address + elementOffset*2. If maxLength is null, it's derived from the UTF-16 code unit length of text (caller is responsible for the field actually being that size).

maxLength is in UTF-16 code units, not bytes. Truncates if text exceeds maxLength; otherwise NUL-terminates and zero-pads the remainder.

Implementation

void writeString(String text, [int? maxLength, int elementOffset = 0]) {
  var units = text.codeUnits; // List<int>, one per UTF-16 code unit
  var len = maxLength ?? units.length;
  var writeLen = units.length < len ? units.length : len;

  // Don't leave a lone leading surrogate at the truncation boundary.
  if (
    writeLen < units.length &&
    writeLen > 0 && _isHighSurrogate(units[writeLen - 1])
  ) writeLen--;

  final dst = offsetBy(elementOffset * 2).asView<Uint16List>(len);
  dst.setRange(0, writeLen, units);
  dst.fillRange(writeLen, len, 0);
}