Created
June 7, 2022 10:29
-
-
Save ugovaretto/d3a6877c4099069727c23927f51f0163 to your computer and use it in GitHub Desktop.
Create aligned Vec instance
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Create aligned Vec | |
fn main() { | |
let ivec: Vec<i32> = aligned_vec(2048, 4096, 256); | |
assert!(ivec.as_ptr() as u64 % 256 == 0); | |
} | |
pub fn aligned_vec<T: Sized>(size: usize, capacity: usize, align: usize) -> Vec<T> { | |
unsafe { | |
if size == 0 { | |
Vec::<T>::new() | |
} else { | |
let size = size * std::mem::size_of::<T>(); | |
let capacity = (capacity * std::mem::size_of::<T>()).max(size); | |
let layout = std::alloc::Layout::from_size_align_unchecked(size, align); | |
let raw_ptr = std::alloc::alloc(layout) as *mut T; | |
Vec::from_raw_parts(raw_ptr, size, capacity) | |
} | |
} | |
} | |
//use crate page_size to retrieve system page size |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment