solana_program_pack/
lib.rs1use solana_program_error::ProgramError;
10
11pub trait IsInitialized {
13 fn is_initialized(&self) -> bool;
15}
16
17pub trait Sealed: Sized {}
19
20pub trait Pack: Sealed {
22 const LEN: usize;
24 #[doc(hidden)]
25 fn pack_into_slice(&self, dst: &mut [u8]);
26 #[doc(hidden)]
27 fn unpack_from_slice(src: &[u8]) -> Result<Self, ProgramError>;
28
29 fn get_packed_len() -> usize {
31 Self::LEN
32 }
33
34 fn unpack(input: &[u8]) -> Result<Self, ProgramError>
36 where
37 Self: IsInitialized,
38 {
39 let value = Self::unpack_unchecked(input)?;
40 if value.is_initialized() {
41 Ok(value)
42 } else {
43 Err(ProgramError::UninitializedAccount)
44 }
45 }
46
47 fn unpack_unchecked(input: &[u8]) -> Result<Self, ProgramError> {
49 if input.len() != Self::LEN {
50 return Err(ProgramError::InvalidAccountData);
51 }
52 Self::unpack_from_slice(input)
53 }
54
55 fn pack(src: Self, dst: &mut [u8]) -> Result<(), ProgramError> {
57 if dst.len() != Self::LEN {
58 return Err(ProgramError::InvalidAccountData);
59 }
60 src.pack_into_slice(dst);
61 Ok(())
62 }
63}