0
votes

I'm trying to length prefix a payload that i'm streaming through a socket, and so far the only way i've been able to get it working is:

Uint8List payload = getPayloadSomehow();
final lBytes = ByteData(4)..setUint32(0, payload.length);
final prefix = lBytes.buffer.asUint8List();
final prefixedPayload = []..addAll(prefix)..addAll(payload);

Creating a ByteData and filling it with the length, and then extracting the buffer as a Uint8List feels very roundabout. But i haven't been able to find a cleaner way to do the conversion and prefixing.

I'd really appreciate it if someone could point me to a better solution, thanks.

1

1 Answers

1
votes

How about:

var payload = getPayloadSomehow();
var prefixed = Uint8List(payload.length + 4);
prefixed.buffer.asUint32List(0, 1)[0] = payload.length;
prefixed.setRange(4, prefixed.length, payload);