Skip to content

Commit 8b6d1ca

Browse files
nth root - improved precondition check
1 parent 0df3c96 commit 8b6d1ca

File tree

2 files changed

+12
-2
lines changed

2 files changed

+12
-2
lines changed

framework/base/src/types/managed/wrapped/managed_decimal.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -17,7 +17,8 @@ pub use managed_decimal_signed::ManagedDecimalSigned;
1717

1818
use crate::{
1919
abi::{TypeAbi, TypeAbiFrom, TypeName},
20-
api::{ManagedTypeApi, ManagedTypeApiImpl},
20+
api::{ManagedTypeApi, ManagedTypeApiImpl, quick_signal_error},
21+
err_msg,
2122
formatter::{FormatBuffer, FormatByteReceiver, SCDisplay},
2223
typenum::{U4, U8, Unsigned},
2324
types::BigUint,
@@ -156,6 +157,10 @@ impl<M: ManagedTypeApi, D: Decimals + Clone> ManagedDecimal<M, D> {
156157
/// # Panics
157158
/// Panics if `k` is zero.
158159
pub fn nth_root(&self, k: u32) -> Self {
160+
if k == 0 {
161+
quick_signal_error::<M>(err_msg::BIG_UINT_NTH_ROOT_ZERO);
162+
}
163+
159164
if k == 1 {
160165
return self.clone();
161166
}
@@ -164,7 +169,7 @@ impl<M: ManagedTypeApi, D: Decimals + Clone> ManagedDecimal<M, D> {
164169
// Multiply by sf^(k-1) before rooting so the decimal position is preserved.
165170
// For k==0, the check in BigUint::nth_root handles the error signal.
166171
let scaled = &self.data * &sf.pow(k.saturating_sub(1));
167-
ManagedDecimal::from_raw_units(scaled.nth_root(k), self.decimals.clone())
172+
ManagedDecimal::from_raw_units(scaled.nth_root_unchecked(k), self.decimals.clone())
168173
}
169174
}
170175

framework/base/src/types/managed/wrapped/num/big_uint.rs

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -364,6 +364,11 @@ impl<M: ManagedTypeApi> BigUint<M> {
364364
return self.clone();
365365
}
366366

367+
self.nth_root_unchecked(k)
368+
}
369+
370+
// Expects k > 1. Does not check this precondition, so it is the caller's responsibility to ensure it.
371+
pub(crate) fn nth_root_unchecked(&self, k: u32) -> Self {
367372
// log2 is None for the number zero,
368373
// but in this case we can return early with the correct result of zero without doing any computation
369374
let Some(log2) = self.log2_floor() else {

0 commit comments

Comments
 (0)