@@ -7,7 +7,7 @@ use std::ops::{Add, AddAssign, Div, DivAssign, Mul, MulAssign, Sub, SubAssign};
77use std:: str:: FromStr ;
88use thiserror:: Error ;
99
10- use crate :: errors:: { CheckedMultiplyRatioError , StdError } ;
10+ use crate :: errors:: { CheckedFromRatioError , StdError } ;
1111use crate :: { OverflowError , Uint512 } ;
1212
1313use super :: Fraction ;
@@ -132,28 +132,31 @@ impl Decimal256 {
132132 pub fn from_ratio ( numerator : impl Into < Uint256 > , denominator : impl Into < Uint256 > ) -> Self {
133133 match Decimal256 :: checked_from_ratio ( numerator, denominator) {
134134 Ok ( value) => value,
135- Err ( CheckedMultiplyRatioError :: DivideByZero ) => {
135+ Err ( CheckedFromRatioError :: DivideByZero ) => {
136136 panic ! ( "Denominator must not be zero" )
137137 }
138- Err ( CheckedMultiplyRatioError :: Overflow ) => panic ! ( "Multiplication overflow" ) ,
138+ Err ( CheckedFromRatioError :: MulOverflow ) => panic ! ( "Multiplication overflow" ) ,
139139 }
140140 }
141141
142142 /// Returns the ratio (numerator / denominator) as a Decimal256
143143 pub fn checked_from_ratio (
144144 numerator : impl Into < Uint256 > ,
145145 denominator : impl Into < Uint256 > ,
146- ) -> Result < Self , CheckedMultiplyRatioError > {
146+ ) -> Result < Self , CheckedFromRatioError > {
147147 let numerator: Uint256 = numerator. into ( ) ;
148148 let denominator: Uint256 = denominator. into ( ) ;
149149 if denominator. is_zero ( ) {
150- return Err ( CheckedMultiplyRatioError :: DivideByZero ) ;
150+ return Err ( CheckedFromRatioError :: DivideByZero ) ;
151151 }
152152
153- Ok ( Self (
154- // numerator * DECIMAL_FRACTIONAL / denominator
155- numerator. checked_multiply_ratio ( Self :: DECIMAL_FRACTIONAL , denominator) ?,
156- ) )
153+ match numerator. checked_multiply_ratio ( Self :: DECIMAL_FRACTIONAL , denominator) {
154+ Ok ( ratio) => {
155+ // numerator * DECIMAL_FRACTIONAL / denominator
156+ Ok ( Self ( ratio) )
157+ }
158+ Err ( _) => Err ( CheckedFromRatioError :: MulOverflow ) ,
159+ }
157160 }
158161
159162 pub const fn is_zero ( & self ) -> bool {
@@ -704,16 +707,22 @@ mod tests {
704707 Decimal256 :: from_ratio ( 1u128 , 0u128 ) ;
705708 }
706709
710+ #[ test]
711+ #[ should_panic( expected = "Multiplication overflow" ) ]
712+ fn decimal256_from_ratio_panics_for_mul_overflow ( ) {
713+ Decimal256 :: from_ratio ( Uint256 :: MAX , 1u128 ) ;
714+ }
715+
707716 #[ test]
708717 fn decimal256_checked_from_ratio_does_not_panic ( ) {
709718 assert_eq ! (
710719 Decimal256 :: checked_from_ratio( 1u128 , 0u128 ) ,
711- Err ( CheckedMultiplyRatioError :: DivideByZero )
720+ Err ( CheckedFromRatioError :: DivideByZero )
712721 ) ;
713722
714723 assert_eq ! (
715724 Decimal256 :: checked_from_ratio( Uint256 :: MAX , 1u128 ) ,
716- Err ( CheckedMultiplyRatioError :: Overflow )
725+ Err ( CheckedFromRatioError :: MulOverflow )
717726 ) ;
718727 }
719728
0 commit comments