Skip to content

Commit

Permalink
Bound the contained type with sync.
Browse files Browse the repository at this point in the history
Lazy<Cell<T>> would be a bad idea.
  • Loading branch information
khuey committed Jan 28, 2017
1 parent 63b6be8 commit 512bec5
Show file tree
Hide file tree
Showing 3 changed files with 25 additions and 8 deletions.
2 changes: 1 addition & 1 deletion 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
Expand Up @@ -5,7 +5,7 @@ description = "Lazy initialization."
keywords = ["lazy", "initialization"]
license = "Apache-2.0/MIT"
repository = "https://github.com/khuey/lazy-init"
version = "0.1.0"
version = "0.1.1"

[dev-dependencies]
scoped-pool = "1.0.0"
29 changes: 23 additions & 6 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,14 +22,20 @@ enum ThisOrThat<T, U> {

/// `LazyTransform<T, U>` is a synchronized holder type, that holds a value of
/// type T until it is lazily converted into a value of type U.
pub struct LazyTransform<T, U> {
pub struct LazyTransform<T, U>
where T: Sync,
U: Sync
{
initialized: AtomicBool,
lock: Mutex<()>,
value: UnsafeCell<Option<ThisOrThat<T, U>>>,
}

// Implementation details.
impl<T, U> LazyTransform<T, U> {
impl<T, U> LazyTransform<T, U>
where T: Sync,
U: Sync
{
fn extract<'a>(&'a self) -> Option<&'a U> {
// Make sure we're initialized first!
match unsafe { (*self.value.get()).as_ref() } {
Expand All @@ -41,7 +47,10 @@ impl<T, U> LazyTransform<T, U> {
}

// Public API.
impl<T, U> LazyTransform<T, U> {
impl<T, U> LazyTransform<T, U>
where T: Sync,
U: Sync
{
/// Construct a new, untransformed `LazyTransform<T, U>` with an argument of
/// type T.
pub fn new(t: T) -> LazyTransform<T, U> {
Expand Down Expand Up @@ -103,15 +112,23 @@ impl<T, U> LazyTransform<T, U> {
}
}

unsafe impl<T, U> Sync for LazyTransform<T, U> {}
unsafe impl<T, U> Sync for LazyTransform<T, U>
where T: Sync,
U: Sync
{
}

/// `Lazy<T>` is a lazily initialized synchronized holder type. You can think
/// of it as a LazyTransform where the initial type doesn't exist.
pub struct Lazy<T> {
pub struct Lazy<T>
where T: Sync
{
inner: LazyTransform<(), T>,
}

impl<T> Lazy<T> {
impl<T> Lazy<T>
where T: Sync
{
/// Construct a new, uninitialized `Lazy<T>`.
pub fn new() -> Lazy<T> {
Lazy { inner: LazyTransform::new(()) }
Expand Down

0 comments on commit 512bec5

Please sign in to comment.