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
//! Various utilities that help interfacing with wasm runtime code.
19

            
20
/// Pack a pointer and length into an `u64`.
21
pub fn pack_ptr_and_len(ptr: u32, len: u32) -> u64 {
22
	// The static assertions from above are changed into a runtime check.
23
	#[cfg(all(not(feature = "std"), feature = "disable_target_static_assertions"))]
24
	assert_eq!(4, core::mem::size_of::<usize>());
25

            
26
	(u64::from(len) << 32) | u64::from(ptr)
27
}
28

            
29
/// Unpacks an `u64` into the pointer and length.
30
///
31
/// Runtime API functions return a 64-bit value which encodes a pointer in the least-significant
32
/// 32-bits and a length in the most-significant 32 bits. This interprets the returned value as a
33
/// pointer, length tuple.
34
pub fn unpack_ptr_and_len(val: u64) -> (u32, u32) {
35
	// The static assertions from above are changed into a runtime check.
36
	#[cfg(all(not(feature = "std"), feature = "disable_target_static_assertions"))]
37
	assert_eq!(4, core::mem::size_of::<usize>());
38

            
39
	let ptr = (val & (!0u32 as u64)) as u32;
40
	let len = (val >> 32) as u32;
41

            
42
	(ptr, len)
43
}
44

            
45
#[cfg(test)]
46
mod tests {
47
	use super::{pack_ptr_and_len, unpack_ptr_and_len};
48

            
49
	#[test]
50
	fn ptr_len_packing_unpacking() {
51
		const PTR: u32 = 0x1337;
52
		const LEN: u32 = 0x7f000000;
53

            
54
		let packed = pack_ptr_and_len(PTR, LEN);
55
		let (ptr, len) = unpack_ptr_and_len(packed);
56

            
57
		assert_eq!(PTR, ptr);
58
		assert_eq!(LEN, len);
59
	}
60
}