Skip to content

Commit 37e223c

Browse files
committed
dec2flt: Refactor the fast path
This is just a bit of code cleanup to make use of returning early.
1 parent 19a909a commit 37e223c

File tree

1 file changed

+23
-24
lines changed

1 file changed

+23
-24
lines changed

library/core/src/num/dec2flt/decimal.rs

+23-24
Original file line numberDiff line numberDiff line change
@@ -34,14 +34,15 @@ pub struct Decimal {
3434
impl Decimal {
3535
/// Detect if the float can be accurately reconstructed from native floats.
3636
#[inline]
37-
fn is_fast_path<F: RawFloat>(&self) -> bool {
37+
fn can_use_fast_path<F: RawFloat>(&self) -> bool {
3838
F::MIN_EXPONENT_FAST_PATH <= self.exponent
3939
&& self.exponent <= F::MAX_EXPONENT_DISGUISED_FAST_PATH
4040
&& self.mantissa <= F::MAX_MANTISSA_FAST_PATH
4141
&& !self.many_digits
4242
}
4343

44-
/// The fast path algorithm using machine-sized integers and floats.
44+
/// Try turning the decimal into an exact float representation, using machine-sized integers
45+
/// and floats.
4546
///
4647
/// This is extracted into a separate function so that it can be attempted before constructing
4748
/// a Decimal. This only works if both the mantissa and the exponent
@@ -59,30 +60,28 @@ impl Decimal {
5960
// require setting it by changing the global state (like the control word of the x87 FPU).
6061
let _cw = set_precision::<F>();
6162

62-
if self.is_fast_path::<F>() {
63-
let mut value = if self.exponent <= F::MAX_EXPONENT_FAST_PATH {
64-
// normal fast path
65-
let value = F::from_u64(self.mantissa);
66-
if self.exponent < 0 {
67-
value / F::pow10_fast_path((-self.exponent) as _)
68-
} else {
69-
value * F::pow10_fast_path(self.exponent as _)
70-
}
63+
if !self.can_use_fast_path::<F>() {
64+
return None;
65+
}
66+
67+
let value = if self.exponent <= F::MAX_EXPONENT_FAST_PATH {
68+
// normal fast path
69+
let value = F::from_u64(self.mantissa);
70+
if self.exponent < 0 {
71+
value / F::pow10_fast_path((-self.exponent) as _)
7172
} else {
72-
// disguised fast path
73-
let shift = self.exponent - F::MAX_EXPONENT_FAST_PATH;
74-
let mantissa = self.mantissa.checked_mul(INT_POW10[shift as usize])?;
75-
if mantissa > F::MAX_MANTISSA_FAST_PATH {
76-
return None;
77-
}
78-
F::from_u64(mantissa) * F::pow10_fast_path(F::MAX_EXPONENT_FAST_PATH as _)
79-
};
80-
if self.negative {
81-
value = -value;
73+
value * F::pow10_fast_path(self.exponent as _)
8274
}
83-
Some(value)
8475
} else {
85-
None
86-
}
76+
// disguised fast path
77+
let shift = self.exponent - F::MAX_EXPONENT_FAST_PATH;
78+
let mantissa = self.mantissa.checked_mul(INT_POW10[shift as usize])?;
79+
if mantissa > F::MAX_MANTISSA_FAST_PATH {
80+
return None;
81+
}
82+
F::from_u64(mantissa) * F::pow10_fast_path(F::MAX_EXPONENT_FAST_PATH as _)
83+
};
84+
85+
if self.negative { Some(-value) } else { Some(value) }
8786
}
8887
}

0 commit comments

Comments
 (0)