readVarUint method

int readVarUint()

Read a variable length unsigned integer from the buffer encoded as an LEB128 unsigned integer.

Implementation

int readVarUint() {
  int result = 0;
  if (kIsWeb) {
    // Use a double multiplier instead of bit shifting to avoid 32-bit
    // overflow on web platforms. JavaScript bitwise operations truncate to
    // 32-bit signed integers, but floating-point multiplication works
    // correctly for integers up to 2^53.
    double multiplier = 1;
    while (true) {
      int byte = buffer.getUint8(readIndex++) & 0xff;
      result += ((byte & 0x7f) * multiplier).toInt();
      if ((byte & 0x80) == 0) break;
      multiplier *= 128; // 2^7
    }
  } else {
    int shift = 0;
    while (true) {
      int byte = buffer.getUint8(readIndex++) & 0xff;
      result |= (byte & 0x7f) << shift;
      if ((byte & 0x80) == 0) break;
      shift += 7;
    }
  }
  return result;
}