Merge rust-bitcoin/rust-bitcoin#3120: base58: Remove or document casts

4b66a479b0 base58: Use u32 instead of usize (Tobin C. Harding)
3f8cf1b335 base58: Use from and document cast (Tobin C. Harding)
121b435a9b base58: Use from to cast u8 (Tobin C. Harding)

Pull request description:

  Done as part of #2941.

  Remove or document casts in the `base58` crate. Two separate patches because to assist review, with the hope that reviewers are able to just read the diff without going to the crate's code.

ACKs for top commit:
  Kixunil:
    ACK 4b66a479b0
  apoelstra:
    ACK 4b66a479b0 successfully ran local tests

Tree-SHA512: e120e844af6e41eb29cc1538a9bad21a4e3ea8b27b90b7221a09eb5112093c72248ba3d72cd91d950ea8420032cb2e66790c24f9e15af7f2c0554f6cac3854c0
This commit is contained in:
merge-script 2024-08-07 02:12:24 +00:00
commit 000661360e
No known key found for this signature in database
GPG Key ID: C588D63CE41B97C1
1 changed files with 10 additions and 10 deletions

View File

@ -73,18 +73,18 @@ pub fn decode(data: &str) -> Result<Vec<u8>, InvalidCharacterError> {
// Build in base 256
for d58 in data.bytes() {
// Compute "X = X * 58 + next_digit" in base 256
if d58 as usize >= BASE58_DIGITS.len() {
if usize::from(d58) >= BASE58_DIGITS.len() {
return Err(InvalidCharacterError { invalid: d58 });
}
let mut carry = match BASE58_DIGITS[d58 as usize] {
Some(d58) => d58 as u32,
let mut carry = match BASE58_DIGITS[usize::from(d58)] {
Some(d58) => u32::from(d58),
None => {
return Err(InvalidCharacterError { invalid: d58 });
}
};
for d256 in scratch.iter_mut().rev() {
carry += *d256 as u32 * 58;
*d256 = carry as u8;
carry += u32::from(*d256) * 58;
*d256 = carry as u8; // cast loses data intentionally
carry /= 256;
}
assert_eq!(carry, 0);
@ -208,7 +208,7 @@ where
let mut leading_zeroes = true;
// Build string in little endian with 0-58 in place of characters...
for d256 in data {
let mut carry = d256 as usize;
let mut carry = u32::from(d256);
if leading_zeroes && carry == 0 {
leading_zero_count += 1;
} else {
@ -216,13 +216,13 @@ where
}
for ch in buf.slice_mut() {
let new_ch = *ch as usize * 256 + carry;
*ch = (new_ch % 58) as u8;
let new_ch = u32::from(*ch) * 256 + carry;
*ch = (new_ch % 58) as u8; // cast loses data intentionally
carry = new_ch / 58;
}
while carry > 0 {
buf.push((carry % 58) as u8);
buf.push((carry % 58) as u8); // cast loses data intentionally
carry /= 58;
}
}
@ -233,7 +233,7 @@ where
}
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(())