Timmmm
Timmmm

Reputation: 96625

How to slice a ByteBuffer

Dart's ByteBuffer and ByteData are pretty direct copies of Javascript's ArrayBuffer and DataView respectively (but with even more confusing names!)

However there doesn't seem to be an equivalent to ArrayBuffer.slice(), that creates a copy of of part of an ArrayBuffer. Did I miss it? Is this deliberate or just an omission?

Upvotes: 0

Views: 981

Answers (1)

jamesdlin
jamesdlin

Reputation: 90015

You can copy part of a ByteBuffer, although the process might be a bit convoluted:

You can use Uint8List.view to create a Uint8List view (i.e., not a copy) of a ByteBuffer. From there you can use its sublist method to copy a portion of it to a new Uint8List, and then access its buffer property to get back a ByteBuffer.

In other words:

ByteBuffer slice = Uint8List.view(byteBuffer).sublist(start, end).buffer;

Another way to get a Uint8List view from a ByteBuffer and then creating a copy:

ByteBuffer slice = Uint8List.fromList(byteBuffer.asUint8List(start, end)).buffer;

In practice, I think this usually isn't quite as bad as it might seem since typically you'd start off from a Uint8List anyway.

Upvotes: 2

Related Questions