ab_io_type/lib.rs
1#![feature(maybe_uninit_slice, ptr_as_uninit)]
2#![no_std]
3
4pub mod bool;
5pub mod fixed_capacity_bytes;
6pub mod fixed_capacity_string;
7pub mod maybe_data;
8pub mod metadata;
9pub mod trivial_type;
10pub mod unaligned;
11pub mod variable_bytes;
12pub mod variable_elements;
13
14use crate::trivial_type::TrivialType;
15use core::ops::{Deref, DerefMut};
16use core::ptr::NonNull;
17
18/// The maximum alignment supported by [`IoType`] types (16 bytes, corresponds to alignment of
19/// `u128`)
20pub const MAX_ALIGNMENT: u8 = 16;
21
22const _: () = {
23 assert!(
24 size_of::<usize>() >= size_of::<u32>(),
25 "At least 32-bit platform required"
26 );
27
28 // Only support little-endian environments, in big-endian byte order will be different, and
29 // it'll not be possible to simply send bytes of data structures that implement `TrivialType`
30 // from host to guest environment
31 assert!(
32 u16::from_ne_bytes(1u16.to_le_bytes()) == 1u16,
33 "Only little-endian platform supported"
34 );
35
36 // Max alignment is expected to match that of `u128`
37 assert!(
38 align_of::<u128>() == MAX_ALIGNMENT as usize,
39 "Max alignment mismatch"
40 );
41
42 // Only support targets with expected alignment and refuse to compile on other targets
43 assert!(align_of::<()>() == 1, "Unsupported alignment of `()`");
44 assert!(align_of::<u8>() == 1, "Unsupported alignment of `u8`");
45 assert!(align_of::<u16>() == 2, "Unsupported alignment of `u16`");
46 assert!(align_of::<u32>() == 4, "Unsupported alignment of `u32`");
47 assert!(align_of::<u64>() == 8, "Unsupported alignment of `u64`");
48 assert!(align_of::<u128>() == 16, "Unsupported alignment of `u128`");
49 assert!(align_of::<i8>() == 1, "Unsupported alignment of `i8`");
50 assert!(align_of::<i16>() == 2, "Unsupported alignment of `i16`");
51 assert!(align_of::<i32>() == 4, "Unsupported alignment of `i32`");
52 assert!(align_of::<i64>() == 8, "Unsupported alignment of `i64`");
53 assert!(align_of::<i128>() == 16, "Unsupported alignment of `i128`");
54};
55
56struct DerefWrapper<T>(T);
57
58impl<T> Deref for DerefWrapper<T> {
59 type Target = T;
60
61 #[inline(always)]
62 fn deref(&self) -> &Self::Target {
63 &self.0
64 }
65}
66
67impl<T> DerefMut for DerefWrapper<T> {
68 #[inline(always)]
69 fn deref_mut(&mut self) -> &mut Self::Target {
70 &mut self.0
71 }
72}
73
74// TODO: A way to point output types to input types in order to avoid unnecessary memory copy
75// (setting a pointer)
76/// Trait that is used for types that are crossing host/guest boundary in contracts.
77///
78/// Crucially, it is implemented for any type that implements [`TrivialType`] and for
79/// [`VariableBytes`](crate::variable_bytes::VariableBytes).
80///
81/// # Safety
82/// This trait is used for types with memory transmutation capabilities, it must not be relied on
83/// with untrusted data. Serializing and deserializing of types that implement this trait is simply
84/// casting of underlying memory. As a result, all the types implementing this trait must not use
85/// implicit padding, unions or anything similar that might make it unsound to access any bits of
86/// the type.
87///
88/// Helper functions are provided to make casting to/from bytes a bit safer than it would otherwise,
89/// but extra care is still needed.
90///
91/// **Do not implement this trait explicitly!** Use `#[derive(TrivialType)]` instead, which will
92/// ensure safety requirements are upheld, or use `VariableBytes` if more flexibility is needed.
93///
94/// In case of variable state size is needed, create a wrapper struct around `VariableBytes` and
95/// implement traits on it by forwarding everything to inner implementation.
96pub unsafe trait IoType {
97 /// Data structure metadata in binary form, describing shape and types of the contents, see
98 /// [`IoTypeMetadataKind`] for encoding details
99 ///
100 /// [`IoTypeMetadataKind`]: crate::metadata::IoTypeMetadataKind
101 const METADATA: &[u8];
102
103 /// Pointer with trivial type that this `IoType` represents
104 type PointerType: TrivialType;
105
106 /// Number of bytes that are currently used to store data
107 fn size(&self) -> u32;
108
109 /// Pointer to the number of bytes that are currently used to store data.
110 ///
111 /// # Safety
112 /// While calling this function is technically safe, it and allows to ignore many of its
113 /// invariants, so requires extra care. In particular, no modifications must be done to the
114 /// value while this returned pointer might be used and no changes must be done through the
115 /// returned pointer. Also, lifetimes are only superficial here and can be easily (and
116 /// incorrectly) ignored by using `Copy`.
117 unsafe fn size_ptr(&self) -> impl Deref<Target = NonNull<u32>>;
118
119 /// An exclusive pointer to the number of bytes that are currently used to store data.
120 ///
121 /// NOTE: Pointer might be `null` for [`TrivialType`]s that don't store size internally, in
122 /// which case type's capacity should be used as size.
123 ///
124 /// # Safety
125 /// While calling this function is technically safe, it and allows to ignore many of its
126 /// invariants, so requires extra care. In particular, the value's contents must not be read or
127 /// written to while returned point might be used. Also, lifetimes are only superficial here and
128 /// can be easily (and incorrectly) ignored by using `Copy`.
129 unsafe fn size_mut_ptr(&mut self) -> impl DerefMut<Target = *mut u32>;
130
131 /// Number of bytes are allocated right now
132 fn capacity(&self) -> u32;
133
134 /// Number of bytes are allocated right now
135 ///
136 /// # Safety
137 /// While calling this function is technically safe, it and allows to ignore many of its
138 /// invariants, so requires extra care. In particular, no modifications must be done to the
139 /// value while this returned pointer might be used and no changes must be done through the
140 /// returned pointer. Also, lifetimes are only superficial here and can be easily (and
141 /// incorrectly) ignored by using `Copy`.
142 unsafe fn capacity_ptr(&self) -> impl Deref<Target = NonNull<u32>>;
143
144 /// Set the number of used bytes
145 ///
146 /// # Safety
147 /// `size` must be set to number of properly initialized bytes
148 unsafe fn set_size(&mut self, size: u32);
149
150 /// Create a reference to a type, which is represented by provided memory.
151 ///
152 /// Memory must be correctly aligned and sufficient in size, but padding beyond the size of the
153 /// type is allowed. Memory behind a pointer must not be written to in the meantime either.
154 ///
155 /// Only `size` are guaranteed to be allocated for types that can store variable amount of
156 /// data due to read-only nature of read-only access here.
157 ///
158 /// # Panics
159 /// Panics if `size` is a `null` pointer in case of non-[`TrivialType`]
160 ///
161 /// # Safety
162 /// Input bytes must be previously produced by taking underlying bytes of the same type.
163 // `impl Deref` is used to tie lifetime of returned value to inputs, but still treat it as a
164 // shared reference for most practical purposes. While lifetime here is somewhat superficial due
165 // to `Copy` nature of the value, it must be respected. Size must point to properly initialized
166 // memory.
167 #[track_caller]
168 unsafe fn from_ptr<'a>(
169 ptr: &'a NonNull<Self::PointerType>,
170 size: &'a u32,
171 capacity: u32,
172 ) -> impl Deref<Target = Self> + 'a;
173
174 /// Create a mutable reference to a type, which is represented by provided memory.
175 ///
176 /// Memory must be correctly aligned and sufficient in size or else `None` will be returned, but
177 /// padding beyond the size of the type is allowed. Memory behind a pointer must not be read or
178 /// written to in the meantime either.
179 ///
180 /// `size` indicates how many bytes are used within larger allocation for types that can
181 /// store variable amount of data.
182 ///
183 /// # Panics
184 /// Panics if `size` is a `null` pointer in case of non-[`TrivialType`]
185 ///
186 /// # Safety
187 /// Input bytes must be previously produced by taking underlying bytes of the same type.
188 // `impl DerefMut` is used to tie lifetime of returned value to inputs, but still treat it as an
189 // exclusive reference for most practical purposes. While lifetime here is somewhat superficial
190 // due to `Copy` nature of the value, it must be respected. Size must point to properly
191 // initialized memory for non-[`TrivialType`].
192 #[track_caller]
193 unsafe fn from_mut_ptr<'a>(
194 ptr: &'a mut NonNull<Self::PointerType>,
195 size: &'a mut *mut u32,
196 capacity: u32,
197 ) -> impl DerefMut<Target = Self> + 'a;
198
199 /// Get a raw pointer to the underlying data with no checks.
200 ///
201 /// # Safety
202 /// While calling this function is technically safe, it and allows to ignore many of its
203 /// invariants, so requires extra care. In particular, no modifications must be done to the
204 /// value while this returned pointer might be used and no changes must be done through the
205 /// returned pointer. Also, lifetimes are only superficial here and can be easily (and
206 /// incorrectly) ignored by using `Copy`.
207 unsafe fn as_ptr(&self) -> impl Deref<Target = NonNull<Self::PointerType>>;
208
209 /// Get an exclusive raw pointer to the underlying data with no checks.
210 ///
211 /// # Safety
212 /// While calling this function is technically safe, it and allows to ignore many of its
213 /// invariants, so requires extra care. In particular, the value's contents must not be read or
214 /// written to while returned point might be used. Also, lifetimes are only superficial here and
215 /// can be easily (and incorrectly) ignored by using `Copy`.
216 unsafe fn as_mut_ptr(&mut self) -> impl DerefMut<Target = NonNull<Self::PointerType>>;
217}
218
219/// Marker trait, companion to [`IoType`] that indicates the ability to store optional contents.
220///
221/// This means that zero bytes size is a valid invariant. This type is never implemented for types
222/// implementing [`TrivialType`] because they always have fixed size, and it is not zero.
223pub trait IoTypeOptional: IoType {}