pub struct WeakAlloc<A> { /* private fields */ }
Expand description
A custom allocator that can be given ownership of data, returning a WeakRef
.
Implementations§
Source§impl<A> WeakAlloc<A>where
A: GlobalAlloc + Clone,
impl<A> WeakAlloc<A>where
A: GlobalAlloc + Clone,
Sourcepub fn give<T: Send + Sync + 'static>(&self, element: T) -> WeakRef<T, A>
pub fn give<T: Send + Sync + 'static>(&self, element: T) -> WeakRef<T, A>
Give ownership of a value to the allocator. The value may be deallocated at any time if no other strong references to it exist.
Returns a WeakRef that can be used to get back an Arc in the future using the upgrade method, if the value still exists.
Because of the way Arc is implemented, prefer giving T where the size of T is small. Otherwise the backing allocation will not be deallocated when dropping the Arc, it will only be deallocated after all the weak references go out of scope. So [u8; 1000] is bad, but Box<[u8; 1000]> and Vec<[u8; 1000]> are good.
Sourcepub fn give_and_upgrade<T: Send + Sync + 'static>(
&self,
element: T,
) -> ArcRef<T, A>
pub fn give_and_upgrade<T: Send + Sync + 'static>( &self, element: T, ) -> ArcRef<T, A>
Alternative to A.give(x).upgrade().unwrap()
that never fails. There is a race condition
in that snippet if another thread fills the memory causing the allocator to call
WEAK_LIST.pop_lru()
after the call to give
but before the call to upgrade
.
That race condition is avoided in this method by holding the lock slightly longer, so that
no other thread can modify the list before we upgrade to an ArcRef.
pub fn upgrade<T: Send + Sync + 'static>( &self, w: &WeakRef<T, A>, ) -> Option<ArcRef<T, A>>
Sourcepub fn clear(&self)
pub fn clear(&self)
Remove all the weak references from the WeakAlloc. This will deallocate all the WeakRefs that do not have an active ArcRef.
Sourcepub unsafe fn weak_alloc(&self, layout: Layout) -> *mut u8
pub unsafe fn weak_alloc(&self, layout: Layout) -> *mut u8
Try to allocate some memory without freeing any existing weak allocations. This can be used
to implement the equivalent to try_give
: try to allocate a box with some contents but
only if there is enough memory. If there isn’t enough memory this method will return a null
pointer and the code needed to initialize the box can be skipped (using give
forces you
to initialize the value).
§Safety
The same restrictions as GlobalAlloc::alloc
.
Trait Implementations§
Source§impl<A> GlobalAlloc for WeakAlloc<A>where
A: GlobalAlloc,
impl<A> GlobalAlloc for WeakAlloc<A>where
A: GlobalAlloc,
Source§unsafe fn alloc(&self, layout: Layout) -> *mut u8
unsafe fn alloc(&self, layout: Layout) -> *mut u8
layout
. Read more