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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
//! 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>> {
    value: T,
    modulus: T,
}

impl<T: Clone + Eq + Rem<Output = T>> Modular<T> {
    /// Constructs a new modular arithmetic integer.
    pub fn new(value: T, modulus: T) -> Self {
        Self {
            value: value % modulus.clone(),
            modulus,
        }
    }

    /// Gets the value of the integer.
    pub fn value(&self) -> &T {
        &self.value
    }

    /// Gets the modulus of the integer.
    pub fn modulus(&self) -> &T {
        &self.modulus
    }

    /// Splits the integer into its value and modulus.
    pub fn into_parts(self) -> (T, T) {
        (self.value, self.modulus)
    }
}

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: Clone + Eq + Rem<Output = T> + One + From<usize>, const M: usize> StaticModular<T, M> {
    /// Constructs a new modular integer.
    pub fn new(value: T) -> Self {
        Self(value % M.into())
    }

    /// Gets the value of the integer.
    pub fn value(&self) -> &T {
        &self.0
    }

    /// Consumes the integer, producing its value.
    pub fn into_value(self) -> T {
        self.0
    }

    /// Consumes the integer, producing an equivalent [`Modular`] value.
    pub fn into_dynamic(self) -> Modular<T> {
        Modular {
            value: self.0,
            modulus: M.into(),
        }
    }
}

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(
            self.into_dynamic()
                .try_add(rhs.into_dynamic())
                .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::new(value)
    }
}