Skip to content

Instantly share code, notes, and snippets.

@josephg
Last active October 9, 2018 23:20
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 josephg/aaf7a5f2f53d50537135372a5a32a7f6 to your computer and use it in GitHub Desktop.
Save josephg/aaf7a5f2f53d50537135372a5a32a7f6 to your computer and use it in GitHub Desktop.
Rust allocations
// This is an example of making a c-style struct ending in a dynamically sized array in stable rust.
use std::alloc::{GlobalAlloc, Layout, System};
struct Blah {
height: usize,
arr: [u8; 0],
}
impl Blah {
fn get_layout_at(height: usize) -> Layout {
Layout::from_size_align(
std::mem::size_of::<Blah>() + height,
std::mem::align_of::<Blah>()).unwrap()
}
fn alloc(height: usize) -> *mut Blah {
unsafe {
let b = System.alloc(Blah::get_layout_at(height)) as *mut Blah;
(*b).height = height;
b
}
}
unsafe fn free(p: *mut Blah) {
System.dealloc(p as *mut u8, Blah::get_layout_at((*p).height));
}
fn get_mut_slice(&mut self) -> &mut [u8] {
unsafe {
std::slice::from_raw_parts_mut(self.arr.as_mut_ptr(), self.height)
}
}
}
// Safe boxed version
struct BlahBox(*mut Blah);
impl BlahBox {
fn new(height: usize) -> BlahBox {
BlahBox(Blah::alloc(height))
}
fn get_mut_slice(&mut self) -> &mut [u8] {
unsafe { (*self.0).get_mut_slice() }
}
}
impl Drop for BlahBox {
fn drop(&mut self) {
unsafe { Blah::free(self.0); }
}
}
fn main() {
let mut blah = BlahBox::new(100);
let slice = blah.get_mut_slice();
slice[2] = 7;
println!("{}", slice[2]);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment