vector_ta/utilities/
aligned_vector.rs1use std::{
2 alloc::{alloc, dealloc, Layout},
3 ptr::NonNull,
4};
5
6pub struct AlignedVec {
7 ptr: NonNull<f64>,
8 len: usize,
9 cap: usize,
10}
11
12impl AlignedVec {
13 #[inline]
14 pub fn with_capacity(cap: usize) -> Self {
15 assert!(cap > 0);
16 let layout = Layout::from_size_align(cap * 8, 64).expect("layout");
17 let raw = unsafe { alloc(layout) } as *mut f64;
18 if raw.is_null() {
19 std::alloc::handle_alloc_error(layout);
20 }
21 Self {
22 ptr: unsafe { NonNull::new_unchecked(raw) },
23 len: cap,
24 cap,
25 }
26 }
27
28 #[inline]
29 pub fn as_slice(&self) -> &[f64] {
30 unsafe { std::slice::from_raw_parts(self.ptr.as_ptr(), self.len) }
31 }
32
33 #[inline]
34 pub fn as_mut_slice(&mut self) -> &mut [f64] {
35 unsafe { std::slice::from_raw_parts_mut(self.ptr.as_ptr(), self.len) }
36 }
37
38 #[inline]
39 pub fn as_ptr(&self) -> *const f64 {
40 self.ptr.as_ptr()
41 }
42}
43
44impl Drop for AlignedVec {
45 fn drop(&mut self) {
46 let layout = Layout::from_size_align(self.cap * 8, 64).unwrap();
47 unsafe { dealloc(self.ptr.as_ptr() as *mut u8, layout) };
48 }
49}
50
51impl AsRef<[f64]> for AlignedVec {
52 #[inline]
53 fn as_ref(&self) -> &[f64] {
54 self.as_slice()
55 }
56}