Home > Enterprise >  How to imply a specific number of bytes to a string slice
How to imply a specific number of bytes to a string slice

Time:07-14

Might seem like a dumb question, however, I've been trying to restrict a string slice (that comes as parameter to a function) to a number of bytes.

This is what I've tried

fn padd_address(addr: &str) -> Result<web3::types::H256, std::error::Error> {
  if addr.strip_prefix("0x").unwrap().as_bytes().len() > std::mem::size_of::<[u8; 20]>() {
    std::error::Error()
  }

  let padded = &format!("0x{}", format!("{:0>64}", addr))[..];
  H256::from_str(padded).unwrap()
}

Now assume I have an address like this let addr = "0xdAC17F958D2ee523a2206206994597C13D831ec7";. The function will firstly, strip 0x prefix and after will compute the nb of bytes associated with the string.

Now if I were to println!("{:?}", addr.strip_prefix("0x").unwrap().as_bytes().len()) I get 40 bytes in return instead of 20 which is the actual size of a contract address.

Any thoughts how I can check whether the string that comes as parameter, i.e addr has 20 bytes only?

CodePudding user response:

I get 40 bytes in return instead of 20 which is the actual size of a contract address.

No, your address is

dAC17F958D2ee523a2206206994597C13D831ec7

which is in fact 40 bytes. as_bytes() simply returns the bytes data underlying the string, so it returns

b"dAC17F958D2ee523a2206206994597C13D831ec7"

it does not decode anything. Which incidentally makes it useless syntactic overhead as it's literally what str::len does.

If you want the underlying value, you need something like the hex crate to decode your address from hexadecimal to binary (or hand-roll the same decoding), at which point you will have 20 bytes of data.

  • Related