Skip to content

Commit 68f0b47

Browse files
committed
isqrt: remove duplication by delegating to unsigned integers
1 parent 1b34f1c commit 68f0b47

File tree

2 files changed

+12
-40
lines changed

2 files changed

+12
-40
lines changed

library/core/src/num/int_macros.rs

Lines changed: 11 additions & 39 deletions
Original file line numberDiff line numberDiff line change
@@ -915,26 +915,10 @@ macro_rules! int_impl {
915915
#[inline]
916916
pub const fn checked_isqrt(self) -> Option<Self> {
917917
if self < 0 {
918-
return None;
919-
} else if self < 2 {
920-
return Some(self);
921-
}
922-
923-
let mut x: Self = self;
924-
let mut c: Self = 0;
925-
let mut d: Self = 1 << (self.ilog2() & !1);
926-
927-
while (d != 0) {
928-
if x >= c + d {
929-
x -= c + d;
930-
c = (c >> 1) + d;
931-
} else {
932-
c >>= 1;
933-
}
934-
d >>= 2;
918+
None
919+
} else {
920+
Some((self as $UnsignedT).isqrt() as Self)
935921
}
936-
937-
return Some(c);
938922
}
939923

940924
/// Saturating integer addition. Computes `self + rhs`, saturating at the numeric
@@ -2118,27 +2102,15 @@ macro_rules! int_impl {
21182102
without modifying the original"]
21192103
#[inline]
21202104
pub const fn isqrt(self) -> Self {
2121-
if self < 0 {
2122-
panic!("argument of integer square root must be non-negative")
2123-
} else if self < 2 {
2124-
return self;
2125-
}
2126-
2127-
let mut x: Self = self;
2128-
let mut c: Self = 0;
2129-
let mut d: Self = 1 << (self.ilog2() & !1);
2130-
2131-
while (d != 0) {
2132-
if x >= c + d {
2133-
x -= c + d;
2134-
c = (c >> 1) + d;
2135-
} else {
2136-
c >>= 1;
2137-
}
2138-
d >>= 2;
2105+
// I would like to implement it as
2106+
// ```
2107+
// self.checked_isqrt().expect("argument of integer square root must be non-negative")
2108+
// ```
2109+
// but `expect` is not yet stable as a `const fn`.
2110+
match self.checked_isqrt() {
2111+
Some(sqrt) => sqrt,
2112+
None => panic!("argument of integer square root must be non-negative"),
21392113
}
2140-
2141-
return c;
21422114
}
21432115

21442116
/// Calculates the quotient of Euclidean division of `self` by `rhs`.

library/core/src/num/uint_macros.rs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2011,7 +2011,7 @@ macro_rules! uint_impl {
20112011
d >>= 2;
20122012
}
20132013

2014-
return c;
2014+
c
20152015
}
20162016

20172017
/// Performs Euclidean division.

0 commit comments

Comments
 (0)