wasmtime/runtime/vm/memory/
static_.rs

1//! Support for implementing the [`RuntimeLinearMemory`] trait in terms of a
2//! fixed allocation that cannot move.
3
4use crate::prelude::*;
5use crate::runtime::vm::memory::RuntimeLinearMemory;
6use crate::runtime::vm::MemoryBase;
7
8/// A "static" memory where the lifetime of the backing memory is managed
9/// elsewhere. Currently used with the pooling allocator.
10pub 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
22impl StaticMemory {
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 {} exceeds the pooling allocator's \
32                 configured maximum memory size of {} bytes",
33                initial_size,
34                base_capacity,
35            );
36        }
37
38        // Only use the part of the slice that is necessary.
39        let base_capacity = match maximum_size {
40            Some(max) if max < base_capacity => max,
41            _ => base_capacity,
42        };
43
44        Ok(Self {
45            base,
46            capacity: base_capacity,
47            size: initial_size,
48        })
49    }
50}
51
52impl RuntimeLinearMemory for StaticMemory {
53    fn byte_size(&self) -> usize {
54        self.size
55    }
56
57    fn byte_capacity(&self) -> usize {
58        self.capacity
59    }
60
61    fn grow_to(&mut self, new_byte_size: usize) -> Result<()> {
62        // Never exceed the static memory size; this check should have been made
63        // prior to arriving here.
64        assert!(new_byte_size <= self.capacity);
65
66        // Update our accounting of the available size.
67        self.size = new_byte_size;
68        Ok(())
69    }
70
71    fn set_byte_size(&mut self, len: usize) {
72        self.size = len;
73    }
74
75    fn base(&self) -> MemoryBase {
76        self.base.clone()
77    }
78}