Skip to main content

spiral_server/db/
aligned_memory.rs

1use std::{
2    alloc::{alloc_zeroed, dealloc, realloc, Layout},
3    mem::size_of,
4    ops::{Index, IndexMut},
5    slice::{from_raw_parts, from_raw_parts_mut},
6};
7
8const ALIGN_SIMD: usize = 64; // enough to support AVX-512
9pub type AlignedMemory64 = AlignedMemory<ALIGN_SIMD>;
10
11pub struct AlignedMemory<const ALIGN: usize> {
12    p: *mut u64,
13    sz_u64: usize,
14    layout: Layout,
15}
16
17impl<const ALIGN: usize> AlignedMemory<{ ALIGN }> {
18    pub fn new(sz_u64: usize) -> Self {
19        let sz_bytes = sz_u64 * size_of::<u64>();
20        let layout = Layout::from_size_align(sz_bytes, ALIGN).unwrap();
21
22        let ptr;
23        unsafe {
24            ptr = alloc_zeroed(layout);
25        }
26
27        Self {
28            p: ptr as *mut u64,
29            sz_u64,
30            layout,
31        }
32    }
33
34    pub fn extend(&mut self, new_size: usize) {
35        self.sz_u64 = new_size;
36        let new_size = self.sz_u64 * size_of::<u64>();
37        unsafe {
38            self.p = realloc(self.p as *mut u8, self.layout, new_size) as *mut u64;
39            self.layout = Layout::from_size_align_unchecked(new_size, self.layout.align());
40        }
41    }
42
43    pub fn insert(&mut self, index: usize, element: u64) {
44        self.extend(self.sz_u64 + 1);
45        self.as_mut_slice()[index..].rotate_right(1);
46        self[index] = element;
47    }
48
49    pub fn as_slice(&self) -> &[u64] {
50        unsafe { from_raw_parts(self.p, self.sz_u64) }
51    }
52
53    pub fn as_mut_slice(&mut self) -> &mut [u64] {
54        unsafe { from_raw_parts_mut(self.p, self.sz_u64) }
55    }
56
57    pub unsafe fn as_ptr(&self) -> *const u64 {
58        self.p
59    }
60
61    pub unsafe fn as_mut_ptr(&mut self) -> *mut u64 {
62        self.p
63    }
64
65    pub fn len(&self) -> usize {
66        self.sz_u64
67    }
68}
69
70unsafe impl<const ALIGN: usize> Send for AlignedMemory<{ ALIGN }> {}
71unsafe impl<const ALIGN: usize> Sync for AlignedMemory<{ ALIGN }> {}
72
73impl<const ALIGN: usize> Drop for AlignedMemory<{ ALIGN }> {
74    fn drop(&mut self) {
75        unsafe {
76            dealloc(self.p as *mut u8, self.layout);
77        }
78    }
79}
80
81impl<const ALIGN: usize> Index<usize> for AlignedMemory<{ ALIGN }> {
82    type Output = u64;
83
84    fn index(&self, index: usize) -> &Self::Output {
85        &self.as_slice()[index]
86    }
87}
88
89impl<const ALIGN: usize> IndexMut<usize> for AlignedMemory<{ ALIGN }> {
90    fn index_mut(&mut self, index: usize) -> &mut Self::Output {
91        &mut self.as_mut_slice()[index]
92    }
93}
94
95impl<const ALIGN: usize> Clone for AlignedMemory<{ ALIGN }> {
96    fn clone(&self) -> Self {
97        let mut out = Self::new(self.sz_u64);
98        out.as_mut_slice().copy_from_slice(self.as_slice());
99        out
100    }
101}