gp_wasm_interface/
host_state.rs

1// This file is part of Substrate.
2
3// Copyright (C) 2019-2022 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//! This module defines `HostState` struct which provide logic and state
19//! required for execution of host.
20
21use sp_allocator::{AllocationStats, FreeingBumpHeapAllocator};
22
23/// The state required to construct a HostContext context. The context only lasts for one host
24/// call, whereas the state is maintained for the duration of a Wasm runtime call, which may make
25/// many different host calls that must share state.
26pub struct HostState {
27	/// The allocator instance to keep track of allocated memory.
28	///
29	/// This is stored as an `Option` as we need to temporarly set this to `None` when we are
30	/// allocating/deallocating memory. The problem being that we can only mutable access `caller`
31	/// once.
32	pub allocator: Option<FreeingBumpHeapAllocator>,
33	pub panic_message: Option<String>,
34}
35
36impl HostState {
37	/// Constructs a new `HostState`.
38	pub fn new(allocator: FreeingBumpHeapAllocator) -> Self {
39		HostState { allocator: Some(allocator), panic_message: None }
40	}
41
42	/// Takes the error message out of the host state, leaving a `None` in its place.
43	pub fn take_panic_message(&mut self) -> Option<String> {
44		self.panic_message.take()
45	}
46
47	pub fn allocation_stats(&self) -> AllocationStats {
48		self.allocator.as_ref()
49			.expect("Allocator is always set and only unavailable when doing an allocation/deallocation; qed")
50			.stats()
51	}
52}