From 6030953496d637a02f6f50773dddda3f969ec98f Mon Sep 17 00:00:00 2001 From: Frostie314159 Date: Sun, 11 Aug 2024 16:50:44 +0200 Subject: [PATCH] Renamed function and created safety comments. --- examples/initialised.rs | 8 ++++---- src/lib.rs | 17 ++++++++++++++--- 2 files changed, 18 insertions(+), 7 deletions(-) diff --git a/examples/initialised.rs b/examples/initialised.rs index 94d6d26..6d477cf 100644 --- a/examples/initialised.rs +++ b/examples/initialised.rs @@ -4,18 +4,18 @@ use std::mem; pool!(TestPool: [u32; 3], [0u32; 3]); fn main() { - let mut buffer = unsafe { Box::::new_potentially_uninit() }.unwrap(); + let mut buffer = unsafe { Box::::new_uninit() }.unwrap(); println!("Allocated new buffer, with contents: {:#x}", *buffer); *buffer = 0xf00dbabeu32; - let _buffer_2 = unsafe { Box::::new_potentially_uninit() }.unwrap(); - let _buffer_3 = unsafe { Box::::new_potentially_uninit() }.unwrap(); + let _buffer_2 = unsafe { Box::::new_uninit() }.unwrap(); + let _buffer_3 = unsafe { Box::::new_uninit() }.unwrap(); mem::drop(buffer); println!("Dropped buffer."); - let reallocated_buffer = unsafe { Box::::new_potentially_uninit() }.unwrap(); + let reallocated_buffer = unsafe { Box::::new_uninit() }.unwrap(); println!( "Reallocated buffer, with contents: 0x{:#x}", *reallocated_buffer diff --git a/src/lib.rs b/src/lib.rs index 98d8583..78ffb29 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -92,9 +92,11 @@ impl Box

{ 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 { + /// + /// # 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 { let p = match P::get().alloc() { Some(p) => p, None => return None, @@ -102,12 +104,21 @@ impl Box

{ 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 { 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) -> Self { Self { ptr } }