encodeVarintBigInt static method

List<int> encodeVarintBigInt(
  1. BigInt value
)

Encodes value (0 to 2^64-1) as a Bitcoin-style varint.

Implementation

static List<int> encodeVarintBigInt(BigInt value) {
  if (value < BigInt.zero || value > BinaryOps.maxU64) {
    throw BuError(
      DefaultErrorType.badCbor,
      "Failed to encode value as varint.",
    );
  }
  if (value < BigInt.from(253)) {
    return [value.toInt()];
  }
  if (value < BigInt.from(0x10000)) {
    final bytes = List<int>.filled(3, 0);
    bytes[0] = 0xfd;
    BinaryOps.writeUint16LE(value.toInt(), bytes, 1);
    return 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, ...value.toLeBytes(length: 8)];
}