Repository Public Apache-2.0
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// Project : SPB Quantum Crypto7// File : crates/spb-pqc-core/src/math/mldsa.rs8// Module : Crates9// Repository : https://git.spboucher.ai/spb-quantum-crypto10// Project Website : https://pqce.spboucher.ai11// Created : 2026-12-0312// Last Modified : 2026-12-0313//14// Author : Simon-Pierre Boucher15// Position : Professor of Finance16// Institution : Université du Québec en Outaouais (UQO)17// Organization : SP Boucher18// Website : https://spboucher.ai19// Git : https://git.spboucher.ai20//21// Preferred Contact: contact@spboucher.ai22// Development : dev@spboucher.ai23// Support : support@spboucher.ai24// Security/Admin : admin@spboucher.ai25//26// Copyright (c) 202627// Simon-Pierre Boucher28// All rights reserved where applicable. This file is governed by the29// applicable project license, copyright notices and relevant law.30// Existing third-party rights and notices remain unaffected.31//32// License : Apache-2.033//34// Do not embed credentials, private keys, access tokens,35// certificates or confidential personal information.36//37// =============================================================================38// END OF SP BOUCHER SOURCE HEADER39// =============================================================================4041//! Arithmetic of ML-DSA: `Z_q` with `q = 8380417 = 2^23 − 2^13 + 1`, the ring42//! `R_q = Z_q[X]/(X^256+1)`, its fully-split NTT, rounding, sampling and bit43//! packing (FIPS 204 §7).44//!45//! # Representation and bounds46//!47//! Coefficients are signed `i32`. Unlike ML-KEM, reduction is lazy and every48//! function documents the interval it accepts and returns:49//!50//! * [`montgomery_reduce`]`(a)`: `|a| < 2^31·q` → `r ≡ a·2^-32 (mod q)`, `|r| < q`.51//! Proof: `t = a·q⁻¹ mod± 2^32`, so `a − t·q ≡ 0 (mod 2^32)` and52//! `|a − t·q| < 2^31·q + 2^31·q = 2^32·q`.53//! * [`reduce32`]`(a)`: `a ≤ 2^31 − 2^22 − 1` → `r ≡ a`, `−6283008 ≤ r ≤ 6283008`.54//! * [`freeze`]`(a)`: same domain → canonical `[0, q)`.55//! * [`ntt`]: input `|c| < q` → output `|c| < 9q` (each of the 8 layers adds56//! one Montgomery product of magnitude `< q`).57//! * [`pointwise_montgomery`]: `|a·b| < 2^31·q` (true whenever both are `< 9q`58//! since `81·q² < 256·q² < 2^31·q`) → `|c| < q`, value `a·b·2^-32`.59//! * [`ntt_inv_tomont`]: input `|c| < q` → output `|c| < q`, value multiplied60//! by `2^32` (it cancels the factor of one Montgomery product). Inside, the61//! "sum" branch doubles per layer, so the largest intermediate is `< 256q < 2^31`.62//!63//! Secret-dependent code paths: [`ntt`], [`ntt_inv_tomont`], the reductions,64//! [`decompose`] and the packers are branch-free. [`rej_bounded_poly`] and the65//! signing loop reject on secret-derived values *by specification*; see66//! `docs/security/constant-time.md` for what that reveals.67//!68//! | FIPS 204 | Here |69//! |---------------------------------------|------------------------------|70//! | Alg. 16/18 `SimpleBitPack/Unpack` | [`simple_bit_pack`], [`simple_bit_unpack`] |71//! | Alg. 17/19 `BitPack/Unpack` | [`bit_pack`], [`bit_unpack`] |72//! | Alg. 29 `SampleInBall` | [`sample_in_ball`] |73//! | Alg. 30 `RejNTTPoly`, Alg. 14 | [`rej_ntt_poly`] |74//! | Alg. 31 `RejBoundedPoly`, Alg. 15 | [`rej_bounded_poly`] |75//! | Alg. 35 `Power2Round` | [`power2round`] |76//! | Alg. 36 `Decompose` | [`decompose`] |77//! | Alg. 37/38 `HighBits/LowBits` | via [`decompose`] |78//! | Alg. 39 `MakeHint`, Alg. 40 `UseHint` | [`make_hint`], [`use_hint`] |79//! | Alg. 41 `NTT`, Alg. 42 `NTT⁻¹` | [`ntt`], [`ntt_inv_tomont`] |80//! | Alg. 49 `MontgomeryReduce` | [`montgomery_reduce`] |81//! | Appendix B zetas | `ZETAS` (computed at compile time from ζ = 1753) |8283use crate::ct::wipe;84use crate::hash::keccak::Shake;8586/// Ring degree.87pub const N: usize = 256;88/// The prime modulus.89pub const Q: i32 = 8_380_417;90/// Number of dropped bits of `t`.91pub const D: u32 = 13;92/// `q⁻¹ mod 2^32`.93const QINV: i32 = 58_728_449;94const Q64: u64 = Q as u64;9596/// A polynomial of `R_q` (or its NTT image). Wiped on drop.97#[derive(Clone)]98pub struct Poly {99 /// Coefficients, lowest degree first.100 pub c: [i32; N],101}102103impl Poly {104 /// The zero polynomial.105 pub const fn zero() -> Self {106 Poly { c: [0; N] }107 }108}109110impl Drop for Poly {111 fn drop(&mut self) {112 wipe(&mut self.c);113 }114}115116/// Montgomery reduction (FIPS 204 Algorithm 49); see the module docs for the bound.117#[inline(always)]118pub fn montgomery_reduce(a: i64) -> i32 {119 let t = (a as i32).wrapping_mul(QINV);120 ((a - (t as i64) * (Q as i64)) >> 32) as i32121}122123/// Partial reduction to `[−6283008, 6283008]` for `a ≤ 2^31 − 2^22 − 1`.124#[inline(always)]125pub fn reduce32(a: i32) -> i32 {126 let t = (a + (1 << 22)) >> 23;127 a - t * Q128}129130/// Adds `q` if `a` is negative (constant time).131#[inline(always)]132pub fn caddq(a: i32) -> i32 {133 a + ((a >> 31) & Q)134}135136/// Canonical representative in `[0, q)`.137#[inline(always)]138pub fn freeze(a: i32) -> i32 {139 caddq(reduce32(a))140}141142/// Centered representative in `[−(q−1)/2, (q−1)/2]` of a canonical value.143#[inline(always)]144pub fn center(a: i32) -> i32 {145 debug_assert!((0..Q).contains(&a));146 // subtract q when a > (q-1)/2147 a - ((((Q - 1) / 2 - a) >> 31) & Q)148}149150const fn pow_mod(base: u64, mut exp: u32) -> u64 {151 let mut acc = 1u64;152 let mut b = base % Q64;153 while exp > 0 {154 if exp & 1 == 1 {155 acc = acc * b % Q64;156 }157 b = b * b % Q64;158 exp >>= 1;159 }160 acc161}162163const fn bitrev8(i: u32) -> u32 {164 let mut r = 0;165 let mut k = 0;166 while k < 8 {167 r |= ((i >> k) & 1) << (7 - k);168 k += 1;169 }170 r171}172173/// `2^32 mod q`.174const MONT: u64 = (1u64 << 32) % Q64;175176/// `ZETAS[k] = ζ^BitRev8(k) · 2^32 mod q`, ζ = 1753 (FIPS 204 Appendix B, in177/// Montgomery form, canonical representatives).178const ZETAS: [i32; N] = {179 let mut z = [0i32; N];180 let mut k = 0;181 while k < N {182 z[k] = (pow_mod(1753, bitrev8(k as u32)) * MONT % Q64) as i32;183 k += 1;184 }185 z186};187188/// `2^64 / 256 mod q`: final scaling of the inverse NTT, including one factor `2^32`.189const INV_NTT_F: i32 = {190 let inv256 = pow_mod(256, (Q - 2) as u32);191 (MONT * MONT % Q64 * inv256 % Q64) as i32192};193194/// Forward NTT, in place (FIPS 204 Algorithm 41). Input `|c| < q`, output `|c| < 9q`.195pub fn ntt(w: &mut Poly) {196 let w = &mut w.c;197 let mut m = 0;198 let mut len = 128;199 while len >= 1 {200 let mut start = 0;201 while start < N {202 m += 1;203 let z = ZETAS[m] as i64;204 for j in start..start + len {205 let t = montgomery_reduce(z * w[j + len] as i64);206 w[j + len] = w[j] - t;207 w[j] += t;208 }209 start += 2 * len;210 }211 len /= 2;212 }213}214215/// Inverse NTT times `2^32`, in place (FIPS 204 Algorithm 42 followed by a216/// multiplication by the Montgomery constant). Input `|c| < q`, output `|c| < q`.217pub fn ntt_inv_tomont(w: &mut Poly) {218 let w = &mut w.c;219 let mut m = N;220 let mut len = 1;221 while len < N {222 let mut start = 0;223 while start < N {224 m -= 1;225 let z = -(ZETAS[m] as i64);226 for j in start..start + len {227 let t = w[j];228 w[j] = t + w[j + len];229 w[j + len] = t - w[j + len];230 w[j + len] = montgomery_reduce(z * w[j + len] as i64);231 }232 start += 2 * len;233 }234 len *= 2;235 }236 for c in w.iter_mut() {237 *c = montgomery_reduce(INV_NTT_F as i64 * *c as i64);238 }239}240241/// Coefficient-wise Montgomery product `a ∘ b · 2^-32`.242pub fn pointwise_montgomery(a: &Poly, b: &Poly) -> Poly {243 let mut r = Poly::zero();244 for i in 0..N {245 r.c[i] = montgomery_reduce(a.c[i] as i64 * b.c[i] as i64);246 }247 r248}249250/// `a ← a + b` without reduction.251pub fn add_assign(a: &mut Poly, b: &Poly) {252 for i in 0..N {253 a.c[i] += b.c[i];254 }255}256257/// `a ← a − b` without reduction.258pub fn sub_assign(a: &mut Poly, b: &Poly) {259 for i in 0..N {260 a.c[i] -= b.c[i];261 }262}263264/// Applies [`reduce32`] to every coefficient.265pub fn poly_reduce(a: &mut Poly) {266 for c in a.c.iter_mut() {267 *c = reduce32(*c);268 }269}270271/// Applies [`freeze`] to every coefficient (result in `[0, q)`).272pub fn poly_freeze(a: &mut Poly) {273 for c in a.c.iter_mut() {274 *c = freeze(*c);275 }276}277278/// Infinity norm of the centered representatives, for coefficients within the279/// [`reduce32`] domain. No early exit: the scan length is independent of the data.280pub fn inf_norm(a: &Poly) -> i32 {281 let mut max = 0i32;282 for &c in a.c.iter() {283 let v = center(freeze(c));284 let abs = (v ^ (v >> 31)) - (v >> 31);285 // max = max(max, abs) without branching286 let gt = (max - abs) >> 31;287 max = (abs & gt) | (max & !gt);288 }289 max290}291292/// `Power2Round` (Alg. 35) for canonical `r`: `r = r1·2^13 + r0`, `r0 ∈ (−2^12, 2^12]`.293#[inline(always)]294pub fn power2round(r: i32) -> (i32, i32) {295 debug_assert!((0..Q).contains(&r));296 let r1 = (r + (1 << (D - 1)) - 1) >> D;297 (r1, r - (r1 << D))298}299300/// `Decompose` (Alg. 36) for canonical `r` and `γ2 ∈ {(q−1)/88, (q−1)/32}`:301/// returns `(r1, r0)` with `r ≡ r1·2γ2 + r0`, `r0 ∈ (−γ2, γ2]`, and the corner302/// case `r − r0 = q − 1 → (0, r0 − 1)`.303///304/// Division-free and branch-free: `r1` is obtained by multiplying305/// `⌈r / 2^7⌉` by a fixed-point reciprocal of `2γ2 / 2^7`. Exhaustively checked306/// against the literal definition for all `r ∈ [0, q)` and both `γ2`.307#[inline(always)]308pub fn decompose(r: i32, gamma2: i32) -> (i32, i32) {309 debug_assert!((0..Q).contains(&r));310 let mut r1 = (r + 127) >> 7;311 if gamma2 == (Q - 1) / 32 {312 r1 = (r1 * 1025 + (1 << 21)) >> 22;313 r1 &= 15;314 } else {315 debug_assert!(gamma2 == (Q - 1) / 88);316 r1 = (r1 * 11275 + (1 << 23)) >> 24;317 r1 ^= ((43 - r1) >> 31) & r1;318 }319 let mut r0 = r - r1 * 2 * gamma2;320 r0 -= (((Q - 1) / 2 - r0) >> 31) & Q;321 (r1, r0)322}323324/// `MakeHint(z, r)` (Alg. 39): whether adding `z` changes the high bits of `r`.325/// Both inputs canonical.326#[inline(always)]327pub fn make_hint(z: i32, r: i32, gamma2: i32) -> bool {328 let r1 = decompose(r, gamma2).0;329 let v1 = decompose(freeze(r + z), gamma2).0;330 r1 != v1331}332333/// `UseHint(h, r)` (Alg. 40) for canonical `r`. Used on public data only.334#[inline(always)]335pub fn use_hint(h: bool, r: i32, gamma2: i32) -> i32 {336 let m = (Q - 1) / (2 * gamma2);337 let (r1, r0) = decompose(r, gamma2);338 if !h {339 r1340 } else if r0 > 0 {341 (r1 + 1) % m342 } else {343 (r1 + m - 1) % m344 }345}346347/// `RejNTTPoly` (Alg. 30): uniform element of `T_q` from a 34-byte public seed348/// (SHAKE128, `CoeffFromThreeBytes`). Variable time on public data.349pub fn rej_ntt_poly(seed: &[u8; 34]) -> Poly {350 let mut xof = Shake::new_128();351 xof.absorb(seed);352 let mut a = Poly::zero();353 let mut j = 0;354 let mut block = [0u8; 168];355 while j < N {356 xof.squeeze(&mut block);357 for c in block.chunks_exact(3) {358 let z = c[0] as i32 | ((c[1] as i32) << 8) | (((c[2] & 0x7F) as i32) << 16);359 if z < Q && j < N {360 a.c[j] = z;361 j += 1;362 }363 }364 }365 a366}367368/// `RejBoundedPoly` (Alg. 31): coefficients in `[−η, η]` from a 66-byte seed369/// (SHAKE256, `CoeffFromHalfByte`), `η ∈ {2, 4}`.370///371/// The seed is secret. Rejection is mandated by the standard; what is372/// observable is the number of rejected nibbles, not the accepted values.373pub fn rej_bounded_poly(seed: &[u8; 66], eta: i32) -> Poly {374 debug_assert!(eta == 2 || eta == 4);375 let mut xof = Shake::new_256();376 xof.absorb(seed);377 let mut a = Poly::zero();378 let mut j = 0;379 let mut block = [0u8; 136];380 while j < N {381 xof.squeeze(&mut block);382 for &z in block.iter() {383 for half in [z & 0x0F, z >> 4] {384 let b = half as i32;385 if j < N {386 if eta == 2 && b < 15 {387 // 2 − (b mod 5), with b mod 5 computed without a division388 let b5 = b - ((205 * b) >> 10) * 5;389 a.c[j] = 2 - b5;390 j += 1;391 } else if eta == 4 && b < 9 {392 a.c[j] = 4 - b;393 j += 1;394 }395 }396 }397 }398 }399 wipe(&mut block);400 a401}402403/// `SampleInBall` (Alg. 29): polynomial with exactly `τ` coefficients in `{−1, 1}`404/// from the commitment hash `c̃`. Operates on public data (`c̃` is in the signature).405pub fn sample_in_ball(ctilde: &[u8], tau: usize) -> Poly {406 let mut xof = Shake::new_256();407 xof.absorb(ctilde);408 let mut s = [0u8; 8];409 xof.squeeze(&mut s);410 let signs = u64::from_le_bytes(s);411 let mut c = Poly::zero();412 for i in (N - tau)..N {413 let mut jb = [0u8; 1];414 loop {415 xof.squeeze(&mut jb);416 if jb[0] as usize <= i {417 break;418 }419 }420 let j = jb[0] as usize;421 c.c[i] = c.c[j];422 let bit = (signs >> (i + tau - N)) & 1;423 c.c[j] = 1 - 2 * bit as i32;424 }425 c426}427428/// Number of bits of a non-negative integer.429pub const fn bitlen(x: u32) -> u32 {430 32 - x.leading_zeros()431}432433/// `SimpleBitPack(w, b)` (Alg. 16): coefficients in `[0, b]`, `bitlen(b)` bits each.434pub fn simple_bit_pack(w: &Poly, bits: u32, out: &mut [u8]) {435 debug_assert_eq!(out.len(), 32 * bits as usize);436 let mut acc: u64 = 0;437 let mut n: u32 = 0;438 let mut o = 0;439 for &c in w.c.iter() {440 acc |= (c as u32 as u64) << n;441 n += bits;442 while n >= 8 {443 out[o] = acc as u8;444 o += 1;445 acc >>= 8;446 n -= 8;447 }448 }449}450451/// `SimpleBitUnpack(v, b)` (Alg. 18): returns coefficients in `[0, 2^bits)`.452pub fn simple_bit_unpack(v: &[u8], bits: u32) -> Poly {453 debug_assert_eq!(v.len(), 32 * bits as usize);454 let mask = (1u64 << bits) - 1;455 let mut w = Poly::zero();456 let mut acc: u64 = 0;457 let mut n: u32 = 0;458 let mut i = 0;459 for &b in v {460 acc |= (b as u64) << n;461 n += 8;462 while n >= bits && i < N {463 w.c[i] = (acc & mask) as i32;464 i += 1;465 acc >>= bits;466 n -= bits;467 }468 }469 w470}471472/// `BitPack(w, a, b)` (Alg. 17): coefficients in `[−a, b]` stored as `b − w_i`473/// on `bits = bitlen(a + b)` bits.474pub fn bit_pack(w: &Poly, b: i32, bits: u32, out: &mut [u8]) {475 let mut t = Poly::zero();476 for i in 0..N {477 t.c[i] = b - w.c[i];478 }479 simple_bit_pack(&t, bits, out);480}481482/// `BitUnpack(v, a, b)` (Alg. 19): returns `b − z_i`; the caller checks the483/// range when `a + b + 1` is not a power of two.484pub fn bit_unpack(v: &[u8], b: i32, bits: u32) -> Poly {485 let mut w = simple_bit_unpack(v, bits);486 for c in w.c.iter_mut() {487 *c = b - *c;488 }489 w490}491492#[cfg(test)]493mod tests {494 use super::*;495496 fn test_poly(tag: u8) -> Poly {497 let mut seed = [0u8; 34];498 seed[0] = tag;499 rej_ntt_poly(&seed)500 }501502 fn naive_mul(a: &Poly, b: &Poly) -> Poly {503 let mut r = [0i64; N];504 for i in 0..N {505 for j in 0..N {506 let p = (a.c[i] as i64 * b.c[j] as i64) % Q as i64;507 if i + j < N {508 r[i + j] = (r[i + j] + p) % Q as i64;509 } else {510 r[i + j - N] = (r[i + j - N] - p).rem_euclid(Q as i64);511 }512 }513 }514 let mut out = Poly::zero();515 for i in 0..N {516 out.c[i] = r[i].rem_euclid(Q as i64) as i32;517 }518 out519 }520521 #[test]522 fn constants() {523 assert_eq!((Q as i64 * QINV as i64) & 0xFFFF_FFFF, 1);524 assert_eq!(MONT, 4193792); // 2^32 mod q525 assert_eq!(INV_NTT_F, 41978); // mont^2 / 256526 // ζ = 1753 is a primitive 512th root of unity527 assert_eq!(pow_mod(1753, 256), Q64 - 1);528 assert_eq!(pow_mod(1753, 512), 1);529 // FIPS 204 Appendix B: zetas[1] = 4808194 (plain form), i.e. 1753^128530 assert_eq!(pow_mod(1753, bitrev8(1)), 4808194);531 assert_eq!(pow_mod(1753, bitrev8(2)), 3765607);532 // last entry: ζ^255 = −ζ⁻¹533 assert_eq!(pow_mod(1753, bitrev8(255)) * 1753 % Q64, Q64 - 1);534 }535536 #[test]537 fn montgomery_and_reduce_boundaries() {538 let r2 = (MONT * MONT % Q64) as i64; // 2^64 mod q539 for &a in &[540 0i64,541 1,542 -1,543 Q as i64 - 1,544 -(Q as i64) + 1,545 (1i64 << 31) * (Q as i64) - 1,546 -((1i64 << 31) * (Q as i64) - 1),547 123456789012345,548 ] {549 let r = montgomery_reduce(a);550 assert!(r.abs() < Q, "bound for a = {a}");551 // r·2^32 ≡ a (mod q)552 assert_eq!((r as i64 * MONT as i64 - a).rem_euclid(Q as i64), 0);553 let _ = r2;554 }555 for &a in &[0i32, 1, -1, Q, -Q, i32::MIN, i32::MAX - (1 << 22)] {556 let r = reduce32(a);557 assert!((-6283008..=6283008).contains(&r));558 assert_eq!((r as i64 - a as i64).rem_euclid(Q as i64), 0);559 assert_eq!(freeze(a) as i64, (a as i64).rem_euclid(Q as i64));560 }561 assert_eq!(center(0), 0);562 assert_eq!(center((Q - 1) / 2), (Q - 1) / 2);563 assert_eq!(center((Q + 1) / 2), -(Q - 1) / 2);564 assert_eq!(center(Q - 1), -1);565 }566567 #[test]568 fn ntt_round_trip_scales_by_montgomery_constant() {569 let a = test_poly(1);570 let mut x = a.clone();571 ntt(&mut x);572 assert!(x.c.iter().all(|c| c.abs() < 9 * Q));573 poly_reduce(&mut x);574 ntt_inv_tomont(&mut x);575 for i in 0..N {576 assert_eq!(freeze(x.c[i]) as u64, a.c[i] as u64 * MONT % Q64);577 }578 }579580 #[test]581 fn ntt_product_equals_schoolbook_product() {582 for tag in 0..3u8 {583 let a = test_poly(30 + tag);584 let b = test_poly(40 + tag);585 let (mut na, mut nb) = (a.clone(), b.clone());586 ntt(&mut na);587 ntt(&mut nb);588 let mut p = pointwise_montgomery(&na, &nb);589 ntt_inv_tomont(&mut p);590 poly_freeze(&mut p);591 assert_eq!(p.c, naive_mul(&a, &b).c);592 }593 // boundary: all coefficients q−1594 let mut top = Poly::zero();595 top.c = [Q - 1; N];596 let mut n1 = top.clone();597 ntt(&mut n1);598 let mut p = pointwise_montgomery(&n1, &n1);599 ntt_inv_tomont(&mut p);600 poly_freeze(&mut p);601 assert_eq!(p.c, naive_mul(&top, &top).c);602 }603604 #[test]605 fn decompose_matches_definition_exhaustively() {606 for gamma2 in [(Q - 1) / 88, (Q - 1) / 32] {607 let alpha = 2 * gamma2;608 for r in 0..Q {609 // literal Algorithm 36610 let mut r0 = r % alpha;611 if r0 > alpha / 2 {612 r0 -= alpha;613 }614 let (e1, e0) = if r - r0 == Q - 1 {615 (0, r0 - 1)616 } else {617 ((r - r0) / alpha, r0)618 };619 assert_eq!(decompose(r, gamma2), (e1, e0), "r = {r}, γ2 = {gamma2}");620 }621 }622 }623624 #[test]625 fn power2round_matches_definition_exhaustively() {626 for r in 0..Q {627 let mut r0 = r % (1 << D);628 if r0 > (1 << (D - 1)) {629 r0 -= 1 << D;630 }631 assert_eq!(power2round(r), ((r - r0) >> D, r0));632 }633 }634635 #[test]636 fn hints_recover_high_bits() {637 // UseHint(MakeHint(z, r), r) = HighBits(r + z) for |z| ≤ γ2 (FIPS 204 §7.4)638 for gamma2 in [(Q - 1) / 88, (Q - 1) / 32] {639 let mut r = 1i64;640 for step in 0..200_000 {641 r = (r * 1_103_515_245 + 12345) % Q as i64;642 let z = ((step * 7919) % (2 * gamma2 as i64 + 1)) - gamma2 as i64;643 let (rr, zz) = (r as i32, freeze(z as i32));644 let h = make_hint(zz, rr, gamma2);645 let expect = decompose(freeze(rr + zz), gamma2).0;646 assert_eq!(use_hint(h, rr, gamma2), expect);647 }648 }649 }650651 #[test]652 fn samplers_respect_their_ranges() {653 for eta in [2, 4] {654 let p = rej_bounded_poly(&[7u8; 66], eta);655 assert!(p.c.iter().all(|&c| (-eta..=eta).contains(&c)));656 assert!(p.c.contains(&eta) && p.c.contains(&-eta));657 }658 for tau in [39usize, 49, 60] {659 let c = sample_in_ball(&[3u8; 32], tau);660 assert_eq!(c.c.iter().filter(|&&x| x != 0).count(), tau);661 assert!(c.c.iter().all(|&x| (-1..=1).contains(&x)));662 }663 // b mod 5 trick used by CoeffFromHalfByte664 for b in 0..15 {665 assert_eq!(b - ((205 * b) >> 10) * 5, b % 5);666 }667 }668669 #[test]670 fn packing_round_trips() {671 let mut p = test_poly(9);672 for c in p.c.iter_mut() {673 *c &= 0x3FF;674 }675 let mut buf = [0u8; 320];676 simple_bit_pack(&p, 10, &mut buf);677 assert_eq!(simple_bit_unpack(&buf, 10).c, p.c);678679 for (b, bits) in [680 (1i32 << 17, 18u32),681 (1 << 19, 20),682 (1 << 12, 13),683 (2, 3),684 (4, 4),685 ] {686 let mut w = test_poly(11);687 let a = if bits >= 13 { b - 1 } else { b };688 for c in w.c.iter_mut() {689 *c = (*c % (a + b + 1)) - a; // in [−a, b]690 }691 let mut buf = vec![0u8; 32 * bits as usize];692 bit_pack(&w, b, bits, &mut buf);693 assert_eq!(bit_unpack(&buf, b, bits).c, w.c);694 }695 assert_eq!(bitlen(0), 0);696 assert_eq!(bitlen(43), 6);697 assert_eq!(bitlen(15), 4);698 }699}700