( num: bigint | number, buf: Uint8Array = new Uint8Array(MaxVarintLen64), offset = 0, )
| 217 | */ |
| 218 | // deno-lint-ignore deno-style-guide/exported-function-args-maximum |
| 219 | export function encodeVarint( |
| 220 | num: bigint | number, |
| 221 | buf: Uint8Array = new Uint8Array(MaxVarintLen64), |
| 222 | offset = 0, |
| 223 | ): [Uint8Array_, number] { |
| 224 | num = BigInt(num); |
| 225 | if (num < 0n) { |
| 226 | throw new RangeError( |
| 227 | `Cannot encode the input into varint as it should be non-negative integer: received ${num}`, |
| 228 | ); |
| 229 | } |
| 230 | if (num > MaxUint64) { |
| 231 | throw new RangeError( |
| 232 | `Cannot encode the input ${num} into varint as it overflows uint64`, |
| 233 | ); |
| 234 | } |
| 235 | for ( |
| 236 | let i = offset; |
| 237 | i < buf.length; |
| 238 | i += 1 |
| 239 | ) { |
| 240 | if (num < MSBN) { |
| 241 | buf[i] = Number(num); |
| 242 | i += 1; |
| 243 | return [buf.slice(offset, i), i]; |
| 244 | } |
| 245 | buf[i] = Number((num & 0xFFn) | MSBN); |
| 246 | num >>= SHIFTN; |
| 247 | } |
| 248 | throw new RangeError( |
| 249 | "Cannot encode the input into varint: the provided buffer is too small", |
| 250 | ); |
| 251 | } |
no test coverage detected