| 1 |
//! Implement division |
| 2 |
|
| 3 |
use super::*; |
| 4 |
|
| 5 |
impl Div<BigDecimal> for BigDecimal { |
| 6 |
type Output = BigDecimal; |
| 7 |
#[inline] |
| 8 |
fn div(self, other: BigDecimal) -> BigDecimal { |
| 9 |
if other.is_zero() { |
| 10 |
panic!("Division by zero"); |
| 11 |
} |
| 12 |
if self.is_zero() || other.is_one_quickcheck() == Some(true) { |
| 13 |
return self; |
| 14 |
} |
| 15 |
|
| 16 |
let scale = self.scale - other.scale; |
| 17 |
|
| 18 |
if self.int_val == other.int_val { |
| 19 |
return BigDecimal { |
| 20 |
int_val: 1.into(), |
| 21 |
scale: scale, |
| 22 |
}; |
| 23 |
} |
| 24 |
|
| 25 |
let max_precision = DEFAULT_PRECISION; |
| 26 |
|
| 27 |
return impl_division(self.int_val, &other.int_val, scale, max_precision); |
| 28 |
} |
| 29 |
} |
| 30 |
|
| 31 |
impl<'a> Div<&'a BigDecimal> for BigDecimal { |
| 32 |
type Output = BigDecimal; |
| 33 |
#[inline] |
| 34 |
fn div(self, other: &'a BigDecimal) -> BigDecimal { |
| 35 |
if other.is_zero() { |
| 36 |
panic!("Division by zero"); |
| 37 |
} |
| 38 |
if self.is_zero() || other.is_one_quickcheck() == Some(true) { |
| 39 |
return self; |
| 40 |
} |
| 41 |
|
| 42 |
let scale = self.scale - other.scale; |
| 43 |
|
| 44 |
if self.int_val == other.int_val { |
| 45 |
return BigDecimal { |
| 46 |
int_val: 1.into(), |
| 47 |
scale: scale, |
| 48 |
}; |
| 49 |
} |
| 50 |
|
| 51 |
let max_precision = DEFAULT_PRECISION; |
| 52 |
|
| 53 |
return impl_division(self.int_val, &other.int_val, scale, max_precision); |
| 54 |
} |
| 55 |
} |
| 56 |
|
| 57 |
forward_ref_val_binop!(impl Div for BigDecimal, div); |
| 58 |
|
| 59 |
impl Div<&BigDecimal> for &BigDecimal { |
| 60 |
type Output = BigDecimal; |
| 61 |
|
| 62 |
#[inline] |
| 63 |
fn div(self, other: &BigDecimal) -> BigDecimal { |
| 64 |
if other.is_zero() { |
| 65 |
panic!("Division by zero"); |
| 66 |
} |
| 67 |
// TODO: Fix setting scale |
| 68 |
if self.is_zero() || other.is_one_quickcheck() == Some(true) { |
| 69 |
return self.clone(); |
| 70 |
} |
| 71 |
|
| 72 |
let scale = self.scale - other.scale; |
| 73 |
|
| 74 |
let num_int = &self.int_val; |
| 75 |
let den_int = &other.int_val; |
| 76 |
|
| 77 |
if num_int == den_int { |
| 78 |
return BigDecimal { |
| 79 |
int_val: 1.into(), |
| 80 |
scale: scale, |
| 81 |
}; |
| 82 |
} |
| 83 |
|
| 84 |
let max_precision = DEFAULT_PRECISION; |
| 85 |
|
| 86 |
return impl_division(num_int.clone(), den_int, scale, max_precision); |
| 87 |
} |
| 88 |
} |
| 89 |
|
| 90 |
// tests in lib.tests.ops.div.rs |