toDartStringList method

List<String> toDartStringList(
  1. int maxLength
)

Decodes a double-NUL-terminated UTF-16 string array.

This format is commonly used by Win32 APIs to return lists of strings (e.g., environment blocks or file name lists).

Each string is NUL-terminated, and the array itself is terminated by an additional NUL code unit.

Decoding stops when:

  • A double-NUL terminator is encountered, or
  • maxLength UTF-16 code units have been read

Example:

const strings = ['banana', 'strawberry', 'kiwi'];
final block = strings.toPwstr();
print(block.toDartStringList(24)); // ['banana', 'strawberry', 'kiwi']
print(block.toDartStringList(7)); // ['banana']
print(block.toDartStringList(10)); // ['banana', 'str']
free(block);

Implementation

List<String> toDartStringList(int maxLength) {
  RangeError.checkNotNegative(maxLength, 'maxLength');

  final result = <String>[];
  final buffer = StringBuffer();
  final ptr = cast<WCHAR>();

  for (var i = 0; i < maxLength; i++) {
    final value = (ptr + i).value;

    if (value == 0) {
      // A NUL terminator indicates the end of the current string.
      if (buffer.isNotEmpty) {
        result.add(buffer.toString());
        buffer.clear();
      }

      // Double-NUL terminator marks the end of the array.
      if ((ptr + i + 1).value == 0) break;
    } else {
      // Append non-NUL character to the buffer.
      buffer.writeCharCode(value);
    }
  }

  // Add any remaining string in the buffer to the list.
  if (buffer.isNotEmpty) result.add(buffer.toString());

  return result;
}