UDXPacket.fromBytes constructor

UDXPacket.fromBytes(
  1. Uint8List bytes
)

Creates a UDX packet from raw bytes. New header format (variable length): 0-3: version (4 bytes) 4: destinationCidLength (1 byte) 5 to 5+destCidLen: destinationConnectionId 5+destCidLen: sourceCidLength (1 byte) 6+destCidLen to 6+destCidLen+srcCidLen: sourceConnectionId Next 4: sequence Next 4: destinationStreamId Next 4: sourceStreamId Rest: frames

Implementation

factory UDXPacket.fromBytes(Uint8List bytes) {
  const minHeaderLength = 18; // version(4) + dcidLen(1) + scidLen(1) + seq(4) + destId(4) + srcId(4)
  if (bytes.length < minHeaderLength) {
    throw ArgumentError(
        'Byte array too short for UDXPacket. Minimum $minHeaderLength bytes required, got ${bytes.length}');
  }
  final view =
      ByteData.view(bytes.buffer, bytes.offsetInBytes, bytes.lengthInBytes);

  int offset = 0;

  // Read version
  final version = view.getUint32(offset, Endian.big);
  offset += 4;

  // Read destination CID
  final destCidLength = view.getUint8(offset);
  offset += 1;
  if (destCidLength < ConnectionId.minCidLength || destCidLength > ConnectionId.maxCidLength) {
    throw ArgumentError('Invalid destination CID length: $destCidLength');
  }
  final destCid = ConnectionId.fromUint8List(
      bytes.sublist(offset, offset + destCidLength));
  offset += destCidLength;

  // Read source CID
  final srcCidLength = view.getUint8(offset);
  offset += 1;
  if (srcCidLength < ConnectionId.minCidLength || srcCidLength > ConnectionId.maxCidLength) {
    throw ArgumentError('Invalid source CID length: $srcCidLength');
  }
  final srcCid = ConnectionId.fromUint8List(
      bytes.sublist(offset, offset + srcCidLength));
  offset += srcCidLength;

  // Read sequence, stream IDs
  final sequence = view.getUint32(offset, Endian.big);
  offset += 4;
  final destinationStreamId = view.getUint32(offset, Endian.big);
  offset += 4;
  final sourceStreamId = view.getUint32(offset, Endian.big);
  offset += 4;

  // Parse frames
  final frames = <Frame>[];
  while (offset < bytes.length) {
    final frame = Frame.fromBytes(view, offset);
    frames.add(frame);
    offset += frame.length;
  }

  return UDXPacket(
    version: version,
    destinationCid: destCid,
    sourceCid: srcCid,
    destinationStreamId: destinationStreamId,
    sourceStreamId: sourceStreamId,
    sequence: sequence,
    frames: frames,
  );
}