gp_wasm_interface/
memory_wrapper.rs

1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: Apache-2.0
5
6// Licensed under the Apache License, Version 2.0 (the "License");
7// you may not use this file except in compliance with the License.
8// You may obtain a copy of the License at
9//
10// 	http://www.apache.org/licenses/LICENSE-2.0
11//
12// Unless required by applicable law or agreed to in writing, software
13// distributed under the License is distributed on an "AS IS" BASIS,
14// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15// See the License for the specific language governing permissions and
16// limitations under the License.
17
18/// Wrapper around [`Memory`] that implements [`sp_allocator::Memory`].
19pub struct MemoryWrapper<'a, C>(&'a wasmtime::Memory, &'a mut C);
20
21impl<'a, C> From<(&'a wasmtime::Memory, &'a mut C)> for MemoryWrapper<'a, C> {
22    fn from((memory, caller): (&'a wasmtime::Memory, &'a mut C)) -> Self {
23        Self(memory, caller)
24    }
25}
26
27impl<C: wasmtime::AsContextMut> sp_allocator::Memory for MemoryWrapper<'_, C> {
28	fn with_access<R>(&self, run: impl FnOnce(&[u8]) -> R) -> R {
29		run(self.0.data(&self.1))
30	}
31
32	fn with_access_mut<R>(&mut self, run: impl FnOnce(&mut [u8]) -> R) -> R {
33		run(self.0.data_mut(&mut self.1))
34	}
35
36	fn grow(&mut self, additional: u32) -> std::result::Result<(), ()> {
37		self.0
38			.grow(&mut self.1, additional as u64)
39			.map_err(|e| {
40				log::error!(
41					"Failed to grow memory by {} pages: {}",
42					additional,
43					e,
44				)
45			})
46			.map(drop)
47	}
48
49	fn pages(&self) -> u32 {
50		self.0.size(&self.1) as u32
51	}
52
53	fn max_pages(&self) -> Option<u32> {
54		self.0.ty(&self.1).maximum().map(|p| p as _)
55	}
56}