slebEncode function

Uint8List slebEncode(
  1. dynamic 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(dynamic value) {
  BigInt bn = switch (value) {
    BigInt() => value,
    num() => BigInt.from(value),
    String() => BigInt.parse(value),
    _ => throw ArgumentError('Invalid big number: $value', 'slebEncode'),
  };
  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();
    }
  }

  final 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);
}