spl_pod/
bytemuck.rs

1//! wrappers for `bytemuck` functions
2
3use {bytemuck::Pod, solana_program_error::ProgramError};
4
5/// On-chain size of a `Pod` type
6pub const fn pod_get_packed_len<T: Pod>() -> usize {
7    std::mem::size_of::<T>()
8}
9
10/// Convert a `Pod` into a slice of bytes (zero copy)
11pub fn pod_bytes_of<T: Pod>(t: &T) -> &[u8] {
12    bytemuck::bytes_of(t)
13}
14
15/// Convert a slice of bytes into a `Pod` (zero copy)
16pub fn pod_from_bytes<T: Pod>(bytes: &[u8]) -> Result<&T, ProgramError> {
17    bytemuck::try_from_bytes(bytes).map_err(|_| ProgramError::InvalidArgument)
18}
19
20/// Maybe convert a slice of bytes into a `Pod` (zero copy)
21///
22/// Returns `None` if the slice is empty, or else `Err` if input length is not
23/// equal to `pod_get_packed_len::<T>()`.
24/// This function exists primarily because `Option<T>` is not a `Pod`.
25pub fn pod_maybe_from_bytes<T: Pod>(bytes: &[u8]) -> Result<Option<&T>, ProgramError> {
26    if bytes.is_empty() {
27        Ok(None)
28    } else {
29        bytemuck::try_from_bytes(bytes)
30            .map(Some)
31            .map_err(|_| ProgramError::InvalidArgument)
32    }
33}
34
35/// Convert a slice of bytes into a mutable `Pod` (zero copy)
36pub fn pod_from_bytes_mut<T: Pod>(bytes: &mut [u8]) -> Result<&mut T, ProgramError> {
37    bytemuck::try_from_bytes_mut(bytes).map_err(|_| ProgramError::InvalidArgument)
38}
39
40/// Convert a slice of bytes into a `Pod` slice (zero copy)
41pub fn pod_slice_from_bytes<T: Pod>(bytes: &[u8]) -> Result<&[T], ProgramError> {
42    bytemuck::try_cast_slice(bytes).map_err(|_| ProgramError::InvalidArgument)
43}
44
45/// Convert a slice of bytes into a mutable `Pod` slice (zero copy)
46pub fn pod_slice_from_bytes_mut<T: Pod>(bytes: &mut [u8]) -> Result<&mut [T], ProgramError> {
47    bytemuck::try_cast_slice_mut(bytes).map_err(|_| ProgramError::InvalidArgument)
48}
49
50/// Convert a `Pod` slice into a single slice of bytes
51pub fn pod_slice_to_bytes<T: Pod>(slice: &[T]) -> &[u8] {
52    bytemuck::cast_slice(slice)
53}