const MAX_BITS: u32 = i64::BITS - 1;
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct Modulus {
bits: u32,
}
impl Modulus {
#[must_use]
pub const fn new<const BITS: u32>() -> Self {
const {
assert!(
BITS >= 1 && BITS <= MAX_BITS,
"a modulus is 1..=63 bits wide"
);
}
Self { bits: BITS }
}
#[must_use]
pub const fn try_new(bits: u32) -> Option<Self> {
if bits >= 1 && bits <= MAX_BITS {
Some(Self { bits })
} else {
None
}
}
#[must_use]
pub const fn bits(self) -> u32 {
self.bits
}
#[must_use]
pub const fn modulus(self) -> u64 {
1u64 << self.bits
}
#[must_use]
pub const fn mask(self) -> u64 {
self.modulus() - 1
}
#[must_use]
pub const fn half(self) -> u64 {
self.modulus() >> 1
}
#[must_use]
pub const fn reduce(self, value: u64) -> u64 {
value & self.mask()
}
#[must_use]
pub const fn add(self, a: u64, n: u64) -> u64 {
self.reduce(a.wrapping_add(n))
}
#[must_use]
pub const fn add_signed(self, a: u64, delta: i64) -> u64 {
self.reduce(a.wrapping_add_signed(delta))
}
#[must_use]
pub const fn forward(self, from: u64, to: u64) -> u64 {
self.reduce(to.wrapping_sub(from))
}
#[must_use]
pub const fn signed(self, from: u64, to: u64) -> i64 {
let forward = self.forward(from, to);
if forward <= self.half() {
forward.cast_signed()
} else {
(forward.wrapping_sub(self.modulus())).cast_signed()
}
}
#[must_use]
pub const fn is_tie(self, a: u64, b: u64) -> bool {
self.forward(b, a) == self.half()
}
#[must_use]
pub const fn lt(self, a: u64, b: u64) -> bool {
self.signed(b, a) < 0
}
#[must_use]
pub const fn leq(self, a: u64, b: u64) -> bool {
self.signed(b, a) <= 0
}
#[must_use]
pub const fn gt(self, a: u64, b: u64) -> bool {
self.signed(b, a) > 0 && !self.is_tie(a, b)
}
#[must_use]
pub const fn geq(self, a: u64, b: u64) -> bool {
self.signed(b, a) >= 0 && !self.is_tie(a, b)
}
#[must_use]
pub const fn in_closed_range(self, value: u64, first: u64, last: u64) -> bool {
let span = self.signed(first, last);
if span < 0 {
return false;
}
let offset = self.signed(first, value);
offset >= 0 && offset <= span
}
#[must_use]
pub const fn extend_near(self, reference: i64, raw: u64) -> Option<i64> {
reference.checked_add(self.signed(reference.cast_unsigned(), raw))
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct Unwrapper {
modulus: Modulus,
last: Option<(u64, i128)>,
}
impl Unwrapper {
#[must_use]
pub const fn new(modulus: Modulus) -> Self {
Self {
modulus,
last: None,
}
}
#[must_use]
pub const fn seeded(modulus: Modulus, origin: i128) -> Self {
Self {
modulus,
last: Some((origin.cast_unsigned() as u64, origin)),
}
}
#[must_use]
pub const fn modulus(&self) -> Modulus {
self.modulus
}
#[must_use]
pub const fn position(&self) -> Option<i128> {
match self.last {
Some((_, position)) => Some(position),
None => None,
}
}
pub fn unwrap(&mut self, raw: u64) -> i128 {
let position = match self.last {
Some((previous_raw, previous)) => {
previous + i128::from(self.modulus.signed(previous_raw, raw))
}
None => i128::from(raw),
};
self.last = Some((raw, position));
position
}
}
#[cfg(test)]
mod tests {
use super::*;
const S16: Modulus = Modulus::new::<16>();
const S32: Modulus = Modulus::new::<32>();
const S33: Modulus = Modulus::new::<33>();
#[test]
fn widths_outside_the_range_are_refused_at_runtime() {
assert_eq!(Modulus::try_new(0), None);
assert_eq!(Modulus::try_new(64), None);
assert_eq!(Modulus::try_new(1), Some(Modulus::new::<1>()));
assert_eq!(Modulus::try_new(63), Some(Modulus::new::<63>()));
assert_eq!(Modulus::new::<63>().modulus(), 1 << 63);
assert_eq!(S16.mask(), 0xFFFF);
assert_eq!(S16.half(), 0x8000);
}
#[test]
fn forward_and_signed_cross_the_wrap() {
assert_eq!(S16.forward(0xFFFF, 0), 1);
assert_eq!(S16.forward(0, 0xFFFF), 0xFFFF);
assert_eq!(S16.signed(0xFFFF, 0), 1);
assert_eq!(S16.signed(0, 0xFFFF), -1);
assert_eq!(S16.signed(5, 5), 0);
assert_eq!(S32.signed(u64::from(u32::MAX) - 9, 5), 15);
assert_eq!(S33.signed(5, (1 << 33) - 10), -15);
}
#[test]
fn the_half_space_tie_resolves_forward_and_orders_nothing() {
assert_eq!(S16.signed(0, 0x8000), 0x8000);
assert_eq!(S16.signed(0x8000, 0), 0x8000);
assert!(S16.is_tie(0, 0x8000));
for (a, b) in [(0, 0x8000), (0x8000, 0)] {
assert!(!S16.lt(a, b));
assert!(!S16.gt(a, b));
assert!(!S16.leq(a, b));
assert!(!S16.geq(a, b));
}
assert_eq!(S16.signed(0, 0x8001), -0x7FFF);
assert_eq!(S16.signed(0, 0x7FFF), 0x7FFF);
}
#[test]
fn ordering_predicates_follow_the_shorter_direction() {
assert!(S16.lt(0xFFFF, 0));
assert!(S16.gt(0, 0xFFFF));
assert!(S16.leq(3, 3));
assert!(S16.geq(3, 3));
assert!(S16.in_closed_range(0, 0xFFFE, 2));
assert!(!S16.in_closed_range(3, 0xFFFE, 2));
assert!(!S16.in_closed_range(0, 2, 0xFFFE));
}
#[test]
fn inputs_are_reduced_and_addition_wraps() {
assert_eq!(S16.reduce(0x1_0005), 5);
assert_eq!(S16.add(0xFFFF, 1), 0);
assert_eq!(S16.add(u64::MAX, 1), 0);
assert_eq!(S16.add_signed(5, -10), 0xFFFB);
assert_eq!(S16.add_signed(0, i64::MIN), 0);
assert_eq!(S33.add_signed(5, -10), (1 << 33) - 5);
assert_eq!(S16.forward(0x1_0000, 0x2_0001), 1);
}
#[test]
fn extend_near_picks_the_closest_congruent_value() {
assert_eq!(S32.extend_near(0x1_0000_0005, 3), Some(0x1_0000_0003));
assert_eq!(S32.extend_near(0x1_FFFF_FFFE, 2), Some(0x2_0000_0002));
assert_eq!(S32.extend_near(2, u64::from(u32::MAX)), Some(-1));
assert_eq!(
S32.extend_near(i64::MAX, u64::from(u32::MAX)),
Some(i64::MAX)
);
assert_eq!(S32.extend_near(i64::MAX, 0), None);
assert_eq!(S32.extend_near(i64::MIN, u64::from(u32::MAX)), None);
}
#[test]
fn the_unwrapper_carries_a_counter_across_its_wraps_in_both_directions() {
let mut u = Unwrapper::new(S16);
assert_eq!(u.unwrap(0xFFFE), 0xFFFE);
assert_eq!(u.unwrap(1), 0x1_0001);
assert_eq!(u.unwrap(0xFFFF), 0xFFFF);
assert_eq!(u.unwrap(0x7FFF), 0x1_7FFF);
assert_eq!(Unwrapper::new(S16).position(), None);
assert_eq!(u.position(), Some(0x1_7FFF));
let mut seeded = Unwrapper::seeded(S33, (1 << 33) + 10);
assert_eq!(seeded.position(), Some((1 << 33) + 10));
assert_eq!(seeded.unwrap(5), (1 << 33) + 5);
assert_eq!(seeded.modulus(), S33);
let mut back = Unwrapper::new(S33);
assert_eq!(back.unwrap(2), 2);
assert_eq!(back.unwrap((1 << 33) - 3), -3);
}
#[test]
fn the_32_bit_unwrap_table_holds_for_every_edge() {
const CASES: [(&[u32], &[i128]); 6] = [
(
&[0xFFFF_F000, 0xFFFF_FBB8, 0x0000_0770],
&[0xFFFF_F000, 0xFFFF_FBB8, 0x1_0000_0770],
),
(&[0x9000_0000], &[0x9000_0000]),
(&[0x0001_0000, 0x0000_F448], &[0x1_0000, 0xF448]),
(&[0, 0x8000_0000], &[0, 0x8000_0000]),
(&[1000, 0xFFFF_F000], &[1000, -4096]),
(&[0xFFFF_F000, 1000], &[0xFFFF_F000, 0x1_0000_03E8]),
];
for (raws, expected) in CASES {
let mut unwrapper = Unwrapper::new(S32);
let got: alloc::vec::Vec<i128> = raws
.iter()
.map(|&raw| unwrapper.unwrap(u64::from(raw)))
.collect();
assert_eq!(got, expected, "{raws:x?}");
}
}
}