Skip to content

Commit

Permalink
Added LockedBox::try_new
Browse files Browse the repository at this point in the history
Closes #1
  • Loading branch information
ecton committed Jul 14, 2024
1 parent 35f0571 commit 61ad0e3
Show file tree
Hide file tree
Showing 4 changed files with 26 additions and 9 deletions.
7 changes: 7 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,13 @@ All notable changes to this project will be documented in this file.
The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).

## 0.1.2

### Added

- `LockedBox::try_new` returns `None` if the allocation is too large or
an out of memory error.

## 0.1.1

### Added
Expand Down
10 changes: 5 additions & 5 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 1 addition & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
[package]
name = "lockedbox"
version = "0.1.1"
version = "0.1.2"
description = "A Box-like type that prevents paging its contents to disk."
edition = "2021"
license = "MIT OR Apache-2.0"
Expand Down
16 changes: 13 additions & 3 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -24,13 +24,23 @@ impl<T> LockedBox<T> {
///
/// # Panics
///
/// This function panics If `size_of::<T>() >= usize::MAX - 4 * PAGE_SIZE`.
/// This function panics if `size_of::<T>() >= usize::MAX - 4 * PAGE_SIZE`
/// or the underlying allocation fails.
pub fn new(contained: T) -> Self {
Self::try_new(contained).expect("allocation too large")
}

/// Creates a new locked box with `contained` in a newly allocated,
/// `mlock`-protected region of memory.
///
/// Returns `None` if `size_of::<T>() >= usize::MAX - 4 * PAGE_SIZE` or the
/// underlying allocation fails.
pub fn try_new(contained: T) -> Option<Self> {
// SAFETY: no references are made to the data contained by the allocated
// memory until after `contained` as been written. The size of the
// allocation is checked by `memsec`.
let memory = unsafe {
let memory = memsec::malloc::<T>().expect("allocation too large");
let memory = memsec::malloc::<T>()?;
// It is important to lock the memory before storing the value,
// otherwise the process could be preempted between the write and
// the mlock calls, and the memory theoretically could be paged to
Expand All @@ -41,7 +51,7 @@ impl<T> LockedBox<T> {
ptr::write(memory.as_ptr(), contained);
memory
};
Self(memory)
Some(Self(memory))
}

/// Returns the pointer to the underlying data.
Expand Down

0 comments on commit 61ad0e3

Please sign in to comment.