From 0636253f068942a3ca8a5a64f2df4db1c887a859 Mon Sep 17 00:00:00 2001 From: kirbylife Date: Thu, 27 Apr 2023 23:37:49 -0600 Subject: [PATCH] Improve the write_u32 method --- src/screen.rs | 41 +++++++++++++---------------------------- 1 file changed, 13 insertions(+), 28 deletions(-) diff --git a/src/screen.rs b/src/screen.rs index 802fc63..961ccf4 100644 --- a/src/screen.rs +++ b/src/screen.rs @@ -158,37 +158,22 @@ impl< self.write_str(core::str::from_utf8(&buff[..=num_len]).unwrap()); } - pub fn write_u32(&mut self, num: u32) { - // This function is for debugging purposes only, it does not show - // The 0's to the right of the number - // The max number in an u32 is: 4,294,967,295 - let mut buff = [0; 10]; - let len = num_chars(num, &mut buff); - self.write_str(&core::str::from_utf8(&buff[..len]).unwrap()); + pub fn write_u32(&mut self, mut num: u32) { + if num == 0 { + self.write_char('0'); + return; + } + + let mut buff = [0u8; 10]; + let num_len = num.ilog10() as usize; + for i in (0..=num_len).rev() { + buff[i] = (num % 10) as u8 + '0' as u8; + num /= 10; + } + self.write_str(core::str::from_utf8(&buff[..=num_len]).unwrap()); } } fn last_bit(n: u8) -> bool { (n & 1) != 0 } - -fn num_rev(mut num: u32) -> u32 { - let mut rev_num = 0; - while num > 0 { - let digit = num % 10; - rev_num = rev_num * 10 + digit; - num /= 10; - } - rev_num -} - -fn num_chars(n: u32, output: &mut [u8]) -> usize { - let mut n = num_rev(n); - let mut i = 0; - while n > 0 { - output[i] = (n % 10) as u8 + '0' as u8; - n = n / 10; - i += 1; - } - i -}