use ethnum::{I256, U256};
use crate::kernel::mul::{div_d_round, mul_128x128};
use crate::round::round_away;
use crate::{Dec19, Fixed19, OutOfRange, Round};
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
pub struct ProductSum {
total: I256,
}
impl ProductSum {
#[must_use]
pub const fn new() -> Self {
Self { total: I256::ZERO }
}
#[track_caller]
pub fn add<A: Fixed19, B: Fixed19>(&mut self, a: A, b: B) {
self
.checked_add(a, b)
.expect("ProductSum overflow: total out of 256-bit range");
}
pub fn checked_add<A: Fixed19, B: Fixed19>(
&mut self,
a: A,
b: B,
) -> Result<(), OutOfRange> {
let (neg_a, a) = a.__to_parts();
let (neg_b, b) = b.__to_parts();
let [w0, w1, w2, w3] = mul_128x128(a, b);
let product = U256::from_words(
((w3 as u128) << 64) | w2 as u128,
((w1 as u128) << 64) | w0 as u128,
);
let total = if neg_a != neg_b {
self.total.checked_sub_unsigned(product)
} else {
self.total.checked_add_unsigned(product)
};
self.total = total.ok_or(OutOfRange)?;
Ok(())
}
pub fn finish(&self, mode: Round) -> Result<Dec19, OutOfRange> {
let negative = self.total.is_negative();
let (hi, lo) = self.total.unsigned_abs().into_words();
let words = [lo as u64, (lo >> 64) as u64, hi as u64, (hi >> 64) as u64];
let magnitude = div_d_round(words, negative, mode).ok_or(OutOfRange)?;
Dec19::from_parts(negative, magnitude).ok_or(OutOfRange)
}
pub fn div<D: Fixed19>(
&self,
denominator: D,
mode: Round,
) -> Result<Dec19, OutOfRange> {
let (neg_d, d) = denominator.__to_parts();
if d == 0 {
return Err(OutOfRange);
}
let negative = self.total.is_negative() != neg_d;
let (q, r) = self.total.unsigned_abs().div_rem(U256::from(d));
let (q_high, q) = q.into_words();
if q_high != 0 {
return Err(OutOfRange);
}
let (_, r) = r.into_words();
let away = round_away(mode, negative, q & 1 == 1, r, d);
let magnitude = q.checked_add(away as u128).ok_or(OutOfRange)?;
Dec19::from_parts(negative, magnitude).ok_or(OutOfRange)
}
}