Skip to main content

ab_contracts_common/
output.rs

1//! Memory given to method calls as `#[output]`
2
3use crate::ContractError;
4use ab_io_type::maybe_data::MaybeData;
5use ab_io_type::trivial_type::{AnyBitPattern, TrivialType};
6use ab_io_type::variable_elements::VariableElements;
7use ab_io_type::{IoType, IoTypeOptional};
8use core::fmt;
9use core::marker::PhantomData;
10use core::mem::MaybeUninit;
11use core::ptr::NonNull;
12
13/// Memory that can be given to a method call as an `#[output]` of type `Target`.
14///
15/// A call can leave contents behind that are not a valid value of `Target`, for example when it
16/// fails halfway, so the contents must be parsed before they are accessed, unless every bit
17/// pattern is a valid value (see [`AnyBitPattern`]). [`Lent`] does this for memory whose contents
18/// need parsing.
19///
20/// A call gets the pointer, size and capacity from [`Self::as_raw_output()`]. Until `self` is used
21/// again, the call may write initialized bytes anywhere within the capacity, even if it fails. If
22/// it succeeds, the size it reports is set with [`Self::set_output_size()`].
23///
24/// # Safety
25/// [`Self::as_raw_output()`] returns a pointer aligned for `Target::PointerType`, and a size that
26/// is valid for `Target` and doesn't exceed the capacity it returns. The pointer is valid for
27/// writes of the capacity, but for reads only of the size, with that many bytes initialized: the
28/// bytes after them may be uninitialized and must not be read before they are written. While
29/// `self` stays exclusively borrowed after that, the memory is not accessed other than through the
30/// pointer. Whatever initialized bytes a call leaves within the size (the initial one or the last
31/// one set with [`Self::set_output_size()`]) are never accessed as `Target` without being parsed
32/// first, unless every bit pattern is a valid value of `Target::PointerType`.
33#[diagnostic::on_unimplemented(
34    message = "`{Self}` can't be given to a call as an `#[output]` of type `{Target}`",
35    label = "expected `&mut {Target}` whose contents accept every bit pattern, or \
36    `&mut Lent<{Target}>`",
37    note = "a failed call can leave invalid contents behind, use `Lent::new()` for a local value, \
38    `Lent::<MaybeData<'_, _>>::from_uninit()` or \
39    `Lent::<VariableElements<'_, _>>::from_uninit()` for a local container, or \
40    `Env::lend_output()` for an `#[output]` the method received"
41)]
42pub unsafe trait OutputArg<Target>
43where
44    Target: IoType,
45{
46    /// Pointer to the contents, size and capacity to give to a call
47    fn as_raw_output(&mut self) -> (NonNull<Target::PointerType>, u32, u32);
48
49    /// Set the size that a successful call reported.
50    ///
51    /// # Safety
52    /// `size` must be valid for `Target` (see [`IoType::try_from_ptr()`]) and not exceed the
53    /// capacity, and that many bytes must be initialized.
54    unsafe fn set_output_size(&mut self, size: u32);
55}
56
57// Without this attribute rustc reports the unsatisfied `AnyBitPattern` bound of the contents of
58// containers instead of the message of `OutputArg`
59#[diagnostic::do_not_recommend]
60// SAFETY: Pointer, size and capacity are those of a valid value, the pointer can be used for reads
61// of the size and writes of the capacity while the value isn't accessed otherwise
62// (`IoType::as_mut_ptr()`), which it isn't while `self` is exclusively borrowed. Initialized
63// contents are a valid value, since every bit pattern is.
64unsafe impl<T> OutputArg<T> for T
65where
66    T: IoType<PointerType: AnyBitPattern>,
67{
68    #[inline(always)]
69    fn as_raw_output(&mut self) -> (NonNull<T::PointerType>, u32, u32) {
70        (
71            IoType::as_mut_ptr(self),
72            IoType::size(self),
73            IoType::capacity(self),
74        )
75    }
76
77    #[inline(always)]
78    unsafe fn set_output_size(&mut self, size: u32) {
79        // SAFETY: The size is valid and doesn't exceed the capacity, with that many bytes
80        // initialized (function contract), which are a valid value, since every bit pattern is
81        unsafe { IoType::set_size(self, size) }
82    }
83}
84
85enum LentValue<'a, T> {
86    /// A plain value owned by `Lent`, which may not be a valid value after a call
87    Owned(MaybeUninit<T>),
88    /// A container view owned by `Lent` over memory borrowed for `'a`. The view itself is valid,
89    /// while its contents may not be after a call.
90    View(T),
91    /// A plain value or a container view borrowed for `'a`
92    Borrowed(NonNull<T>, PhantomData<&'a mut T>),
93}
94
95/// Memory lent to calls as an `#[output]`, whose contents are parsed before they are accessed.
96///
97/// A call can leave contents behind that are not a valid value, for example when it fails halfway,
98/// so the contents are only accessible through [`Self::get_mut()`], which parses them once after
99/// each call. Plain values can also be replaced with [`Self::set()`], and containers emptied with
100/// [`Self::clear()`]. Memory whose contents accept every bit pattern can be given to calls
101/// directly, see [`OutputArg`].
102///
103/// Created with [`Self::new()`] for a local value, with `Lent::<MaybeData<'_, _>>::from_uninit()`
104/// or `Lent::<VariableElements<'_, _>>::from_uninit()` for a local container, and with
105/// [`Env::lend_output()`] for an `#[output]` the method received.
106///
107/// [`Env::lend_output()`]: crate::env::Env::lend_output
108pub struct Lent<'a, T>
109where
110    T: IoType,
111{
112    value: LentValue<'a, T>,
113    /// Pointer to the contents, size and capacity, read from the value again while it is
114    /// `checked`
115    ptr: NonNull<T::PointerType>,
116    size: u32,
117    capacity: u32,
118    /// Neither a call nor a size set changed the contents since they were last known to be valid
119    checked: bool,
120}
121
122impl<T> fmt::Debug for Lent<'_, T>
123where
124    T: IoType,
125{
126    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
127        // Contents may not be a valid value
128        f.debug_struct("Lent")
129            .field("size", &self.size)
130            .field("capacity", &self.capacity)
131            .field("checked", &self.checked)
132            .finish_non_exhaustive()
133    }
134}
135
136// SAFETY: Pointer, size and capacity are those of the value when it was last known to be valid
137// (created, parsed, set or cleared), so the pointer can be used for reads of the size and writes
138// of the capacity (`IoType::as_mut_ptr()`). Since then, only calls changed the contents, by writing
139// initialized bytes within the capacity, and the size, through `Self::set_output_size()`. The value
140// is owned by `self` or borrowed by it for `'a`, so it isn't accessed while `self` is exclusively
141// borrowed. The contents are only accessed as `T` after `Self::get_mut()` parsed them,
142// `Self::set()` wrote a valid value or `Self::clear()` set a size that is valid without contents.
143unsafe impl<T> OutputArg<T> for Lent<'_, T>
144where
145    T: IoType,
146{
147    #[inline(always)]
148    fn as_raw_output(&mut self) -> (NonNull<T::PointerType>, u32, u32) {
149        let raw_parts = self.raw_parts();
150        self.checked = false;
151        raw_parts
152    }
153
154    #[inline(always)]
155    unsafe fn set_output_size(&mut self, size: u32) {
156        // Make sure the cached size is that of the value
157        self.raw_parts();
158        // The only valid size of a plain value is its size, so a different size means `T` is a
159        // container view, which is a valid value regardless of its contents
160        if size != self.size {
161            // SAFETY: A container view, which is valid, owned by `self` or borrowed by it, and not
162            // referenced elsewhere while `self` is exclusively borrowed
163            let value = unsafe { self.value_ptr().as_mut() };
164            // SAFETY: The size is valid and doesn't exceed the capacity, with that many bytes
165            // initialized (function contract), the contents are only accessed after
166            // `Self::get_mut()` parsed them
167            unsafe {
168                IoType::set_size(value, size);
169            }
170            self.size = size;
171        }
172        // The contents may have changed together with the size
173        self.checked = false;
174    }
175}
176
177impl<T> Lent<'static, T>
178where
179    T: TrivialType,
180{
181    /// Lend a local value
182    #[inline(always)]
183    pub fn new(value: T) -> Self {
184        Self {
185            value: LentValue::Owned(MaybeUninit::new(value)),
186            // Read from the value before it is given to a call
187            ptr: NonNull::dangling(),
188            size: T::SIZE,
189            capacity: T::SIZE,
190            checked: true,
191        }
192    }
193}
194
195impl<'a, Data> Lent<'a, MaybeData<'a, Data>>
196where
197    Data: TrivialType,
198    MaybeData<'a, Data>: IoType,
199{
200    /// Lend a local [`MaybeData`] over uninitialized memory, like [`MaybeData::from_uninit()`].
201    ///
202    /// Returns `None` if `size != 0`.
203    #[inline(always)]
204    pub fn from_uninit(uninit: &'a mut MaybeUninit<Data>, size: &'a mut u32) -> Option<Self> {
205        Some(Self::from_view(MaybeData::from_uninit(uninit, size)?))
206    }
207}
208
209impl<'a, Element, const RECOMMENDED_ALLOCATION: u32>
210    Lent<'a, VariableElements<'a, Element, RECOMMENDED_ALLOCATION>>
211where
212    Element: TrivialType,
213    VariableElements<'a, Element, RECOMMENDED_ALLOCATION>: IoType,
214{
215    /// Lend a local [`VariableElements`] over uninitialized memory, like
216    /// [`VariableElements::from_uninit()`].
217    ///
218    /// Returns `None` if `size != 0` or if the buffer is larger than `u32::MAX` bytes.
219    #[inline(always)]
220    pub fn from_uninit(uninit: &'a mut [MaybeUninit<Element>], size: &'a mut u32) -> Option<Self> {
221        Some(Self::from_view(VariableElements::from_uninit(
222            uninit, size,
223        )?))
224    }
225}
226
227impl<'a, T> Lent<'a, T>
228where
229    T: IoType,
230{
231    /// Lend a container view over memory borrowed for `'a`
232    #[inline(always)]
233    fn from_view(mut view: T) -> Self {
234        let ptr = IoType::as_mut_ptr(&mut view);
235        let size = IoType::size(&view);
236        let capacity = IoType::capacity(&view);
237        Self {
238            value: LentValue::View(view),
239            ptr,
240            size,
241            capacity,
242            checked: true,
243        }
244    }
245
246    /// Lend `value`, which is only borrowed for `'a`, rather than until the method returns like
247    /// with [`Env::lend_output()`].
248    ///
249    /// # Safety
250    /// After the returned `Lent` was given to a call, `value` may hold contents that are not a
251    /// valid value. Once the `Lent` is no longer used, the contents of `value` must not be accessed
252    /// without being parsed first, unless the last use of the `Lent` after its last call was a
253    /// successful [`Self::get_mut()`], [`Self::set()`] or [`Self::clear()`], or the contents of `T`
254    /// accept every bit pattern.
255    ///
256    /// [`Env::lend_output()`]: crate::env::Env::lend_output
257    #[inline(always)]
258    pub unsafe fn from_mut_unchecked(value: &'a mut T) -> Self {
259        let ptr = IoType::as_mut_ptr(value);
260        let size = IoType::size(value);
261        let capacity = IoType::capacity(value);
262        Self {
263            value: LentValue::Borrowed(NonNull::from_mut(value), PhantomData),
264            ptr,
265            size,
266            capacity,
267            checked: true,
268        }
269    }
270
271    /// Exclusive access to the contents, which are parsed once after each call.
272    ///
273    /// Repeated calls without a call in between don't parse the contents again. Returns
274    /// [`ContractError::BadOutput`] if they are not a valid value of `T`. They then stay
275    /// inaccessible until [`Self::set()`] replaces a plain value or [`Self::clear()`] empties a
276    /// container. Lending them again doesn't help either: methods generated by `#[contract]` reject
277    /// outputs with invalid initial contents with [`ContractError::BadInput`].
278    ///
279    /// A plain value is returned as `&mut T`. A container is returned as a new view of the lent
280    /// memory that only lives while `self` is borrowed (see [`IoType::reborrow_mut()`]). Code that
281    /// replaces it, for example with a view of other memory, doesn't change what `self` lends to
282    /// calls.
283    #[inline(always)]
284    pub fn get_mut(&mut self) -> Result<T::Reborrowed<'_>, ContractError> {
285        if !self.checked {
286            let (mut ptr, mut size, capacity) = self.raw_parts();
287            // SAFETY: The pointer is aligned and valid for writes of the capacity and for reads of
288            // the size, which is valid for `T` and doesn't exceed the capacity, with that many
289            // bytes initialized. The value was valid with these parts, and calls since then only
290            // wrote initialized bytes within the capacity and set a valid size
291            // (`OutputArg::set_output_size()` contract). Nothing else accesses the memory while
292            // `self` is exclusively borrowed, and nothing is moved out of the returned value,
293            // which is dropped right away.
294            if unsafe { T::try_from_mut_ptr(&mut ptr, &mut size, capacity) }.is_none() {
295                return Err(ContractError::BadOutput);
296            }
297            self.checked = true;
298        }
299        // SAFETY: A valid value, since it was parsed above or neither a call nor a size set changed
300        // it since it was last known to be valid, owned by `self` or borrowed by it, and not
301        // referenced elsewhere while `self` is borrowed
302        let value = unsafe { self.value_ptr().as_mut() };
303        Ok(value.reborrow_mut())
304    }
305
306    /// Pointer to the value, which may not be valid unless `checked`
307    #[inline(always)]
308    fn value_ptr(&mut self) -> NonNull<T> {
309        match &mut self.value {
310            LentValue::Owned(value) => NonNull::from_mut(value).cast::<T>(),
311            LentValue::View(view) => NonNull::from_mut(view),
312            LentValue::Borrowed(value, _) => *value,
313        }
314    }
315
316    /// Pointer to the contents, size and capacity, read from the value unless a call or a size set
317    /// may have changed it since it was last known to be valid
318    #[inline(always)]
319    fn raw_parts(&mut self) -> (NonNull<T::PointerType>, u32, u32) {
320        if self.checked {
321            // SAFETY: A valid value, since neither a call nor a size set changed it since it was
322            // created, parsed, set or cleared, owned by `self` or borrowed by it, and not
323            // referenced elsewhere while `self` is exclusively borrowed
324            let value = unsafe { self.value_ptr().as_mut() };
325            self.ptr = IoType::as_mut_ptr(value);
326            self.size = IoType::size(value);
327            self.capacity = IoType::capacity(value);
328        } else if let LentValue::Owned(value) = &mut self.value {
329            // An owned value moves together with `Lent`, unlike the memory of other values
330            self.ptr = NonNull::from_mut(value).cast::<T::PointerType>();
331        }
332        (self.ptr, self.size, self.capacity)
333    }
334}
335
336impl<T> Lent<'_, T>
337where
338    T: TrivialType,
339{
340    /// Replace the contents with a valid value
341    #[inline(always)]
342    pub fn set(&mut self, value: T) -> &mut T {
343        let mut ptr = self.value_ptr();
344        // SAFETY: Aligned and valid for writes of `T`, owned by `self` or borrowed by it, and not
345        // referenced elsewhere while `self` is exclusively borrowed
346        unsafe {
347            ptr.write(value);
348        }
349        self.checked = true;
350        // SAFETY: A valid value was written above, not referenced elsewhere while `self` is
351        // borrowed
352        unsafe { ptr.as_mut() }
353    }
354}
355
356impl<T> Lent<'_, T>
357where
358    T: IoTypeOptional,
359{
360    /// Empty the contents, which makes them a valid value whatever calls left behind.
361    ///
362    /// The size becomes `0` and the capacity stays the same. This makes a container accessible
363    /// again after [`Self::get_mut()`] returned [`ContractError::BadOutput`], so the memory can be
364    /// lent to another call, even if it was lent with [`Env::lend_output()`] and can't be lent
365    /// anew. Since a call gets the contents of an `#[output]` as its initial contents, this also
366    /// gives the next call an empty container rather than what the previous call left behind.
367    ///
368    /// Returns the emptied container like [`Self::get_mut()`] does.
369    ///
370    /// [`Env::lend_output()`]: crate::env::Env::lend_output
371    #[inline(always)]
372    pub fn clear(&mut self) -> T::Reborrowed<'_> {
373        self.size = 0;
374        self.checked = true;
375        // SAFETY: A container view, which is a valid value regardless of its contents, owned by
376        // `self` or borrowed by it, and not referenced elsewhere while `self` is exclusively
377        // borrowed
378        let value = unsafe { self.value_ptr().as_mut() };
379        // SAFETY: Size `0` is valid for `T`, doesn't exceed the capacity and doesn't require any
380        // initialized bytes (`IoTypeOptional` contract), which makes the value valid as `checked`
381        // says
382        unsafe {
383            IoType::set_size(value, 0);
384        }
385        value.reborrow_mut()
386    }
387}