rialo_s_serialize_utils/
lib.rs1#![allow(clippy::arithmetic_side_effects)]
4#![allow(clippy::ptr_as_ptr)]
5use rialo_s_pubkey::Pubkey;
6use rialo_sanitize::SanitizeError;
7
8pub mod cursor;
9
10pub fn append_u16(buf: &mut Vec<u8>, data: u16) {
11 let start = buf.len();
12 buf.resize(buf.len() + 2, 0);
13 let end = buf.len();
14 buf[start..end].copy_from_slice(&data.to_le_bytes());
15}
16
17pub fn append_u8(buf: &mut Vec<u8>, data: u8) {
18 let start = buf.len();
19 buf.resize(buf.len() + 1, 0);
20 buf[start] = data;
21}
22
23pub fn append_slice(buf: &mut Vec<u8>, data: &[u8]) {
24 let start = buf.len();
25 buf.resize(buf.len() + data.len(), 0);
26 let end = buf.len();
27 buf[start..end].copy_from_slice(data);
28}
29
30pub fn read_u8(current: &mut usize, data: &[u8]) -> Result<u8, SanitizeError> {
31 if data.len() < *current + 1 {
32 return Err(SanitizeError::IndexOutOfBounds);
33 }
34 let e = data[*current];
35 *current += 1;
36 Ok(e)
37}
38
39pub fn read_pubkey(current: &mut usize, data: &[u8]) -> Result<Pubkey, SanitizeError> {
40 let len = std::mem::size_of::<Pubkey>();
41 if data.len() < *current + len {
42 return Err(SanitizeError::IndexOutOfBounds);
43 }
44 let e = Pubkey::try_from(&data[*current..*current + len])
45 .map_err(|_| SanitizeError::ValueOutOfBounds)?;
46 *current += len;
47 Ok(e)
48}
49
50pub fn read_u16(current: &mut usize, data: &[u8]) -> Result<u16, SanitizeError> {
51 if data.len() < *current + 2 {
52 return Err(SanitizeError::IndexOutOfBounds);
53 }
54 let mut fixed_data = [0u8; 2];
55 fixed_data.copy_from_slice(&data[*current..*current + 2]);
56 let e = u16::from_le_bytes(fixed_data);
57 *current += 2;
58 Ok(e)
59}
60
61pub fn read_slice(
62 current: &mut usize,
63 data: &[u8],
64 data_len: usize,
65) -> Result<Vec<u8>, SanitizeError> {
66 if data.len() < *current + data_len {
67 return Err(SanitizeError::IndexOutOfBounds);
68 }
69 let e = data[*current..*current + data_len].to_vec();
70 *current += data_len;
71 Ok(e)
72}