Convert principal to Vec 29 bytes length

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.

You will need to save the length of the bytes accompanied.

Principal::from_slice(&[1]) and Principal::from_slice(&[0,1]) are two different Principals.

To your original question, you can create an mutable vector with 29 zeros and copy the Principal slice into desired part of the vector.

1 Like

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])
} 
3 Likes

Thanks a tone for your answers!!! Exactly what I was looking for :pray:.