feat: remove zeroed vector by pushing front

This commit is contained in:
Chris Hyunhum Cho 2024-08-23 07:46:47 -07:00 committed by GitHub
parent b4bda00141
commit a050618fd8
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 13 additions and 6 deletions

View File

@ -69,7 +69,7 @@ static BASE58_DIGITS: [Option<u8>; 128] = [
/// Decodes a base58-encoded string into a byte vector. /// Decodes a base58-encoded string into a byte vector.
pub fn decode(data: &str) -> Result<Vec<u8>, InvalidCharacterError> { pub fn decode(data: &str) -> Result<Vec<u8>, InvalidCharacterError> {
// 11/15 is just over log_256(58) // 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 // Build in base 256
for d58 in data.bytes() { for d58 in data.bytes() {
// Compute "X = X * 58 + next_digit" in base 256 // Compute "X = X * 58 + next_digit" in base 256
@ -82,10 +82,17 @@ pub fn decode(data: &str) -> Result<Vec<u8>, InvalidCharacterError> {
return Err(InvalidCharacterError { invalid: d58 }); return Err(InvalidCharacterError { invalid: d58 });
} }
}; };
for d256 in scratch.iter_mut().rev() { if scratch.is_empty() {
carry += u32::from(*d256) * 58; for _ in 0..scratch.capacity() {
*d256 = carry as u8; // cast loses data intentionally scratch.push(carry as u8);
carry /= 256; 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); assert_eq!(carry, 0);
} }
@ -93,7 +100,7 @@ pub fn decode(data: &str) -> Result<Vec<u8>, InvalidCharacterError> {
// Copy leading zeroes directly // Copy leading zeroes directly
let mut ret: Vec<u8> = data.bytes().take_while(|&x| x == BASE58_CHARS[0]).map(|_| 0).collect(); let mut ret: Vec<u8> = data.bytes().take_while(|&x| x == BASE58_CHARS[0]).map(|_| 0).collect();
// Copy rest of string // 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) Ok(ret)
} }