about summary refs log tree commit diff
diff options
context:
space:
mode:
authorFederico Stra <stra.federico@gmail.com>2023-09-28 12:12:18 +0200
committerFederico Stra <stra.federico@gmail.com>2023-09-28 12:12:18 +0200
commit51463175a46599eb69375861bfe3626f68d643a4 (patch)
treeb5a97c37f1563ac79454004ecbb2dd9205a4747c
parentc97ab231415aa46cd1d35e8d00d601dec0d23e86 (diff)
downloadrust-51463175a46599eb69375861bfe3626f68d643a4.tar.gz
rust-51463175a46599eb69375861bfe3626f68d643a4.zip
isqrt: cite source and rename variables to match original C code
-rw-r--r--library/core/src/num/uint_macros.rs27
1 files changed, 16 insertions, 11 deletions
diff --git a/library/core/src/num/uint_macros.rs b/library/core/src/num/uint_macros.rs
index 5de672d5d7e..371d6e180c2 100644
--- a/library/core/src/num/uint_macros.rs
+++ b/library/core/src/num/uint_macros.rs
@@ -1998,21 +1998,26 @@ macro_rules! uint_impl {
                 return self;
             }
 
-            let mut x = self;
-            let mut c = 0;
-            let mut d = 1 << (self.ilog2() & !1);
-
-            while d != 0 {
-                if x >= c + d {
-                    x -= c + d;
-                    c = (c >> 1) + d;
+            // The algorithm is based on the one presented in
+            // <https://en.wikipedia.org/wiki/Methods_of_computing_square_roots#Binary_numeral_system_(base_2)>
+            // which cites as source the following C code:
+            // <https://web.archive.org/web/20120306040058/http://medialab.freaknet.org/martin/src/sqrt/sqrt.c>.
+
+            let mut op = self;
+            let mut res = 0;
+            let mut one = 1 << (self.ilog2() & !1);
+
+            while one != 0 {
+                if op >= res + one {
+                    op -= res + one;
+                    res = (res >> 1) + one;
                 } else {
-                    c >>= 1;
+                    res >>= 1;
                 }
-                d >>= 2;
+                one >>= 2;
             }
 
-            c
+            res
         }
 
         /// Performs Euclidean division.