encodeVarint function

Uint8List encodeVarint(
  1. int number
)

Encodes an unsigned integer into varint bytes.

Implementation

Uint8List encodeVarint(int number) {
  if (number < 0) {
    throw ArgumentError('Varint input must be non-negative');
  }
  if (number == 0) {
    return Uint8List.fromList([0]);
  }

  final List<int> bytes = [];
  while (number > 0) {
    int byte = number & 0x7F; // Get the lowest 7 bits
    number >>= 7; // Shift right by 7 bits
    if (number > 0) {
      byte |= 0x80; // Set MSB if more bytes are coming
    }
    bytes.add(byte);
  }
  return Uint8List.fromList(bytes);
}