hmath/ratio/arith/
sub.rs

1use crate::{BigInt, Ratio};
2
3impl Ratio {
4
5    #[must_use = "method returns a new number and does not mutate the original value"]
6    pub fn sub_rat(&self, other: &Ratio) -> Self {
7        let result = Ratio::from_denom_and_numer(
8            self.denom.mul_bi(&other.denom),
9            self.numer.mul_bi(&other.denom).sub_bi(&other.numer.mul_bi(&self.denom))
10        );
11
12        #[cfg(test)] assert!(result.is_valid());
13
14        result
15    }
16
17    pub fn sub_rat_mut(&mut self, other: &Ratio) {
18        self.numer = self.numer.mul_bi(&other.denom).sub_bi(&other.numer.mul_bi(&self.denom));
19        self.denom.mul_bi_mut(&other.denom);
20
21        self.fit();
22    }
23
24    #[must_use = "method returns a new number and does not mutate the original value"]
25    pub fn sub_bi(&self, other: &BigInt) -> Self {
26
27        // Safety: `self.denom` and `self.numer` are already coprime.
28        let result = Ratio::from_denom_and_numer_raw(
29            self.denom.clone(),
30            self.numer.sub_bi(&self.denom.mul_bi(other))
31        );
32
33        #[cfg(test)] assert!(result.is_valid());
34
35        result
36    }
37
38    pub fn sub_bi_mut(&mut self, other: &BigInt) {
39        self.numer.sub_bi_mut(&self.denom.mul_bi(other));
40        #[cfg(test)] assert!(self.is_valid());
41    }
42
43    #[must_use = "method returns a new number and does not mutate the original value"]
44    pub fn sub_i32(&self, other: i32) -> Self {
45
46        // Safety: `self.denom` and `self.numer` are already coprime.
47        let result = Ratio::from_denom_and_numer_raw(
48            self.denom.clone(),
49            self.numer.sub_bi(&self.denom.mul_i32(other))
50        );
51
52        #[cfg(test)] assert!(result.is_valid());
53
54        result
55    }
56
57    pub fn sub_i32_mut(&mut self, other: i32) {
58        self.numer.sub_bi_mut(&self.denom.mul_i32(other));
59        #[cfg(test)] assert!(self.is_valid());
60    }
61
62}