Skip to main content

rumtk_arena/
dune.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 crate::{direct_alloc, direct_dealloc, MemoryPool};
21use std::alloc::GlobalAlloc;
22use std::alloc::Layout;
23use std::sync::Mutex;
24
25pub struct Arrakis {
26    dunes: Mutex<MemoryPool>,
27}
28
29impl Arrakis {
30    pub const fn with_capacity(allocation_size: usize) -> Self {
31        Self { dunes: Mutex::new(MemoryPool::with_chunk_size(allocation_size)) }
32    }
33
34    #[inline]
35    unsafe fn allocate(&self, layout: Layout) -> *mut u8 {
36        let mut dunes = self.dunes.lock().unwrap();
37        dunes.allocate(layout)
38    }
39
40    #[inline]
41    unsafe fn deallocate(&self,ptr: *mut u8, layout: Layout) {
42        let mut dunes = self.dunes.lock().unwrap();
43        dunes.deallocate(ptr, layout);
44    }
45}
46
47unsafe impl GlobalAlloc for Arrakis {
48    #[cfg(feature = "fast_global_allocator")]
49    #[inline(always)]
50    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
51        direct_alloc(layout)
52    }
53
54    #[cfg(not(feature = "fast_global_allocator"))]
55    #[inline(always)]
56    unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
57        self.allocate(layout)
58    }
59    
60    #[cfg(feature = "fast_global_allocator")]
61    #[inline(always)]
62    unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
63        direct_dealloc(ptr, _layout)
64    }
65
66    #[cfg(not(feature = "fast_global_allocator"))]
67    #[inline(always)]
68    unsafe fn dealloc(&self, ptr: *mut u8, _layout: Layout) {
69        self.deallocate(ptr, _layout)
70    }
71}
72
73#[macro_export]
74macro_rules! rumtk_dune_new {
75    (  ) => {{
76        use $crate::mem::constants::DEFAULT_GLOBAL_MB_ALLOCATION;
77        rumtk_dune_new!(DEFAULT_GLOBAL_MB_ALLOCATION)
78    }};
79    ( $size:expr ) => {{
80        use std::sync::LazyLock;
81        use $crate::dune::{Arrakis};
82
83        Arrakis::with_capacity($size)
84    }};
85}
86
87