base58: Use from and document cast

Done in an effort to reduce the cognitive load of reading the loop.

The base68 decode and encode algorithm uses a `u32` intentionally for
multiplication and a cast to `u8` intentionally when carrying.

Use `From` where possible and document the cast.
This commit is contained in:
Tobin C. Harding 2024-08-05 07:08:46 +10:00
parent 121b435a9b
commit 3f8cf1b335
No known key found for this signature in database
GPG Key ID: 40BF9E4C269D6607
1 changed files with 7 additions and 7 deletions

View File

@ -83,8 +83,8 @@ pub fn decode(data: &str) -> Result<Vec<u8>, InvalidCharacterError> {
} }
}; };
for d256 in scratch.iter_mut().rev() { for d256 in scratch.iter_mut().rev() {
carry += *d256 as u32 * 58; carry += u32::from(*d256) * 58;
*d256 = carry as u8; *d256 = carry as u8; // cast loses data intentionally
carry /= 256; carry /= 256;
} }
assert_eq!(carry, 0); assert_eq!(carry, 0);
@ -208,7 +208,7 @@ where
let mut leading_zeroes = true; let mut leading_zeroes = true;
// Build string in little endian with 0-58 in place of characters... // Build string in little endian with 0-58 in place of characters...
for d256 in data { for d256 in data {
let mut carry = d256 as usize; let mut carry = usize::from(d256);
if leading_zeroes && carry == 0 { if leading_zeroes && carry == 0 {
leading_zero_count += 1; leading_zero_count += 1;
} else { } else {
@ -216,13 +216,13 @@ where
} }
for ch in buf.slice_mut() { for ch in buf.slice_mut() {
let new_ch = *ch as usize * 256 + carry; let new_ch = usize::from(*ch) * 256 + carry;
*ch = (new_ch % 58) as u8; *ch = (new_ch % 58) as u8; // cast loses data intentionally
carry = new_ch / 58; carry = new_ch / 58;
} }
while carry > 0 { while carry > 0 {
buf.push((carry % 58) as u8); buf.push((carry % 58) as u8); // cast loses data intentionally
carry /= 58; carry /= 58;
} }
} }
@ -233,7 +233,7 @@ where
} }
for ch in buf.slice().iter().rev() { for ch in buf.slice().iter().rev() {
writer.write_char(BASE58_CHARS[*ch as usize] as char)?; writer.write_char(char::from(BASE58_CHARS[usize::from(*ch)]))?;
} }
Ok(()) Ok(())