polycompress function
Compresses a polynomial into a byte array representation.
This function takes a polynomial a
and reduces its coefficients before
compressing them into a compact byte array format. The polynomial is processed
in chunks of four coefficients, each being mapped to a 10-bit value. These
values are packed into a sequence of bytes, with five bytes encoding four
coefficients. The resulting byte array is suitable for storage or transmission
in applications where space efficiency is critical.
- Parameter a: The polynomial to be compressed.
- Returns: A byte array containing the compressed representation of the polynomial.
Implementation
Uint8List polycompress(Poly a) {
Uint8List r = Uint8List(KYBER_POLYCOMPRESSEDBYTES);
Poly t = polyreduce(Poly()..coeffs = List<int>.from(a.coeffs));
int pos = 0;
for (int i = 0; i < KYBER_N; i += 4) {
int d0 = ((t.coeffs[i] << 10) + (KYBER_Q >> 1)) ~/ KYBER_Q & 0x3FF;
int d1 = ((t.coeffs[i + 1] << 10) + (KYBER_Q >> 1)) ~/ KYBER_Q & 0x3FF;
int d2 = ((t.coeffs[i + 2] << 10) + (KYBER_Q >> 1)) ~/ KYBER_Q & 0x3FF;
int d3 = ((t.coeffs[i + 3] << 10) + (KYBER_Q >> 1)) ~/ KYBER_Q & 0x3FF;
int packed = d0 | (d1 << 10) | (d2 << 20) | ((d3 & 0x3F) << 30);
r[pos] = packed & 0xFF;
r[pos + 1] = (packed >> 8) & 0xFF;
r[pos + 2] = (packed >> 16) & 0xFF;
r[pos + 3] = (packed >> 24) & 0xFF;
r[pos + 4] = (d3 >> 6) & 0xFF;
pos += 5;
}
return r;
}