Skip to content

Instantly share code, notes, and snippets.

@ugovaretto
Created June 7, 2022 10:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ugovaretto/d3a6877c4099069727c23927f51f0163 to your computer and use it in GitHub Desktop.
Save ugovaretto/d3a6877c4099069727c23927f51f0163 to your computer and use it in GitHub Desktop.
Create aligned Vec instance
// 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