#include "rivide/internal/kem_encode.h"
#include "rivide/internal/kem_compress.h"
void poly_tobytes(uint8_t *buf, const poly_t *p) {
unsigned int i;
for (i = 0; i < KEM_N / 2; i++) {
uint16_t t0 = (uint16_t)((uint16_t)p->coeffs[2 * i] & 0x0FFF);
uint16_t t1 = (uint16_t)((uint16_t)p->coeffs[2 * i + 1] & 0x0FFF);
buf[3 * i] = (uint8_t)(t0 & 0xFF);
buf[3 * i + 1] = (uint8_t)((t0 >> 8) | ((t1 & 0x0F) << 4));
buf[3 * i + 2] = (uint8_t)(t1 >> 4);
}
}
void poly_frombytes(poly_t *p, const uint8_t *buf) {
unsigned int i;
for (i = 0; i < KEM_N / 2; i++) {
p->coeffs[2 * i] =
(int16_t)(((uint16_t)buf[3 * i] | ((uint16_t)buf[3 * i + 1] << 8)) & 0x0FFF);
p->coeffs[2 * i + 1] =
(int16_t)((((uint16_t)buf[3 * i + 1] >> 4) | ((uint16_t)buf[3 * i + 2] << 4)) & 0x0FFF);
}
}
void poly_frommsg(poly_t *p, const uint8_t msg[32]) {
unsigned int i, j;
for (i = 0; i < 32; i++) {
for (j = 0; j < 8; j++) {
p->coeffs[8 * i + j] = decompress_coeff((uint16_t)((msg[i] >> j) & 1), 1);
}
}
}
void poly_tomsg(uint8_t msg[32], const poly_t *p) {
unsigned int i, j;
for (i = 0; i < 32; i++) {
msg[i] = 0;
for (j = 0; j < 8; j++) {
uint16_t t = compress_coeff(p->coeffs[8 * i + j], 1);
msg[i] |= (uint8_t)(t << j);
}
}
}
void polyvec_tobytes(uint8_t *buf, const polyvec_t *v, int k) {
int i;
for (i = 0; i < k; i++) {
poly_tobytes(buf + 384 * i, &v->vec[i]);
}
}
void polyvec_frombytes(polyvec_t *v, const uint8_t *buf, int k) {
int i;
for (i = 0; i < k; i++) {
poly_frombytes(&v->vec[i], buf + 384 * i);
}
}