decodeVarint function
Decodes a varint (LEB128) from buffer starting at offset.
Returns a map with two entries:
'value': the decoded unsigned integer.'bytesRead': the number of bytes consumed from the buffer.
Throws a FormatException if the varint exceeds 10 bytes (the maximum for a 64-bit value) or if the buffer ends before the varint is complete.
Implementation
Map<String, int> decodeVarint(List<int> buffer, int offset) {
int result = 0;
int shift = 0;
int bytesRead = 0;
while (true) {
if (offset + bytesRead >= buffer.length) {
throw FormatException(
'Unexpected end of buffer while decoding varint at offset $offset',
);
}
int byte = buffer[offset + bytesRead];
bytesRead++;
// Accumulate the 7 payload bits at the current shift position.
result = result | ((byte & 0x7F) << shift);
shift += 7;
// If the continuation bit (MSB) is not set, we are done.
if ((byte & 0x80) == 0) {
break;
}
// Varints longer than 10 bytes cannot represent a 64-bit value.
if (bytesRead >= 10) {
throw FormatException(
'Varint exceeds maximum length of 10 bytes at offset $offset',
);
}
}
return {'value': result, 'bytesRead': bytesRead};
}