FastBase58EncodingAlphabet function

String FastBase58EncodingAlphabet(
  1. List<int> bin,
  2. Alphabet alphabet
)

Implementation

String FastBase58EncodingAlphabet(List<int> bin, Alphabet alphabet) {
  var size = bin.length;

  var zcount = 0;
  for (; zcount < size && bin[zcount] == 0;) {
    zcount++;
  }

  // It is crucial to make this as short as possible, especially for
  // the usual case of bitcoin addrs
  size = (zcount +
      // This is an integer simplification of
      // ceil(log(256)/log(58))
      (size - zcount) * 555 ~/ 406 +
      1);

  var out = List<int>.filled(size, 0);

  var i = 0, high = 0;

  high = size - 1;
  bin.forEach((b) {
    i = size - 1;
    for (var carry = b; i > high || carry != 0; i--) {
      carry = (carry + 256 * (out[i])) & 0xffffffff;
      out[i] = carry % 58;
      carry = carry ~/ 58;
    }
    high = i;
  });

  // Determine the additional "zero-gap" in the buffer (aside from zcount)
  for (i = zcount; i < size && out[i] == 0; i++) {}

  // Now encode the values with actual alphabet in-place
  var val = out.sublist(i - zcount);
  size = val.length;
  for (i = 0; i < size; i++) {
    out[i] = alphabet.encode[val[i]];
  }

  return String.fromCharCodes(out.sublist(0, size));
}