From a050618fd87323cc284b04826ae78911a2f32d80 Mon Sep 17 00:00:00 2001 From: Chris Hyunhum Cho Date: Fri, 23 Aug 2024 07:46:47 -0700 Subject: [PATCH 1/2] feat: remove zeroed vector by pushing front --- base58/src/lib.rs | 19 +++++++++++++------ 1 file changed, 13 insertions(+), 6 deletions(-) diff --git a/base58/src/lib.rs b/base58/src/lib.rs index 7e0f15239..881d5d0f6 100644 --- a/base58/src/lib.rs +++ b/base58/src/lib.rs @@ -69,7 +69,7 @@ static BASE58_DIGITS: [Option; 128] = [ /// Decodes a base58-encoded string into a byte vector. pub fn decode(data: &str) -> Result, InvalidCharacterError> { // 11/15 is just over log_256(58) - let mut scratch = vec![0u8; 1 + data.len() * 11 / 15]; + let mut scratch = Vec::with_capacity(1 + data.len() * 11 / 15); // Build in base 256 for d58 in data.bytes() { // Compute "X = X * 58 + next_digit" in base 256 @@ -82,10 +82,17 @@ pub fn decode(data: &str) -> Result, InvalidCharacterError> { return Err(InvalidCharacterError { invalid: d58 }); } }; - for d256 in scratch.iter_mut().rev() { - carry += u32::from(*d256) * 58; - *d256 = carry as u8; // cast loses data intentionally - carry /= 256; + if scratch.is_empty() { + for _ in 0..scratch.capacity() { + scratch.push(carry as u8); + carry /= 256; + } + } else { + for d256 in scratch.iter_mut() { + carry += u32::from(*d256) * 58; + *d256 = carry as u8; // cast loses data intentionally + carry /= 256; + } } assert_eq!(carry, 0); } @@ -93,7 +100,7 @@ pub fn decode(data: &str) -> Result, InvalidCharacterError> { // Copy leading zeroes directly let mut ret: Vec = data.bytes().take_while(|&x| x == BASE58_CHARS[0]).map(|_| 0).collect(); // Copy rest of string - ret.extend(scratch.into_iter().skip_while(|&x| x == 0)); + ret.extend(scratch.into_iter().rev().skip_while(|&x| x == 0)); Ok(ret) } From 441aac0a087254fdd56fc744b937f9d16d59583f Mon Sep 17 00:00:00 2001 From: Chris Hyunhum Cho Date: Mon, 26 Aug 2024 04:44:01 -0700 Subject: [PATCH 2/2] fix: vec! macro enabled only for test module --- base58/src/lib.rs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/base58/src/lib.rs b/base58/src/lib.rs index 881d5d0f6..ffda3179e 100644 --- a/base58/src/lib.rs +++ b/base58/src/lib.rs @@ -18,7 +18,6 @@ #![allow(clippy::needless_question_mark)] // https://github.com/rust-bitcoin/rust-bitcoin/pull/2134 #![allow(clippy::manual_range_contains)] // More readable than clippy's format. -#[macro_use] extern crate alloc; #[cfg(bench)] @@ -248,6 +247,7 @@ where #[cfg(test)] mod tests { + use alloc::vec; use hex::test_hex_unwrap as hex; use super::*;