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