wnafForm static method

List<int> wnafForm(
  1. List<int> c,
  2. int window
)

Implementation

static List<int> wnafForm(List<int> c, int window) {
  assert(window >= 2);
  assert(window <= 64);

  final bitLen = c.length * 8;
  final List<int> wnaf = [];

  // Initialize limb buffer
  final limbs = LimbBuffer(c);

  final BigInt width = BigInt.one << window; // 2^window
  final BigInt windowMask = width - BigInt.one;

  int pos = 0;
  BigInt carry = BigInt.zero;

  while (pos < bitLen) {
    final int u64Idx = pos ~/ 64;
    final int bitIdx = pos % 64;

    final (curU64, nextU64) = limbs.get(u64Idx);

    // Extract window bits
    BigInt bitBuf;
    if (bitIdx + window < 64) {
      bitBuf = (curU64 >> bitIdx).toU64;
    } else {
      bitBuf = ((curU64 >> bitIdx).toU64 | (nextU64 << (64 - bitIdx))).toU64;
    }

    final windowVal = carry + (bitBuf & windowMask);

    if ((windowVal & BigInt.one) == BigInt.zero) {
      // Even → output zero, carry stays same
      wnaf.add(0);
      pos += 1;
    } else {
      // Odd → compute signed digit
      if (windowVal < width ~/ BigInt.two) {
        carry = BigInt.zero;
        wnaf.add(windowVal.toInt());
      } else {
        carry = BigInt.one;
        wnaf.add((windowVal - width).toInt());
      }

      // Fill next window-1 digits with 0
      for (int i = 0; i < window - 1; i++) {
        wnaf.add(0);
      }

      pos += window;
    }
  }
  return wnaf;
}