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