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