]> git.lizzy.rs Git - rust.git/commitdiff
Closer similarities.
authorGiles Cope <gilescope@gmail.com>
Mon, 8 Mar 2021 22:35:37 +0000 (22:35 +0000)
committerGiles Cope <gilescope@gmail.com>
Mon, 8 Mar 2021 22:35:37 +0000 (22:35 +0000)
library/alloc/src/string.rs

index 7292ebdaeec4909aafea9253703f61ce54914bfc..8b0f3047a0a8b8f23e0b1ec1d4d86b89c209dad2 100644 (file)
@@ -2228,18 +2228,18 @@ fn to_string(&self) -> String {
 impl ToString for u8 {
     #[inline]
     fn to_string(&self) -> String {
-        let mut result = String::with_capacity(3);
+        let mut buf = String::with_capacity(3);
         let mut n = *self;
-        if n >= 100 {
-            result.push((b'0' + n / 100) as char);
-            n %= 100;
-        }
-        if !result.is_empty() || n >= 10 {
-            result.push((b'0' + n / 10) as char);
+        if n >= 10 {
+            if n >= 100 {
+                buf.push((b'0' + n / 100) as char);
+                n %= 100;
+            }
+            buf.push((b'0' + n / 10) as char);
             n %= 10;
-        };
-        result.push((b'0' + n) as char);
-        result
+        }
+        buf.push((b'0' + n) as char);
+        buf
     }
 }
 
@@ -2247,31 +2247,21 @@ fn to_string(&self) -> String {
 impl ToString for i8 {
     #[inline]
     fn to_string(&self) -> String {
-        let mut vec = vec![0; 4];
-        let mut free = 0;
+        let mut buf = String::with_capacity(4);
         if self.is_negative() {
-            vec[free] = b'-';
-            free += 1;
+            buf.push('-');
         }
         let mut n = self.unsigned_abs();
         if n >= 10 {
             if n >= 100 {
+                buf.push('1');
                 n -= 100;
-                vec[free] = b'1';
-                free += 1;
             }
-            debug_assert!(n < 100);
-            vec[free] = b'0' + n / 10;
-            free += 1;
+            buf.push((b'0' + n / 10) as char);
             n %= 10;
         }
-        debug_assert!(n < 10);
-        vec[free] = b'0' + n;
-        free += 1;
-        vec.truncate(free);
-
-        // SAFETY: Vec only contains ascii so valid utf8
-        unsafe { String::from_utf8_unchecked(vec) }
+        buf.push((b'0' + n) as char);
+        buf
     }
 }