Z^m number system in Rust A \$Z^m\$ number system includes integers in the interval \$[0, m)\$ when \$m &gt; 0\$ or \$(m, 0]\$ when \$m &lt; 0\$. The code defines a trait Mod to represent numbers in this system and the +, -, and * operator for it. 

use std::ops::Add;
use std::ops::Mul;
use std::ops::Sub;

struct Mod&lt;T: Modulo&lt;T&gt;&gt; {
    modulo: T,
    i: T,
}

trait Modulo&lt;T&gt; {
    fn modulo(&amp;self, n: T) -&gt; T;
}

impl Modulo&lt;i32&gt; for i32 {
    fn modulo(&amp;self, n: i32) -&gt; i32 {
        let mut x: i32 = *self;
        while x.signum() != n.signum() {
            x += n;
        }
        x % n
    }
}

impl Mod&lt;i32&gt; {
    fn new(modulo: i32, i: i32) -&gt; Mod&lt;i32&gt; {
        let n = i.modulo(modulo);
        Mod {
            modulo: modulo,
            i: n,
        }
    }
}

impl Add for Mod&lt;i32&gt; {
    type Output = Mod&lt;i32&gt;;
    fn add(self, other: Mod&lt;i32&gt;) -&gt; Mod&lt;i32&gt; {
        Mod::new(self.modulo, self.i + other.i)
    }
}

impl Sub for Mod&lt;i32&gt; {
    type Output = Mod&lt;i32&gt;;
    fn sub(self, other: Mod&lt;i32&gt;) -&gt; Mod&lt;i32&gt; {
        Mod::new(self.modulo, self.i - other.i)
    }
}

impl Mul for Mod&lt;i32&gt; {
    type Output = Mod&lt;i32&gt;;
    fn mul(self, other: Mod&lt;i32&gt;) -&gt; Mod&lt;i32&gt; {
        Mod::new(self.modulo, self.i * other.i)
    }
}

fn main() {
    let x = Mod::new(-5, 3);
    let y = Mod::new(-5, 8);
    println!("{}", (x + y).i);
    let x = Mod::new(-5, 3);
    let y = Mod::new(-5, 8);
    println!("{}", (x - y).i);
    let x = Mod::new(-5, 3);
    let y = Mod::new(-5, 8);
    println!("{}", (x * y).i);
}


All suggestions are welcome, but I am particularly interested in:


Extending to u32, u16, u8, i16, i8 etc without too much code duplication.
Increasing performance.
I would hesitate to implement Mod&lt;T&gt; * Mod&lt;T&gt;, and instead implement Mod&lt;T&gt; * T (and vice-versa). This is because you make no attempt to preserve the rhs' modulo, so you probably shouldn't have one there.

Consider the code

let mut x: i32 = *self;
while x.signum() != n.signum() {
    x += n;
}
x % n


That while loop makes this operation \$\mathcal{O}(n)\$, whereas a simpler implementation

((x % n) + n) % n


is \$\mathcal{O}(1)\$.

Performance elsewhere is probably uninteresting, since it devolves to basic integer operations.

Extending to other T should probably be done by being generic over the Mod and Add traits, as well as whatever particular operation is needed to implement. Something like

impl&lt;T&gt; Sub&lt;T&gt; for Mod&lt;T&gt;
    where T: Add&lt;T&gt; + Mod&lt;T&gt; + Sub&lt;T&gt;
{
    type Output = Mod&lt;T&gt;;
    fn sub(self, other: T) -&gt; Mod&lt;T&gt; {
        Mod::new(self.modulo, self.i - i)
    }
}


The Add and Mod are needed by Mod::new, the Sub is needed inside the sub call.