gsp_allocator/lib.rs
1// Copyright (C) Parity Technologies (UK) Ltd.
2// SPDX-License-Identifier: Apache-2.0
3
4// See `README.md` for the upstream source and license reference.
5
6//! Collection of allocator implementations.
7//!
8//! This crate provides the following allocator implementations:
9//! - A freeing-bump allocator: [`FreeingBumpHeapAllocator`]
10
11#![cfg_attr(not(feature = "std"), no_std)]
12#![warn(missing_docs)]
13
14#[cfg(feature = "std")]
15mod error;
16#[cfg(feature = "std")]
17mod freeing_bump;
18
19#[cfg(feature = "std")]
20pub use error::Error;
21#[cfg(feature = "std")]
22pub use freeing_bump::{AllocationStats, FreeingBumpHeapAllocator};
23
24/// The size of one wasm page in bytes.
25///
26/// The wasm memory is divided into pages, meaning the minimum size of a memory is one page.
27#[cfg(feature = "std")]
28const PAGE_SIZE: u32 = 65536;
29
30/// The maximum number of wasm pages that can be allocated.
31///
32/// 4GiB / [`PAGE_SIZE`].
33#[cfg(feature = "std")]
34const MAX_WASM_PAGES: u32 = (4u64 * 1024 * 1024 * 1024 / PAGE_SIZE as u64) as u32;
35
36/// Grants access to the memory for the allocator.
37///
38/// Memory of wasm is allocated in pages. A page has a constant size of 64KiB. The maximum allowed
39/// memory size as defined in the wasm specification is 4GiB (65536 pages).
40pub trait Memory {
41 /// Run the given closure `run` and grant it write access to the raw memory.
42 fn with_access_mut<R>(&mut self, run: impl FnOnce(&mut [u8]) -> R) -> R;
43 /// Run the given closure `run` and grant it read access to the raw memory.
44 fn with_access<R>(&self, run: impl FnOnce(&[u8]) -> R) -> R;
45 /// Grow the memory by `additional` pages.
46 #[allow(clippy::result_unit_err)]
47 fn grow(&mut self, additional: u32) -> Result<(), ()>;
48 /// Returns the current number of pages this memory has allocated.
49 fn pages(&self) -> u32;
50 /// Returns the maximum number of pages this memory is allowed to allocate.
51 ///
52 /// The returned number needs to be smaller or equal to `65536`. The returned number needs to be
53 /// bigger or equal to [`Self::pages`].
54 ///
55 /// If `None` is returned, there is no maximum (besides the maximum defined in the wasm spec).
56 fn max_pages(&self) -> Option<u32>;
57}
58
59/// The maximum number of bytes that can be allocated at one time.
60// The maximum possible allocation size was chosen rather arbitrary, 32 MiB should be enough for
61// everybody.
62// 2^25 bytes, 32 MiB
63pub const MAX_POSSIBLE_ALLOCATION: u32 = 33_554_432;