Make the insides of AllocationHandle private (#2332)

* Make the insides of `AllocationHandle` private

* Fix naming
This commit is contained in:
marc0246 2023-09-16 10:10:32 +02:00 committed by GitHub
parent 06f698a6be
commit e9790c1fc3
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
3 changed files with 46 additions and 13 deletions

View File

@ -717,15 +717,33 @@ pub struct MemoryAlloc {
} }
/// An opaque handle identifying an allocation inside an allocator. /// An opaque handle identifying an allocation inside an allocator.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)] #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
#[repr(transparent)] #[cfg_attr(not(doc), repr(transparent))]
pub struct AllocationHandle(pub *mut ()); pub struct AllocationHandle(*mut ());
unsafe impl Send for AllocationHandle {} unsafe impl Send for AllocationHandle {}
unsafe impl Sync for AllocationHandle {} unsafe impl Sync for AllocationHandle {}
impl AllocationHandle { impl AllocationHandle {
/// Stores a index inside an `AllocationHandle`. /// Creates a null `AllocationHandle`.
///
/// Use this if you don't have anything that you need to associate with the allocation.
#[inline]
pub const fn null() -> Self {
AllocationHandle(ptr::null_mut())
}
/// Stores a pointer in an `AllocationHandle`.
///
/// Use this if you want to associate an allocation with some (host) heap allocation.
#[inline]
pub const fn from_ptr(ptr: *mut ()) -> Self {
AllocationHandle(ptr)
}
/// Stores an index inside an `AllocationHandle`.
///
/// Use this if you want to associate an allocation with some index.
#[allow(clippy::useless_transmute)] #[allow(clippy::useless_transmute)]
#[inline] #[inline]
pub const fn from_index(index: usize) -> Self { pub const fn from_index(index: usize) -> Self {
@ -733,10 +751,26 @@ impl AllocationHandle {
AllocationHandle(unsafe { mem::transmute::<usize, *mut ()>(index) }) AllocationHandle(unsafe { mem::transmute::<usize, *mut ()>(index) })
} }
/// Retrieves a previously-stored pointer from the `AllocationHandle`.
///
/// If this handle hasn't been created using [`from_ptr`] then this will return an invalid
/// pointer, dereferencing which is undefined behavior.
///
/// [`from_ptr`]: Self::from_ptr
#[inline]
pub const fn as_ptr(self) -> *mut () {
self.0
}
/// Retrieves a previously-stored index from the `AllocationHandle`. /// Retrieves a previously-stored index from the `AllocationHandle`.
///
/// If this handle hasn't been created using [`from_index`] then this will return a bogus
/// result.
///
/// [`from_index`]: Self::from_index
#[allow(clippy::transmutes_expressible_as_ptr_casts)] #[allow(clippy::transmutes_expressible_as_ptr_casts)]
#[inline] #[inline]
pub const fn into_index(self) -> usize { pub const fn as_index(self) -> usize {
// SAFETY: `usize` and `*mut ()` have the same layout. // SAFETY: `usize` and `*mut ()` have the same layout.
unsafe { mem::transmute::<*mut (), usize>(self.0) } unsafe { mem::transmute::<*mut (), usize>(self.0) }
} }
@ -1414,7 +1448,7 @@ unsafe impl<S: Suballocator + Send + 'static> MemoryAllocator for GenericMemoryA
Ok(MemoryAlloc { Ok(MemoryAlloc {
device_memory, device_memory,
suballocation: None, suballocation: None,
allocation_handle: AllocationHandle(ptr::null_mut()), allocation_handle: AllocationHandle::null(),
}) })
} }
@ -1544,7 +1578,7 @@ impl<S: Suballocator> Block<S> {
Ok(MemoryAlloc { Ok(MemoryAlloc {
device_memory: self.device_memory.clone(), device_memory: self.device_memory.clone(),
suballocation: Some(suballocation), suballocation: Some(suballocation),
allocation_handle: AllocationHandle(self as *mut Block<S> as _), allocation_handle: AllocationHandle::from_ptr(self as *mut Block<S> as _),
}) })
} }

View File

@ -24,7 +24,6 @@ use std::{
cmp, cmp,
error::Error, error::Error,
fmt::{self, Debug, Display}, fmt::{self, Debug, Display},
ptr,
}; };
/// Suballocators are used to divide a *region* into smaller *suballocations*. /// Suballocators are used to divide a *region* into smaller *suballocations*.
@ -499,7 +498,7 @@ unsafe impl Suballocator for FreeListAllocator {
unsafe fn deallocate(&self, suballocation: Suballocation) { unsafe fn deallocate(&self, suballocation: Suballocation) {
// SAFETY: The caller must guarantee that `suballocation` refers to a currently allocated // SAFETY: The caller must guarantee that `suballocation` refers to a currently allocated
// allocation of `self`. // allocation of `self`.
let node_id = SlotId::new(suballocation.handle.into_index()); let node_id = SlotId::new(suballocation.handle.as_index());
let state = unsafe { &mut *self.state.get() }; let state = unsafe { &mut *self.state.get() };
let node = state.nodes.get_mut(node_id); let node = state.nodes.get_mut(node_id);
@ -974,7 +973,7 @@ unsafe impl Suballocator for BuddyAllocator {
#[inline] #[inline]
unsafe fn deallocate(&self, suballocation: Suballocation) { unsafe fn deallocate(&self, suballocation: Suballocation) {
let mut offset = suballocation.offset; let mut offset = suballocation.offset;
let order = suballocation.handle.into_index(); let order = suballocation.handle.as_index();
let min_order = order; let min_order = order;
let state = unsafe { &mut *self.state.get() }; let state = unsafe { &mut *self.state.get() };
@ -1159,7 +1158,7 @@ unsafe impl Suballocator for BumpAllocator {
offset, offset,
size, size,
allocation_type, allocation_type,
handle: AllocationHandle(ptr::null_mut()), handle: AllocationHandle::null(),
}) })
} }

View File

@ -109,7 +109,7 @@ use std::{
mem::ManuallyDrop, mem::ManuallyDrop,
num::NonZeroU64, num::NonZeroU64,
ops::{Bound, Range, RangeBounds, RangeTo}, ops::{Bound, Range, RangeBounds, RangeTo},
ptr::{self, NonNull}, ptr::NonNull,
sync::Arc, sync::Arc,
}; };
@ -155,7 +155,7 @@ impl ResourceMemory {
offset: 0, offset: 0,
size: device_memory.allocation_size(), size: device_memory.allocation_size(),
allocation_type: AllocationType::Unknown, allocation_type: AllocationType::Unknown,
allocation_handle: AllocationHandle(ptr::null_mut()), allocation_handle: AllocationHandle::null(),
suballocation_handle: None, suballocation_handle: None,
allocator: None, allocator: None,
device_memory: ManuallyDrop::new(DeviceOwnedDebugWrapper(device_memory)), device_memory: ManuallyDrop::new(DeviceOwnedDebugWrapper(device_memory)),