typed_data icon indicating copy to clipboard operation
typed_data copied to clipboard

Converting Uint8Buffer -> Uint8List

Open jonasfj opened this issue 6 years ago • 1 comments

It's not obvious to me how to convert aUint8Buffer to a Uint8List.

I imagine Uint8Buffer is useful when building a binary representation of something where I don't know the size of the output yet..

Uint8List serializeObjectStructure(Object input) {
  final result = Uint8Buffer();
  _writeInputRecursively(result, input);
  return Uint8List.fromList(result); // <-- is this efficient?
}

It would faster to do:

return Uint8List.view(result.buffer, 0, result.length);

Perhaps we should expose as UintBuffer.view() or Uint8Buffer.asUint8List(), with documentation pointing out that changing the length of the Uint8Buffer will cause the Uint8List to be decoupled.

It might also be enough to just do a documentation example. Thoughts?

jonasfj avatar Mar 18 '19 13:03 jonasfj

The correct approach is return Uint8List.view(result.buffer, 0, result.length);.

We should probably make that clear in documentation. We could provide a toUint8List on the Uint8Buffer, which destructively clears the buffer and creates a Uint8List on the same data.

lrhn avatar Nov 23 '20 17:11 lrhn