I need to convert the first 8 bytes of a String in Rust to a u64, big endian. This code almost works:
fn main() {
let s = String::from("01234567");
let mut buf = [0u8; 8];
buf.copy_from_slice(s.as_bytes());
let num = u64::from_be_bytes(buf);
println!("{:X}", num);
}
There are multiple problems with this code. First, it only works if the string is exactly 8 bytes long. .copy_from_slice() requires that both source and destination have the same length. This is easy to deal with if the String is too long because I can just grab a slice of the right length, but if the String is short it won't work.
Another problem is that this code is part of a function which is very performance sensitive. It runs in a tight loop over a large data set.
In C, I would just zero the buf, memcpy over the right number of bytes, and do a cast to an unsigned long.
Is there some way to do this in Rust which runs just as fast?