Convert principal to Vec 29 bytes length

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