toPwstr method

PWSTR toPwstr({
  1. Allocator allocator = adaptiveMalloc,
})

Converts this list into a double-NUL-terminated UTF-16 string block.

The returned pointer must be freed using free, unless allocated through an Arena.

Example:

const strings = ['banana', 'strawberry', 'kiwi'];
final multiSz = strings.toPwstr();
// Pass to registry or shell APIs
free(multiSz); // Remember to free when done.

Implementation

PWSTR toPwstr({Allocator allocator = adaptiveMalloc}) {
  if (isEmpty) throw ArgumentError('The list must not be empty.');

  if (any((string) => string.isEmpty)) {
    throw ArgumentError('The list must not contain empty strings.');
  }

  final totalUnits = fold<int>(0, (sum, s) => sum + s.length + 1) + 1;
  final buffer = allocator<WCHAR>(totalUnits);
  var index = 0;

  for (final value in this) {
    final units = value.codeUnits;
    for (var i = 0; i < units.length; i++) {
      buffer[index++] = units[i];
    }
    buffer[index++] = 0;
  }

  buffer[index] = 0; // Final NUL terminator.
  return .new(buffer.cast());
}