swamp_script_code_gen/
constants.rs1use swamp_vm_types::aligner::align;
2use swamp_vm_types::{ConstantMemoryAddress, MemoryAlignment, MemorySize};
3
4const ALIGNMENT_MASK: usize = 0x7;
5
6pub struct ConstantsAllocator {
7 current_addr: u32,
8}
9
10impl Default for ConstantsAllocator {
11 fn default() -> Self {
12 Self::new()
13 }
14}
15
16impl ConstantsAllocator {
17 #[must_use]
18 pub const fn new() -> Self {
19 Self { current_addr: 0 }
20 }
21
22 pub fn allocate(
23 &mut self,
24 size: MemorySize,
25 alignment_enum: MemoryAlignment,
26 ) -> ConstantMemoryAddress {
27 let alignment: usize = alignment_enum.into();
28 let start_addr = align(self.current_addr as usize, alignment) as u32;
29
30 self.current_addr = start_addr + size.0 as u32;
31
32 ConstantMemoryAddress(start_addr)
33 }
34
35 pub fn reset(&mut self) {
36 self.current_addr = 0;
37 }
38}
39
40pub struct ConstantsManager {
41 allocator: ConstantsAllocator,
42 data: Vec<u8>,
43}
44
45impl Default for ConstantsManager {
46 fn default() -> Self {
47 Self::new()
48 }
49}
50
51impl ConstantsManager {
52 #[must_use]
53 pub fn new() -> Self {
54 Self {
55 allocator: ConstantsAllocator::new(),
56 data: vec![0u8; 1024 * 1024],
57 }
58 }
59
60 pub fn allocate(
61 &mut self,
62 data: &[u8],
63 alignment_enum: MemoryAlignment,
64 ) -> ConstantMemoryAddress {
65 let addr = self
66 .allocator
67 .allocate(MemorySize(data.len() as u16), alignment_enum);
68
69 let start_idx = addr.0 as usize;
70 self.data[start_idx..start_idx + data.len()].copy_from_slice(data);
71
72 ConstantMemoryAddress(addr.0)
73 }
74
75 pub fn take_data(self) -> Vec<u8> {
76 self.data
77 }
78}