decodeVarint function

MapEntry<int, int> decodeVarint(
  1. Uint8List bytes, [
  2. int offset = 0
])

Decodes a varint from the beginning of the bytes list. Returns a pair: the decoded integer and the number of bytes consumed. Throws FormatException if varint is malformed or incomplete.

Implementation

MapEntry<int, int> decodeVarint(Uint8List bytes, [int offset = 0]) {
  if (bytes.isEmpty || offset >= bytes.length) {
    throw FormatException('Cannot decode varint from empty or exhausted buffer');
  }

  int result = 0;
  int shift = 0;
  int bytesRead = 0;

  for (int i = offset; i < bytes.length; i++) {
    bytesRead++;
    final byte = bytes[i];
    result |= (byte & 0x7F) << shift;
    shift += 7;

    if ((byte & 0x80) == 0) { // MSB is not set, this is the last byte
      return MapEntry(result, bytesRead);
    }

    if (shift > 63) { // Prevent overflow for standard integer types
        throw FormatException('Varint too long to decode into a 64-bit integer');
    }
  }
  throw FormatException('Varint incomplete: expected more bytes');
}