| 1 |
module.exports = read |
| 2 |
|
| 3 |
var MSB = 0x80 |
| 4 |
, REST = 0x7F |
| 5 |
|
| 6 |
function read(buf, offset) { |
| 7 |
var res = 0 |
| 8 |
, offset = offset || 0 |
| 9 |
, shift = 0 |
| 10 |
, counter = offset |
| 11 |
, b |
| 12 |
, l = buf.length |
| 13 |
|
| 14 |
do { |
| 15 |
if (counter >= l || shift > 49) { |
| 16 |
read.bytes = 0 |
| 17 |
throw new RangeError('Could not decode varint') |
| 18 |
} |
| 19 |
b = buf[counter++] |
| 20 |
res += shift < 28 |
| 21 |
? (b & REST) << shift |
| 22 |
: (b & REST) * Math.pow(2, shift) |
| 23 |
shift += 7 |
| 24 |
} while (b >= MSB) |
| 25 |
|
| 26 |
read.bytes = counter - offset |
| 27 |
|
| 28 |
return res |
| 29 |
} |