Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Implement Inv for Decimal #495

Merged
merged 2 commits into from
Mar 17, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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