slebEncode function

Uint8List slebEncode(
  1. Comparable value
)

Encode a number (or bigint) into a Buffer, with support for negative numbers. The number will be floored to the nearest integer. @param value The number to encode.

Implementation

Uint8List slebEncode(Comparable value) {
  var bn = value is BigInt ? value : BigInt.from(value as num);

  final isNeg = bn < BigInt.zero;
  if (isNeg) {
    bn = -bn - BigInt.one;
  }

  int getLowerBytes(BigInt num) {
    final bytes = num % BigInt.from(0x80);
    if (isNeg) {
      // We swap the bits here again, and remove 1 to do two's complement.
      return (BigInt.from(0x80) - bytes - BigInt.one).toInt();
    } else {
      return (bytes).toInt();
    }
  }

  List<int> pipe = [];

  while (true) {
    final i = getLowerBytes(bn);
    bn = (bn ~/ BigInt.from(0x80));

    // prettier-ignore
    if ((isNeg && bn == BigInt.zero && (i & 0x40) != 0) ||
        (!isNeg && bn == BigInt.zero && (i & 0x40) == 0)) {
      pipe.add(i);
      break;
    } else {
      pipe.add(i | 0x80);
    }
  }

  return Uint8List.fromList(pipe);
}