parse static method

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

Parses a capsule from bytes starting at offset.

Returns a record containing the parsed Capsule and the total number of bytes consumed.

Implementation

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

  // Decode capsule type
  final typeLength = VarInt.decodeLength(bytes[offset]);
  if (offset + typeLength > bytes.length) {
    throw ArgumentError(
      'Buffer too short: need $typeLength bytes for capsule type',
    );
  }
  final type = VarInt.decode(bytes.buffer, offset: offset);

  // Decode data length
  final lengthOffset = offset + typeLength;
  if (lengthOffset >= bytes.length) {
    throw ArgumentError(
      'Buffer too short: missing capsule length at offset $lengthOffset',
    );
  }
  final lengthLength = VarInt.decodeLength(bytes[lengthOffset]);
  if (lengthOffset + lengthLength > bytes.length) {
    throw ArgumentError(
      'Buffer too short: need $lengthLength bytes for capsule length',
    );
  }
  final dataLength = VarInt.decode(bytes.buffer, offset: lengthOffset);
  if (dataLength > _maxCapsuleDataLength) {
    throw ArgumentError(
      'Capsule data length $dataLength exceeds maximum allowed '
      '$_maxCapsuleDataLength bytes',
    );
  }

  // Extract data
  final dataOffset = lengthOffset + lengthLength;
  if (dataOffset + dataLength > bytes.length) {
    throw ArgumentError(
      'Buffer too short: need $dataLength bytes for capsule data at offset '
      '$dataOffset, but buffer length is ${bytes.length}',
    );
  }
  final data = bytes.sublist(dataOffset, dataOffset + dataLength);

  final totalLength = typeLength + lengthLength + dataLength;

  final capsule = _createCapsule(type, data);
  return (capsule, totalLength);
}