1 //! Support for implementing the [`RuntimeLinearMemory`] trait in terms of a 2 //! fixed allocation that cannot move. 3 4 use crate::prelude::*; 5 use crate::runtime::vm::MemoryBase; 6 use crate::runtime::vm::memory::RuntimeLinearMemory; 7 8 /// A "static" memory where the lifetime of the backing memory is managed 9 /// elsewhere. Currently used with the pooling allocator. 10 pub struct StaticMemory { 11 /// The base pointer of this static memory, wrapped up in a send/sync 12 /// wrapper. 13 base: MemoryBase, 14 15 /// The byte capacity of the `base` pointer. 16 capacity: usize, 17 18 /// The current size, in bytes, of this memory. 19 size: usize, 20 } 21 22 impl StaticMemory { new( base: MemoryBase, base_capacity: usize, initial_size: usize, maximum_size: Option<usize>, ) -> Result<Self>23 pub fn new( 24 base: MemoryBase, 25 base_capacity: usize, 26 initial_size: usize, 27 maximum_size: Option<usize>, 28 ) -> Result<Self> { 29 if base_capacity < initial_size { 30 bail!( 31 "initial memory size of {initial_size} exceeds the pooling allocator's \ 32 configured maximum memory size of {base_capacity} bytes", 33 ); 34 } 35 36 // Only use the part of the slice that is necessary. 37 let base_capacity = match maximum_size { 38 Some(max) if max < base_capacity => max, 39 _ => base_capacity, 40 }; 41 42 Ok(Self { 43 base, 44 capacity: base_capacity, 45 size: initial_size, 46 }) 47 } 48 } 49 50 impl RuntimeLinearMemory for StaticMemory { byte_size(&self) -> usize51 fn byte_size(&self) -> usize { 52 self.size 53 } 54 byte_capacity(&self) -> usize55 fn byte_capacity(&self) -> usize { 56 self.capacity 57 } 58 grow_to(&mut self, new_byte_size: usize) -> Result<()>59 fn grow_to(&mut self, new_byte_size: usize) -> Result<()> { 60 // Never exceed the static memory size; this check should have been made 61 // prior to arriving here. 62 assert!(new_byte_size <= self.capacity); 63 64 // Update our accounting of the available size. 65 self.size = new_byte_size; 66 Ok(()) 67 } 68 set_byte_size(&mut self, len: usize)69 fn set_byte_size(&mut self, len: usize) { 70 self.size = len; 71 } 72 base(&self) -> MemoryBase73 fn base(&self) -> MemoryBase { 74 self.base.clone() 75 } 76 vmmemory(&self) -> crate::vm::VMMemoryDefinition77 fn vmmemory(&self) -> crate::vm::VMMemoryDefinition { 78 crate::vm::VMMemoryDefinition { 79 base: self.base.as_non_null().into(), 80 current_length: self.size.into(), 81 } 82 } 83 } 84