decodeNativeString function

  1. @visibleForTesting
String decodeNativeString(
  1. Pointer<Char> ptr, {
  2. int? maxBytes,
})

Decode a NUL-terminated native string without throwing on malformed bytes.

Utf8Pointer.toDartString throws FormatException the moment the buffer isn't valid UTF-8, which is the worst possible behaviour on the error path: a native failure then surfaces as a complaint about character encoding, and the actual message — the only thing that would explain the failure — is lost. That misdirection cost real debugging time when LiteRT-LM v0.15.0 changed the stream-callback ABI and this path started receiving register garbage. Decoding leniently keeps whatever the native layer did send readable, with U+FFFD standing in for the unreadable bytes.

maxBytes bounds an error message only (a broken one might lack its NUL). Generated text and a send_message reply are read to their NUL: a cap there would cut a long reply silently.

Implementation

@visibleForTesting
String decodeNativeString(Pointer<Char> ptr, {int? maxBytes}) {
  final bytes = ptr.cast<Uint8>();
  var length = 0;
  while ((maxBytes == null || length < maxBytes) && bytes[length] != 0) {
    length++;
  }
  return utf8.decode(bytes.asTypedList(length), allowMalformed: true);
}