aligned_memory.rs 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. use std::{
  2. alloc::{alloc_zeroed, dealloc, Layout},
  3. mem::size_of,
  4. ops::{Index, IndexMut},
  5. slice::{from_raw_parts, from_raw_parts_mut},
  6. };
  7. const ALIGN_SIMD: usize = 64; // enough to support AVX-512
  8. pub type AlignedMemory64 = AlignedMemory<ALIGN_SIMD>;
  9. pub struct AlignedMemory<const ALIGN: usize> {
  10. p: *mut u64,
  11. sz_u64: usize,
  12. layout: Layout,
  13. }
  14. impl<const ALIGN: usize> AlignedMemory<{ ALIGN }> {
  15. pub fn new(sz_u64: usize) -> Self {
  16. let sz_bytes = sz_u64 * size_of::<u64>();
  17. let layout = Layout::from_size_align(sz_bytes, ALIGN).unwrap();
  18. let ptr;
  19. unsafe {
  20. ptr = alloc_zeroed(layout);
  21. }
  22. Self {
  23. p: ptr as *mut u64,
  24. sz_u64,
  25. layout,
  26. }
  27. }
  28. pub fn as_slice(&self) -> &[u64] {
  29. unsafe { from_raw_parts(self.p, self.sz_u64) }
  30. }
  31. pub fn as_mut_slice(&mut self) -> &mut [u64] {
  32. unsafe { from_raw_parts_mut(self.p, self.sz_u64) }
  33. }
  34. pub unsafe fn as_ptr(&self) -> *const u64 {
  35. self.p
  36. }
  37. pub unsafe fn as_mut_ptr(&mut self) -> *mut u64 {
  38. self.p
  39. }
  40. pub fn len(&self) -> usize {
  41. self.sz_u64
  42. }
  43. }
  44. impl<const ALIGN: usize> Drop for AlignedMemory<{ ALIGN }> {
  45. fn drop(&mut self) {
  46. unsafe {
  47. dealloc(self.p as *mut u8, self.layout);
  48. }
  49. }
  50. }
  51. impl<const ALIGN: usize> Index<usize> for AlignedMemory<{ ALIGN }> {
  52. type Output = u64;
  53. fn index(&self, index: usize) -> &Self::Output {
  54. &self.as_slice()[index]
  55. }
  56. }
  57. impl<const ALIGN: usize> IndexMut<usize> for AlignedMemory<{ ALIGN }> {
  58. fn index_mut(&mut self, index: usize) -> &mut Self::Output {
  59. &mut self.as_mut_slice()[index]
  60. }
  61. }
  62. impl<const ALIGN: usize> Clone for AlignedMemory<{ ALIGN }> {
  63. fn clone(&self) -> Self {
  64. let mut out = Self::new(self.sz_u64);
  65. out.as_mut_slice().copy_from_slice(self.as_slice());
  66. out
  67. }
  68. }