Serialization converts data structures to bytes. This is fundamental for Solana where all account data is stored as bytes!
Solana accounts store data as raw bytes (&[u8]). You need to serialize (write) and deserialize (read) your data structures.
Byte order matters when converting multi-byte values:
let num: u32 = 0x12345678;
// Little-endian (Solana uses this)
// [0x78, 0x56, 0x34, 0x12]
// Big-endian
// [0x12, 0x34, 0x56, 0x78]let n: u64 = 1000;
// To bytes (little-endian)
let bytes: [u8; 8] = n.to_le_bytes();
// From bytes
let restored = u64::from_le_bytes(bytes);struct Transfer {
amount: u64,
recipient: [u8; 4],
}
impl Transfer {
fn to_bytes(&self) -> [u8; 12] {
let mut bytes = [0u8; 12];
// Copy amount (8 bytes, little-endian)
bytes[0..8].copy_from_slice(&self.amount.to_le_bytes());
// Copy recipient (4 bytes)
bytes[8..12].copy_from_slice(&self.recipient);
bytes
}
fn from_bytes(data: &[u8; 12]) -> Self {
let amount = u64::from_le_bytes(data[0..8].try_into().unwrap());
let mut recipient = [0u8; 4];
recipient.copy_from_slice(&data[8..12]);
Self { amount, recipient }
}
}Implement to_bytes() and from_bytes() for the Transfer struct.
fn to_bytes(&self) -> [u8; 12] {
let mut bytes = [0u8; 12];
bytes[0..8].copy_from_slice(&self.amount.to_le_bytes());
bytes[8..12].copy_from_slice(&self.recipient);
bytes
}
fn from_bytes(data: &[u8; 12]) -> Self {
let amount = u64::from_le_bytes(data[0..8].try_into().unwrap());
let mut recipient = [0u8; 4];
recipient.copy_from_slice(&data[8..12]);
Self { amount, recipient }
}