about summary refs log tree commit diff
diff options
context:
space:
mode:
authorAndrea Canciani <ranma42@gmail.com>2015-12-30 22:03:35 +0100
committerAndrea Canciani <ranma42@gmail.com>2016-01-28 15:13:43 +0100
commit7b33d39da93a9873fa002c6875c934fd13ec7d4a (patch)
tree930104bc16eb179b14bc4553465656ca79ba6d31
parent2fd2670ea0a55b7f7481c5ce2a95c5c5033941d5 (diff)
downloadrust-7b33d39da93a9873fa002c6875c934fd13ec7d4a.tar.gz
rust-7b33d39da93a9873fa002c6875c934fd13ec7d4a.zip
Improve computation of `EscapeUnicode` offset field
Instead of iteratively scanning the bits, use `leading_zeros`.
-rw-r--r--src/libcore/char.rs12
1 files changed, 7 insertions, 5 deletions
diff --git a/src/libcore/char.rs b/src/libcore/char.rs
index df6044fa839..1df2d0d3bc8 100644
--- a/src/libcore/char.rs
+++ b/src/libcore/char.rs
@@ -299,14 +299,16 @@ impl CharExt for char {
 
     #[inline]
     fn escape_unicode(self) -> EscapeUnicode {
-        let mut n = 0;
-        while (self as u32) >> (4 * (n + 1)) != 0 {
-            n += 1;
-        }
+        let c = self as u32;
+        // or-ing 1 ensures that for c==0 the code computes that one
+        // digit should be printed and (which is the same) avoids the
+        // (31 - 32) underflow
+        let msb = 31 - (c | 1).leading_zeros();
+        let msdigit = msb / 4;
         EscapeUnicode {
             c: self,
             state: EscapeUnicodeState::Backslash,
-            offset: n,
+            offset: msdigit as usize,
         }
     }