Skip to main content

rumtk_arena/mem/
mem.rs

1/*
2 *     rumtk attempts to implement HL7 and medical protocols for interoperability in medicine.
3 *     This toolkit aims to be reliable, simple, performant, and standards compliant.
4 *     Copyright (C) 2026  Luis M. Santos, M.D. <lsantos@medicalmasses.com>
5 *     Copyright (C) 2026  MedicalMasses L.L.C. <contact@medicalmasses.com>
6 *
7 *     This program is free software: you can redistribute it and/or modify
8 *     it under the terms of the GNU General Public License as published by
9 *     the Free Software Foundation, either version 3 of the License, or
10 *     (at your option) any later version.
11 *
12 *     This program is distributed in the hope that it will be useful,
13 *     but WITHOUT ANY WARRANTY; without even the implied warranty of
14 *     MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15 *     GNU General Public License for more details.
16 *
17 *     You should have received a copy of the GNU General Public License
18 *     along with this program.  If not, see <https://www.gnu.org/licenses/>.
19 */
20use std::ptr::NonNull;
21
22#[inline(always)]
23pub fn cast_to_nonnull<T: ?Sized>(dst: *mut T) -> NonNull<T> {
24    match NonNull::new(dst) {
25        Some(ptr) => ptr,
26        None => panic!("Failed to allocate memory"),
27    }
28}
29
30#[inline(always)]
31pub fn cast_data_to_ptr<T>(data: &T) -> *const u8 {
32    std::ptr::addr_of!(*data).cast::<u8>()
33}
34
35#[inline(always)]
36pub fn sizeof<T>(data: &T) -> usize {
37    size_of::<T>()
38}
39
40#[inline(always)]
41pub fn zero_memory(data: *mut [u8], offset: usize, length: usize) -> *mut [u8] {
42    let chunk = unsafe { &mut *data };
43    for i in offset..offset + length {
44        chunk[i] = 0;
45    }
46
47    data
48}
49
50#[macro_export]
51macro_rules! rumtk_layout {
52    (  ) => {{
53        rumtk_layout!(0, u8)
54    }};
55    ( $size:expr ) => {{
56        rumtk_layout!($size, u8)
57    }};
58    ( $size:expr, $alignment:ty ) => {{
59        use std::alloc::{Layout};
60
61        Layout::from_size_align_unchecked($size, size_of::<$alignment>())
62    }};
63}