* * @param {Number} val * @returns {Buffer}
(val)
| 1334 | * @returns {Buffer} |
| 1335 | */ |
| 1336 | function uvintPack(val) { |
| 1337 | const rv = []; |
| 1338 | if (val < 128) { |
| 1339 | rv.push(val); |
| 1340 | } else { |
| 1341 | let v = val; |
| 1342 | let numExtraBytes = 0; |
| 1343 | let numBits = v.toString(2).length; |
| 1344 | let reservedBits = numExtraBytes + 1; |
| 1345 | |
| 1346 | while (numBits > (8 - reservedBits)) { |
| 1347 | numExtraBytes += 1; |
| 1348 | numBits -= 8; |
| 1349 | reservedBits = Math.min(numExtraBytes + 1, 8); |
| 1350 | rv.push(v & 0xff); |
| 1351 | v >>= 8; |
| 1352 | } |
| 1353 | |
| 1354 | if (numExtraBytes > 8) { |
| 1355 | throw new Error(`Value ${val} is too big and cannot be encoded as vint`); |
| 1356 | } |
| 1357 | |
| 1358 | const n = 8 - numExtraBytes; |
| 1359 | v |= (0xff >> n) << n; |
| 1360 | rv.push(Math.abs(v)); |
| 1361 | } |
| 1362 | |
| 1363 | rv.reverse(); |
| 1364 | return Buffer.from(rv); |
| 1365 | } |
| 1366 | |
| 1367 | return { |
| 1368 | readVInt: readVInt, |