Skip to content

Commit

Permalink
Renamed function and created safety comments.
Browse files Browse the repository at this point in the history
  • Loading branch information
Frostie314159 committed Aug 11, 2024
1 parent 8a15bd4 commit 6030953
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 7 deletions.
8 changes: 4 additions & 4 deletions examples/initialised.rs
Original file line number Diff line number Diff line change
Expand Up @@ -4,18 +4,18 @@ use std::mem;
pool!(TestPool: [u32; 3], [0u32; 3]);

fn main() {
let mut buffer = unsafe { Box::<TestPool>::new_potentially_uninit() }.unwrap();
let mut buffer = unsafe { Box::<TestPool>::new_uninit() }.unwrap();
println!("Allocated new buffer, with contents: {:#x}", *buffer);

*buffer = 0xf00dbabeu32;

let _buffer_2 = unsafe { Box::<TestPool>::new_potentially_uninit() }.unwrap();
let _buffer_3 = unsafe { Box::<TestPool>::new_potentially_uninit() }.unwrap();
let _buffer_2 = unsafe { Box::<TestPool>::new_uninit() }.unwrap();
let _buffer_3 = unsafe { Box::<TestPool>::new_uninit() }.unwrap();

mem::drop(buffer);
println!("Dropped buffer.");

let reallocated_buffer = unsafe { Box::<TestPool>::new_potentially_uninit() }.unwrap();
let reallocated_buffer = unsafe { Box::<TestPool>::new_uninit() }.unwrap();
println!(
"Reallocated buffer, with contents: 0x{:#x}",
*reallocated_buffer
Expand Down
17 changes: 14 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -92,22 +92,33 @@ impl<P: Pool> Box<P> {
Some(Self { ptr: p })
}
/// Attempt to allocate a potentially unitialized item from the pool.
///
/// This means, that data from a previous allocation may still be present or the memory is still uninitialized, so caution is advised.
pub unsafe fn new_potentially_uninit() -> Option<Self> {
///
/// # Safety
/// The area of memory, to which this box points, maybe uninitialized or contain data from a previous allocation.
/// You must ensure, that you handle this properly and initialize it yourself.
pub unsafe fn new_uninit() -> Option<Self> {
let p = match P::get().alloc() {
Some(p) => p,
None => return None,
};
Some(Self { ptr: p })
}

/// Turn this box into a raw pointer.
///
/// Once you turn a box into a raw pointer, it becomes your responsibility to free it properly again.
/// This can be done, by creating a box from that raw pointer again, using [Self::from_raw].
pub fn into_raw(b: Self) -> NonNull<P::Item> {
let res = b.ptr;
mem::forget(b);
res
}

/// Create a box from a raw pointer.
///
/// # Safety
/// You must ensure, that the pointer points to valid memory, which was allocated from the pool in the generic parameter.
/// If you fail to do so, this will trigger a panic, once this box is dropped.
pub unsafe fn from_raw(ptr: NonNull<P::Item>) -> Self {
Self { ptr }
}
Expand Down

0 comments on commit 6030953

Please sign in to comment.