Skip to main content

harmos_domain/message/
allocation.rs

1/* ***
2 *
3 * Harmos
4 *
5 * SPDX-License-Identifier: Apache-2.0
6 *
7 * ***
8 */
9
10// Checked Decoding Memory Arithmetic And Exact-Capacity Containers
11
12/* === Modules === */
13
14/* === Re-Exports === */
15
16/* === Imports === */
17
18// Standard Library Imports
19
20// Third Party Imports
21
22// Local Imports
23use super::MessageError;
24
25/* === Constants === */
26
27/* === Macros === */
28
29/* === Type Aliases === */
30
31/* === Structs === */
32
33/* === Enums === */
34
35/* === Traits === */
36
37/* === Implementations === */
38
39/* === Public Functions === */
40
41pub fn add(left: usize, right: usize) -> Result<usize, MessageError> {
42    left.checked_add(right).ok_or_else(|| MessageError::borrowed("decoding memory bound overflow"))
43}
44
45pub fn multiply(left: usize, right: usize) -> Result<usize, MessageError> {
46    left.checked_mul(right).ok_or_else(|| MessageError::borrowed("decoding memory bound overflow"))
47}
48
49#[allow(unsafe_code, reason = "transfer the fixed boxed allocation to the original decoder vector")]
50pub fn vector<T>(capacity: usize) -> Result<Vec<T>, MessageError> {
51    std::alloc::Layout::array::<T>(capacity).map_err(|_| MessageError::borrowed("decoding container exceeds address space"))?;
52    let allocation = Box::<[T]>::new_uninit_slice(capacity);
53    let pointer = Box::into_raw(allocation) as *mut std::mem::MaybeUninit<T> as *mut T;
54    // The Box and Vec layouts share T's size/alignment and the exact element
55    // count. No elements are initialized; Vec's length is zero. Vec takes sole
56    // allocation ownership, including the aligned dangling zero-sized case.
57    Ok(unsafe { Vec::from_raw_parts(pointer, 0, capacity) })
58}
59
60/* === Private Functions === */
61
62/* === Tests === */