serializePoly function

Uint8List serializePoly(
  1. List<int> poly
)

Serialize a polynomial (a list of integers in [0, q)) into a bytestring.

Mirrors serialize_poly: builds an integer buffer where coefficient idx occupies bits [idx*14, idx*14 + 14), then returns its big-endian byte representation, padded/truncated to bytelen = (n*14 + 7) >> 3 bytes.

Throws ArgumentError if any coefficient is < 0 or >= q, exactly like the reference's bounds check.

Implementation

Uint8List serializePoly(List<int> poly) {
  final int n = poly.length;

  BigInt buffer = BigInt.zero;
  for (int idx = 0; idx < n; idx++) {
    final int coef = poly[idx];
    if (coef < 0 || coef >= FalconUtils.q) {
      throw ArgumentError('The entries of poly are outside bounds');
    }
    // `|=` and `^=` are equivalent here because the 14-bit slots never overlap.
    buffer |= BigInt.from(coef) << (idx * _bitsPerCoef);
  }

  // The "+ 7" rounds up to the nearest whole byte.
  final int byteLen = (n * _bitsPerCoef + 7) >> 3;
  return _bigIntToBytesBE(buffer, byteLen);
}