Struct vectorscan::alloc::LayoutTracker
source · pub struct LayoutTracker { /* private fields */ }
Available on crate feature
alloc
only.Expand description
An adapter for GlobalAlloc
instances to implement
MallocLikeAllocator
.
This struct also supports introspecting the current allocation table with
Self::current_allocations()
:
use vectorscan::alloc::{LayoutTracker, MallocLikeAllocator};
use std::{slice, alloc::System};
let tracker = LayoutTracker::new(System.into());
let p1 = tracker.allocate(32).unwrap();
let p2 = tracker.allocate(64).unwrap();
let allocs = tracker.current_allocations();
assert_eq!(allocs.len(), 2);
let (p1_p, p1_layout) = allocs[0];
let (p2_p, p2_layout) = allocs[1];
// The pointer value is the same as that returned by the allocate method:
assert!(p1_p == p1);
assert!(p2_p == p2);
// The requested alignment is always 8:
assert!(p1_layout.align() == 8);
assert!(p2_layout.align() == 8);
// The size itself may differ per allocation, though:
assert!(p1_layout.size() == 32);
assert!(p2_layout.size() == 64);
// Note that modifying pointers in use by other threads may cause race conditions
// and undefined behavior!
let s1 = unsafe { slice::from_raw_parts_mut(p1_p.as_ptr(), p1_layout.size()) };
s1[..5].copy_from_slice(b"hello");
let s2 = unsafe { slice::from_raw_parts_mut(p2_p.as_ptr(), p2_layout.size()) };
s2[..5].copy_from_slice(&s1[..5]);
assert_eq!(&s2[..5], b"hello");
// Free memory when done:
tracker.deallocate(p1);
tracker.deallocate(p2);
Implementations§
source§impl LayoutTracker
impl LayoutTracker
sourcepub fn new(allocator: Arc<impl GlobalAlloc + 'static>) -> Self
pub fn new(allocator: Arc<impl GlobalAlloc + 'static>) -> Self
Create a new allocation mapping which records the Layout
argument for
each allocation that goes to the underlying allocator
.
sourcepub fn current_allocations(&self) -> Vec<(NonNull<u8>, Layout)>
pub fn current_allocations(&self) -> Vec<(NonNull<u8>, Layout)>
Get a copy of the current live allocation mapping given a reference to this allocator.
This struct makes use of an RwLock
to allow concurrent access. Note
that pointers may not be safe to dereference if they are freed after this
method is called!
Trait Implementations§
source§impl MallocLikeAllocator for LayoutTracker
impl MallocLikeAllocator for LayoutTracker
LayoutTracker
implements three additional guarantees over the base
MallocLikeAllocator
:
- 0-size allocation requests always return
None
instead of allocating. - all allocations are aligned to at least 8 bytes.
- attempted double frees will panic instead.
impl Send for LayoutTracker
impl Sync for LayoutTracker
Auto Trait Implementations§
impl !RefUnwindSafe for LayoutTracker
impl Unpin for LayoutTracker
impl !UnwindSafe for LayoutTracker
Blanket Implementations§
source§impl<T> BorrowMut<T> for Twhere
T: ?Sized,
impl<T> BorrowMut<T> for Twhere
T: ?Sized,
source§fn borrow_mut(&mut self) -> &mut T
fn borrow_mut(&mut self) -> &mut T
Mutably borrows from an owned value. Read more