toBytes method

Uint8List toBytes()

Converts the UDX packet to raw bytes

Implementation

Uint8List toBytes() {
  final framesBytes =
      frames.map((f) => f.toBytes()).expand((b) => b).toList();

  // Calculate header length: version(4) + dcidLen(1) + dcid + scidLen(1) + scid + seq(4) + destId(4) + srcId(4)
  final headerLength = 4 + 1 + destinationCid.length + 1 + sourceCid.length + 4 + 4 + 4;
  final buffer = Uint8List(headerLength + framesBytes.length);
  final view = ByteData.view(buffer.buffer);

  int offset = 0;

  // Write version
  view.setUint32(offset, version, Endian.big);
  offset += 4;

  // Write destination CID
  view.setUint8(offset, destinationCid.length);
  offset += 1;
  buffer.setAll(offset, destinationCid.bytes);
  offset += destinationCid.length;

  // Write source CID
  view.setUint8(offset, sourceCid.length);
  offset += 1;
  buffer.setAll(offset, sourceCid.bytes);
  offset += sourceCid.length;

  // Write sequence and stream IDs
  view.setUint32(offset, sequence, Endian.big);
  offset += 4;
  view.setUint32(offset, destinationStreamId, Endian.big);
  offset += 4;
  view.setUint32(offset, sourceStreamId, Endian.big);
  offset += 4;

  // Write frames
  buffer.setAll(offset, framesBytes);

  return buffer;
}