casper_contract/contract_api/
mod.rs

1//! Contains support for writing smart contracts.
2
3pub mod account;
4pub mod cryptography;
5pub mod entity;
6pub mod runtime;
7pub mod storage;
8pub mod system;
9
10use alloc::{
11    alloc::{alloc, Layout},
12    vec::Vec,
13};
14use core::{mem, ptr::NonNull};
15
16use casper_types::{bytesrepr::ToBytes, ApiError};
17
18use crate::unwrap_or_revert::UnwrapOrRevert;
19
20/// Calculates size and alignment for an array of T.
21const fn size_align_for_array<T>(n: usize) -> (usize, usize) {
22    (n * size_of::<T>(), mem::align_of::<T>())
23}
24
25/// Allocates bytes
26pub fn alloc_bytes(n: usize) -> NonNull<u8> {
27    let (size, align) = size_align_for_array::<u8>(n);
28    // We treat allocated memory as raw bytes, that will be later passed to deserializer which also
29    // operates on raw bytes.
30    let layout = Layout::from_size_align(size, align)
31        .map_err(|_| ApiError::AllocLayout)
32        .unwrap_or_revert();
33    let raw_ptr = unsafe { alloc(layout) };
34    NonNull::new(raw_ptr)
35        .ok_or(ApiError::OutOfMemory)
36        .unwrap_or_revert()
37}
38
39fn to_ptr<T: ToBytes>(t: T) -> (*const u8, usize, Vec<u8>) {
40    let bytes = t.into_bytes().unwrap_or_revert();
41    let ptr = bytes.as_ptr();
42    let size = bytes.len();
43    (ptr, size, bytes)
44}
45
46fn dictionary_item_key_to_ptr(dictionary_item_key: &str) -> (*const u8, usize) {
47    let bytes = dictionary_item_key.as_bytes();
48    let ptr = bytes.as_ptr();
49    let size = bytes.len();
50    (ptr, size)
51}