Skip to content

Commit

Permalink
Cleaner APIs
Browse files Browse the repository at this point in the history
Signed-off-by: Moritz Hoffmann <antiguru@gmail.com>
  • Loading branch information
antiguru committed Jan 25, 2024
1 parent 0c3dab0 commit 5031ba1
Showing 1 changed file with 23 additions and 12 deletions.
35 changes: 23 additions & 12 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,12 +51,9 @@ unsafe impl Sync for Handle {}

#[allow(clippy::len_without_is_empty)]
impl Handle {
fn new(region: &mut [u8]) -> Self {
Self {
// SAFETY: `region` known to point to valid memory.
ptr: unsafe { NonNull::new_unchecked(region.as_mut_ptr()) },
len: region.len(),
}
/// Construct a new handle from a region of memory
fn new(ptr: NonNull<u8>, len: usize) -> Self {
Self { ptr, len }
}

/// Construct a dangling handle, which is only suitable for zero-sized types.
Expand All @@ -72,12 +69,12 @@ impl Handle {
}

/// Length of the memory area in bytes.
pub fn len(&self) -> usize {
fn len(&self) -> usize {
self.len
}

/// Pointer to memory.
pub fn as_non_null(&self) -> NonNull<u8> {
fn as_non_null(&self) -> NonNull<u8> {
self.ptr
}

Expand Down Expand Up @@ -450,11 +447,23 @@ impl LocalSizeClass {
);

let mut mmap = Self::init_file(byte_len)?;
let mut chunks = mmap.as_mut().chunks_exact_mut(self.size_class.byte_size());
let mem = Handle::new(chunks.next().expect("At least once chunk allocated."));
for slice in chunks {
self.size_class_state.injector.push(Handle::new(slice));
// SAFETY: Memory region initialized, so pointers to it are valid.
let mut chunks = mmap
.as_mut()
.chunks_exact_mut(self.size_class.byte_size())
.map(|chunk| unsafe { NonNull::new_unchecked(chunk.as_mut_ptr()) });

// Capture first region to return immediately.
let ptr = chunks.next().expect("At least once chunk allocated.");
let mem = Handle::new(ptr, self.size_class.byte_size());

// Stash remaining in the injector.
for ptr in chunks {
self.size_class_state
.injector
.push(Handle::new(ptr, self.size_class.byte_size()));
}

stash.push(ManuallyDrop::new(mmap));
Ok(mem)
}
Expand Down Expand Up @@ -517,6 +526,7 @@ impl Drop for LocalSizeClass {
}
}

/// Access the per-thread context.
fn thread_context<R, F: FnOnce(&mut ThreadLocalStealer) -> R>(f: F) -> R {
WORKER.with(|cell| f(&mut cell.borrow_mut()))
}
Expand Down Expand Up @@ -564,6 +574,7 @@ pub fn deallocate(handle: Handle) {
thread_context(|s| s.free(handle))
}

/// A bacground worker that performs periodic tasks.
struct BackgroundWorker {
config: BackgroundWorkerConfig,
receiver: Receiver<BackgroundWorkerConfig>,
Expand Down

0 comments on commit 5031ba1

Please sign in to comment.