1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
//! Implementation of modular arithmetic algorithms for all integer types in an
//! overflow-safe and const-compatible manner.

#![no_std]
#![warn(missing_docs)]

use core::ops::{Add, BitAnd, Neg, Rem, Shr, Sub};
use num_traits::{one, CheckedAdd, One};

/// Represents an integer with an associated modulus.
#[derive(Clone, Copy, PartialEq, Eq)]
pub struct Modular<T: Clone + Eq + Rem<Output = T>> {
    /// The integer.
    pub value: T,

    /// The modulus.
    pub modulus: T,
}

impl<T: CheckedAdd + Clone + Eq + Rem<Output = T> + Shr<Output = T> + BitAnd<Output = T> + One>
    Modular<T>
{
    fn try_add(self, rhs: Self) -> Option<Self> {
        if self.modulus != rhs.modulus {
            None
        } else {
            Some(match self.value.checked_add(&rhs.value) {
                Some(r) => Self {
                    value: r % self.modulus.clone(),
                    modulus: self.modulus,
                },
                None => Self {
                    value: (((self.value.clone() >> one()) + (rhs.value.clone() >> one()))
                        % self.modulus.clone()
                        + ((self.value & one()) + (rhs.value & one())) % self.modulus.clone())
                        % self.modulus.clone(),
                    modulus: self.modulus,
                },
            })
        }
    }

    fn try_sub(self, rhs: Self) -> Option<Self>
    where
        T: Sub<Output = T>,
    {
        self.try_add(-rhs)
    }
}

impl<T: Clone + Eq + Rem<Output = T> + Sub<Output = T> + One> Neg for Modular<T> {
    type Output = Self;

    fn neg(self) -> Self::Output {
        Self {
            value: self.modulus.clone() - self.value - one(),
            modulus: self.modulus,
        }
    }
}

impl<T: CheckedAdd + Clone + Eq + Rem<Output = T> + Shr<Output = T> + BitAnd<Output = T> + One> Add
    for Modular<T>
{
    type Output = Modular<<T as Add>::Output>;

    fn add(self, rhs: Self) -> Self::Output {
        self.try_add(rhs)
            .expect("operands do not have the same modulus!")
    }
}

impl<
        T: CheckedAdd
            + Clone
            + Eq
            + Rem<Output = T>
            + Sub<Output = T>
            + Shr<Output = T>
            + BitAnd<Output = T>
            + One,
    > Sub for Modular<T>
{
    type Output = Modular<<T as Add>::Output>;

    fn sub(self, rhs: Self) -> Self::Output {
        self.try_sub(rhs)
            .expect("operands do not have the same modulus!")
    }
}

/// Represents an integer with a statically specified modulus.
pub struct StaticModular<T: Clone + Eq + Rem<Output = T> + One + From<usize>, const M: usize>(T);

impl<
        T: CheckedAdd
            + Clone
            + Eq
            + Rem<Output = T>
            + Shr<Output = T>
            + BitAnd<Output = T>
            + One
            + From<usize>,
        const M: usize,
    > Add for StaticModular<T, M>
{
    type Output = StaticModular<<T as Add>::Output, M>;

    fn add(self, rhs: Self) -> Self::Output {
        Self(
            Modular {
                value: self.0,
                modulus: M.into(),
            }
            .try_add(Modular {
                value: rhs.0,
                modulus: M.into(),
            })
            .unwrap()
            .value,
        )
    }
}

impl<T: Clone + Eq + From<usize> + Rem<Output = T> + One, const M: usize> From<T>
    for StaticModular<T, M>
{
    fn from(value: T) -> Self {
        Self(value % M.into())
    }
}