encodeUnsigned static method

Uint8List encodeUnsigned(
  1. dynamic d
)

Can serialize an int or a BigInt as a leb128 unsigned format.

Implementation

static Uint8List encodeUnsigned(dynamic d) {
    if (d is! BigInt && d is! int) {
        throw Exception('leb128 encode parameter must be an int or a BigInt');
    }

    BigInt x = d is int ? BigInt.from(d) : d;

    if (x < BigInt.from(0)) {
        throw Exception('leb128 encode unsigned variable must be >= 0');
    }
    String bitstring = x.toRadixString(2);
    while (bitstring.length % 7 != 0) {
        bitstring = '0' + bitstring;
    }
    List<String> bit_groups_7 = [];
    for (int i=0;i<bitstring.length / 7; i++) {
        String bit_group_7 = bitstring.substring(i*7, i*7+7);

        String put_high_bit = i==0 ? '0' : '1';
        bit_groups_7.add(put_high_bit + bit_group_7);
    }
    List<int> leb128_bytes = [];
    for (String bit_group_7 in bit_groups_7.reversed) {
        leb128_bytes.add(int.parse(bit_group_7, radix:2));
    }
    return Uint8List.fromList(leb128_bytes);
}