use crate::FixedPoint;
use crate::core::constants::{constant_bank, sqrt_nth_prime};
use crate::core::equidistribution::{frac, wave_fold};
use crate::core::wrapping::{wrapping_add, wrapping_mul};
use crate::ToponError;
use super::MixingStrategy;
const LANES: usize = 8;
const FINALIZE_ROUNDS: usize = 4;
const MULTIPLIER_BASE: usize = 96;
pub struct ChaoticMixer {
constants: Vec<FixedPoint>,
multipliers: [FixedPoint; LANES],
inv_257: FixedPoint,
}
impl ChaoticMixer {
pub fn new(num_constants: usize) -> Result<Self, ToponError> {
let mut multipliers = [FixedPoint::ZERO; LANES];
for (i, m) in multipliers.iter_mut().enumerate() {
*m = sqrt_nth_prime(MULTIPLIER_BASE + i)?;
}
Ok(ChaoticMixer {
constants: constant_bank(num_constants.max(LANES))?,
multipliers,
inv_257: FixedPoint::one() / FixedPoint::from_int(257),
})
}
fn seed_lanes(&self) -> [FixedPoint; LANES] {
let mut lanes = [FixedPoint::ZERO; LANES];
for (i, lane) in lanes.iter_mut().enumerate() {
*lane = frac(self.multipliers[i] * FixedPoint::from_int(i as i32 + 1));
}
lanes
}
}
impl MixingStrategy for ChaoticMixer {
fn mix(&self, input: &[u8], num_components: usize) -> Result<Vec<FixedPoint>, ToponError> {
let n = self.constants.len();
let inv_257 = self.inv_257;
let mut lanes = self.seed_lanes();
for (pos, &byte) in input.iter().enumerate() {
let byte_norm = FixedPoint::from_int(byte as i32 + 1) * inv_257;
for (i, lane) in lanes.iter_mut().enumerate() {
let injection = byte_norm * self.constants[(pos + i) % n];
*lane = frac(*lane * self.multipliers[i] + injection);
}
}
for _ in 0..FINALIZE_ROUNDS {
for i in 0..LANES {
let neighbor = lanes[(i + 1) % LANES];
lanes[i] = frac(lanes[i] * self.multipliers[i] + neighbor);
}
}
let mut components = Vec::with_capacity(num_components);
for d in 0..num_components {
let mut acc = FixedPoint::ZERO;
for (i, lane) in lanes.iter().enumerate() {
acc = wrapping_add(acc, wrapping_mul(*lane, self.constants[(d + i) % n]));
}
components.push(wave_fold(wrapping_mul(acc, self.constants[d % n]))?);
}
Ok(components)
}
}