encodeVarintBigInt static method

List<int> encodeVarintBigInt(
  1. BigInt value
)

Implementation

static List<int> encodeVarintBigInt(BigInt value) {
  // Range check: 0 ≤ value ≤ 2^64 - 1
  if (value < BigInt.zero || value > BinaryOps.maxU64) {
    throw LayoutException("Failed to encode value as varint.");
  }
  // Fits in 1 byte
  if (value < BigInt.from(253)) {
    return [value.toInt()];
  }

  // Fits in 2 bytes
  if (value < BigInt.from(0x10000)) {
    final bytes = List<int>.filled(3, 0);
    bytes[0] = 0xfd;
    BinaryOps.writeUint16LE(value.toInt(), bytes, 1);
    return bytes;
  }

  // Fits in 4 bytes
  if (value < BigInt.from(0x100000000)) {
    final bytes = List<int>.filled(5, 0);
    bytes[0] = 0xfe;
    BinaryOps.writeUint32LE(value.toInt(), bytes, 1);
    return bytes;
  }
  return [
    0xff,
    ...BigintUtils.toBytes(value, length: 8, order: Endian.little),
  ];
}