soil_client/executor/common/util.rs
1// This file is part of Soil.
2
3// Copyright (C) Soil contributors.
4// Copyright (C) Parity Technologies (UK) Ltd.
5// SPDX-License-Identifier: GPL-3.0-or-later WITH Classpath-exception-2.0
6
7//! Utilities used by all backends
8
9use super::error::Result;
10use std::ops::Range;
11use subsoil::wasm_interface::Pointer;
12
13/// Construct a range from an offset to a data length after the offset.
14/// Returns None if the end of the range would exceed some maximum offset.
15pub fn checked_range(offset: usize, len: usize, max: usize) -> Option<Range<usize>> {
16 let end = offset.checked_add(len)?;
17 (end <= max).then(|| offset..end)
18}
19
20/// Provides safe memory access interface using an external buffer
21pub trait MemoryTransfer {
22 /// Read data from a slice of memory into a newly allocated buffer.
23 ///
24 /// Returns an error if the read would go out of the memory bounds.
25 fn read(&self, source_addr: Pointer<u8>, size: usize) -> Result<Vec<u8>>;
26
27 /// Read data from a slice of memory into a destination buffer.
28 ///
29 /// Returns an error if the read would go out of the memory bounds.
30 fn read_into(&self, source_addr: Pointer<u8>, destination: &mut [u8]) -> Result<()>;
31
32 /// Write data to a slice of memory.
33 ///
34 /// Returns an error if the write would go out of the memory bounds.
35 fn write_from(&self, dest_addr: Pointer<u8>, source: &[u8]) -> Result<()>;
36}