parse static method

(WebTransportCapsule, int) parse(
  1. Uint8List bytes, {
  2. int offset = 0,
})

Parse from bytes.

Returns the parsed WebTransportCapsule and the number of bytes consumed.

Implementation

static (WebTransportCapsule, int) parse(Uint8List bytes, {int offset = 0}) {
  if (offset < 0 || offset > bytes.length) {
    throw ArgumentError('Offset $offset out of bounds');
  }

  final baseOffset = bytes.offsetInBytes + offset;
  final buffer = bytes.buffer;

  // Read type varint
  final typeValue = VarInt.decode(buffer, offset: baseOffset);
  final typeByteLength = VarInt.decodeLength(bytes[offset]);

  // Read length varint
  final lengthValue = VarInt.decode(
    buffer,
    offset: baseOffset + typeByteLength,
  );
  final lengthByteLength =
      VarInt.decodeLength(bytes[offset + typeByteLength]);

  final headerLength = typeByteLength + lengthByteLength;
  final totalLength = headerLength + lengthValue;

  if (offset + totalLength > bytes.length) {
    throw ArgumentError(
      'Buffer too short: need $totalLength bytes starting at offset '
      '$offset, but buffer length is ${bytes.length}',
    );
  }

  final type = CapsuleType.fromValue(typeValue);
  if (type == null) {
    throw ArgumentError(
      'Unknown capsule type: 0x${typeValue.toRadixString(16)}',
    );
  }

  final payloadOffset = offset + headerLength;
  final payload = Uint8List.sublistView(
    bytes,
    payloadOffset,
    payloadOffset + lengthValue,
  );

  return (WebTransportCapsule(type: type, payload: payload), totalLength);
}