findCID method

Future<int?> findCID(
  1. CID cid
)

Returns the byte offset of the section containing cid, or null if not present.

For CAR v1 and CAR v2 the returned offset is relative to the start of the CAR v1 data payload. For CAR v2 the index is used when available; otherwise a streaming scan is performed.

Implementation

Future<int?> findCID(CID cid) async {
  // If an index is present, use it.
  final index = await _loadIndex();
  if (index != null) {
    final digest = Uint8List.fromList(cid.multihash.digest);
    final match = index.firstWhere(
      (e) => _bytesEqual(e.digest, digest),
      orElse: () => _IndexEntry(cid, -1),
    );
    if (match.offset >= 0) return match.offset;
    return null;
  }

  // Fallback: linear scan.
  var offset = 0;
  final payload = await _loadV1Payload();

  final (varintLen, headerSize) = _readVarint(payload, 0);
  offset += varintLen;
  // Skip the header bytes; the linear scan only needs the section CIDs.
  offset += headerSize;

  while (offset < payload.length) {
    final (varintLen, sectionLen) = _readVarint(payload, offset);
    offset += varintLen;
    final (sectionCid, cidLen) = _parseCid(payload, offset);
    if (sectionCid == cid) return offset;
    offset += sectionLen;
  }

  return null;
}