Noob Rust question, how do you convert a Principal to a vector of bytes of exactly 29 bytes regardless if shorter or not?
my_principal.as_slice() gives me a [u8] but it can be shorter than the MAX_LENGTH_IN_BYTES and I would like to have exactly that max length for serialization purpose. For example pre-pending it with zero.
Prepending with zeros doesn’t work cause the principal might start with a zero (as far as I know there is no rule that says a principal can’t start with a zero).
Since the max principal bytes length is 29, we can fit the serialization into 30 bytes. First byte is for the length.
pub fn principal_as_thirty_bytes(p: &Principal) -> [u8; 30] {
let mut bytes: [u8; 30] = [0; 30];
let p_bytes: &[u8] = p.as_slice();
bytes[0] = p_bytes.len() as u8;
bytes[1 .. p_bytes.len() + 1].copy_from_slice(p_bytes);
bytes
}
pub fn thirty_bytes_as_principal(bytes: &[u8; 30]) -> Principal {
Principal::from_slice(&bytes[1..1 + bytes[0] as usize])
}