Skip to content

Commit

Permalink
Inv implementation for Decimal (#495)
Browse files Browse the repository at this point in the history
Fixes #494

Co-authored-by: Manuel Bärenz <m.baerenz@sonnen.de>
  • Loading branch information
turion and Manuel Bärenz committed Mar 17, 2022
1 parent 2d43258 commit 4b97ec4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 5 deletions.
17 changes: 13 additions & 4 deletions src/arithmetic_impls.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@

use crate::{decimal::CalculationResult, ops, Decimal};
use core::ops::{Add, Div, Mul, Rem, Sub};
use num_traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedRem, CheckedSub};
use num_traits::{CheckedAdd, CheckedDiv, CheckedMul, CheckedRem, CheckedSub, Inv};

// Macros and `Decimal` implementations

Expand Down Expand Up @@ -32,10 +32,10 @@ macro_rules! impl_checked {
macro_rules! impl_saturating {
($long:literal, $short:literal, $fun:ident, $impl:ident, $cmp:ident) => {
#[doc = concat!(
"Saturating ",
$long,
"Saturating ",
$long,
". Computes `self ",
$short,
$short,
" other`, saturating at the relevant upper or lower boundary.",
)]
#[inline(always)]
Expand Down Expand Up @@ -198,6 +198,15 @@ impl CheckedRem for Decimal {
}
}

impl Inv for Decimal {
type Output = Self;

#[inline]
fn inv(self) -> Self {
Decimal::ONE / self
}
}

forward_all_binop!(impl Div for Decimal, div);
impl<'a, 'b> Div<&'b Decimal> for &'a Decimal {
type Output = Decimal;
Expand Down
7 changes: 6 additions & 1 deletion tests/decimal_tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ use core::{
convert::{TryFrom, TryInto},
str::FromStr,
};
use num_traits::{Signed, ToPrimitive};
use num_traits::{Inv, Signed, ToPrimitive};
use rust_decimal::{Decimal, Error, RoundingStrategy};

#[test]
Expand Down Expand Up @@ -3366,6 +3366,11 @@ fn test_constants() {
assert_eq!("2", Decimal::TWO.to_string());
}

#[test]
fn test_inv() {
assert_eq!("0.01", Decimal::ONE_HUNDRED.inv().to_string());
}

// Mathematical features
#[cfg(feature = "maths")]
mod maths {
Expand Down

0 comments on commit 4b97ec4

Please sign in to comment.