sp1_primitives/
types.rs

1use serde::{de::DeserializeOwned, Deserialize, Serialize};
2
3#[derive(Debug, Clone, Copy)]
4pub enum RecursionProgramType {
5    Core,
6    Deferred,
7    Compress,
8    Shrink,
9    Wrap,
10}
11
12/// A buffer of serializable/deserializable objects.                                              
13#[derive(Debug, Clone, Serialize, Deserialize)]
14pub struct Buffer {
15    pub data: Vec<u8>,
16    #[serde(skip)]
17    pub ptr: usize,
18}
19
20impl Buffer {
21    pub const fn new() -> Self {
22        Self { data: Vec::new(), ptr: 0 }
23    }
24
25    pub fn from(data: &[u8]) -> Self {
26        Self { data: data.to_vec(), ptr: 0 }
27    }
28
29    /// Set the position ptr to the beginning of the buffer.                                      
30    pub fn head(&mut self) {
31        self.ptr = 0;
32    }
33
34    /// Read the serializable object from the buffer.                                             
35    pub fn read<T: Serialize + DeserializeOwned>(&mut self) -> T {
36        let result: T =
37            bincode::deserialize(&self.data[self.ptr..]).expect("failed to deserialize");
38        let nb_bytes = bincode::serialized_size(&result).expect("failed to get serialized size");
39        self.ptr += nb_bytes as usize;
40        result
41    }
42
43    pub fn read_slice(&mut self, slice: &mut [u8]) {
44        slice.copy_from_slice(&self.data[self.ptr..self.ptr + slice.len()]);
45        self.ptr += slice.len();
46    }
47
48    /// Write the serializable object from the buffer.                                            
49    pub fn write<T: Serialize>(&mut self, data: &T) {
50        let mut tmp = Vec::new();
51        bincode::serialize_into(&mut tmp, data).expect("serialization failed");
52        self.data.extend(tmp);
53    }
54
55    /// Write the slice of bytes to the buffer.                                                   
56    pub fn write_slice(&mut self, slice: &[u8]) {
57        self.data.extend_from_slice(slice);
58    }
59}
60
61impl Default for Buffer {
62    fn default() -> Self {
63        Self::new()
64    }
65}