encodeVarint function

List<int> encodeVarint(
  1. List<int> buffer,
  2. int value
)

Appends the varint-encoded (LEB128) representation of value to buffer.

Each output byte carries 7 bits of payload in bits 0–6 and a continuation flag in bit 7 (MSB). The continuation bit is set on every byte except the last, signaling that more bytes follow.

value is treated as an unsigned 64-bit integer. Negative Dart ints (which are two's-complement 64-bit) will encode as their unsigned representation — 10 bytes for the full 64-bit range.

Returns the same buffer list with the varint bytes appended, allowing fluent chaining.

Implementation

List<int> encodeVarint(List<int> buffer, int value) {
  // Mask to unsigned 64-bit: on the Dart VM, ints are already 64-bit
  // two's-complement, so negative values naturally produce the unsigned
  // bit pattern when processed with >>> (logical right shift).
  int remaining = value;
  do {
    // Extract the lowest 7 bits.
    int byte = remaining & 0x7F;
    // Logical right shift by 7 to advance to the next group.
    remaining = remaining >>> 7;
    // If there are more groups to encode, set the continuation bit.
    if (remaining != 0) {
      byte = byte | 0x80;
    }
    buffer.add(byte);
  } while (remaining != 0);
  return buffer;
}