sc_executor_common/util.rs
1// This file is part of Substrate.
2
3// Copyright (C) Parity Technologies (UK) Ltd.
4// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
5
6// This program is free software: you can redistribute it and/or modify
7// it under the terms of the GNU General Public License as published by
8// the Free Software Foundation, either version 3 of the License, or
9// (at your option) any later version.
10
11// This program is distributed in the hope that it will be useful,
12// but WITHOUT ANY WARRANTY; without even the implied warranty of
13// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14// GNU General Public License for more details.
15
16// You should have received a copy of the GNU General Public License
17// along with this program. If not, see <https://www.gnu.org/licenses/>.
18
19//! Utilities used by all backends
20
21use crate::error::Result;
22use sp_wasm_interface::Pointer;
23use std::ops::Range;
24
25/// Construct a range from an offset to a data length after the offset.
26/// Returns None if the end of the range would exceed some maximum offset.
27pub fn checked_range(offset: usize, len: usize, max: usize) -> Option<Range<usize>> {
28 let end = offset.checked_add(len)?;
29 (end <= max).then(|| offset..end)
30}
31
32/// Provides safe memory access interface using an external buffer
33pub trait MemoryTransfer {
34 /// Read data from a slice of memory into a newly allocated buffer.
35 ///
36 /// Returns an error if the read would go out of the memory bounds.
37 fn read(&self, source_addr: Pointer<u8>, size: usize) -> Result<Vec<u8>>;
38
39 /// Read data from a slice of memory into a destination buffer.
40 ///
41 /// Returns an error if the read would go out of the memory bounds.
42 fn read_into(&self, source_addr: Pointer<u8>, destination: &mut [u8]) -> Result<()>;
43
44 /// Write data to a slice of memory.
45 ///
46 /// Returns an error if the write would go out of the memory bounds.
47 fn write_from(&self, dest_addr: Pointer<u8>, source: &[u8]) -> Result<()>;
48}