| 172 | * ``` |
| 173 | */ |
| 174 | export function decodeVarint32(buf: Uint8Array, offset = 0): [number, number] { |
| 175 | let shift = 0; |
| 176 | let decoded = 0; |
| 177 | for ( |
| 178 | let i = offset; |
| 179 | i <= Math.min(buf.length, offset + MaxVarintLen32); |
| 180 | i += 1, shift += SHIFT |
| 181 | ) { |
| 182 | const byte = buf[i]!; |
| 183 | decoded += (byte & REST) * Math.pow(2, shift); |
| 184 | if (!(byte & MSB)) return [decoded, i + 1]; |
| 185 | } |
| 186 | throw new RangeError( |
| 187 | "Cannot decode the varint input: Malformed or overflow varint", |
| 188 | ); |
| 189 | } |
| 190 | |
| 191 | /** |
| 192 | * Takes unsigned number `num` and converts it into a Varint encoded |