Skip to content

Commit

Permalink
Add checked_div implementation
Browse files Browse the repository at this point in the history
  • Loading branch information
wojciech-cichocki committed Oct 11, 2023
1 parent 9d4992b commit aee8580
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 1 deletion.
28 changes: 28 additions & 0 deletions decimal_core/src/checked_ops.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,17 @@ pub fn generate_checked_ops(characteristics: DecimalCharacteristics) -> proc_mac
.ok_or_else(|| "checked_sub: (self - rhs) subtraction underflow")?
))
}

fn checked_div(self, rhs: Self) -> std::result::Result<Self, String> {
Ok(Self::new(
self.get()
.checked_mul(Self::one())
.ok_or_else(|| "checked_div: (self * Self::one()) multiplication overflow")?
.checked_div(rhs.get())
.ok_or_else(|| "checked_div: ((self * Self::one()) / rhs) division by zero")?
)
)
}
}

#[cfg(test)]
Expand Down Expand Up @@ -54,6 +65,23 @@ pub fn generate_checked_ops(characteristics: DecimalCharacteristics) -> proc_mac
assert_eq!(a.checked_sub(b), Ok(#struct_name::new(24)));
}

#[test]
fn test_checked_div() {
let a = #struct_name::new(2);
let b = #struct_name::new(#struct_name::one());

assert_eq!(a.checked_div(b), Ok(#struct_name::new(2)));
}

#[test]
fn test_0_checked_div() {
let a = #struct_name::new(47);
let b = #struct_name::new(0);
let result = a.checked_div(b);

assert!(result.is_err());
}

#[test]
fn test_underflow_checked_sub() {
let min = #struct_name::new(0);
Expand Down
2 changes: 1 addition & 1 deletion src/traits.rs
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ pub trait Factories<T>: Sized {
fn from_scale_up(integer: T, scale: u8) -> Self;
}


pub trait BetweenDecimals<T>: Sized {
fn from_decimal(other: T) -> Self;
fn checked_from_decimal(other: T) -> std::result::Result<Self, String>;
Expand Down Expand Up @@ -69,4 +68,5 @@ pub trait ByNumber<B>: Sized {
pub trait CheckedOps: Sized {
fn checked_add(self, rhs: Self) -> std::result::Result<Self, String>;
fn checked_sub(self, rhs: Self) -> std::result::Result<Self, String>;
fn checked_div(self, rhs: Self) -> std::result::Result<Self, String>;
}

0 comments on commit aee8580

Please sign in to comment.