Skip to content

Commit

Permalink
feat: Add get method for Copy types
Browse files Browse the repository at this point in the history
  • Loading branch information
novacrazy committed Feb 24, 2017
1 parent cac11a4 commit dc8f820
Showing 1 changed file with 36 additions and 0 deletions.
36 changes: 36 additions & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -105,6 +105,16 @@ impl<T> LazyCell<T> {
}
}

impl<T: Copy> LazyCell<T> {
/// Returns a copy of the contents of the lazy cell.
///
/// This function will return `Some` if the cell has been previously initialized,
/// and `None` if it has not yet been initialized.
pub fn get(&self) -> Option<T> {
unsafe { *self.inner.get() }
}
}

// Tracks the AtomicLazyCell inner state
const NONE: usize = 0;
const LOCK: usize = 1;
Expand Down Expand Up @@ -165,7 +175,21 @@ impl<T> AtomicLazyCell<T> {
}
}

impl<T: Copy> AtomicLazyCell<T> {
/// Returns a copy of the contents of the lazy cell.
///
/// This function will return `Some` if the cell has been previously initialized,
/// and `None` if it has not yet been initialized.
pub fn get(&self) -> Option<T> {
match self.state.load(Ordering::Acquire) {
SOME => unsafe { *self.inner.get() },
_ => None,
}
}
}

unsafe impl<T: Sync> Sync for AtomicLazyCell<T> {}

unsafe impl<T: Send> Send for AtomicLazyCell<T> {}

#[cfg(test)]
Expand All @@ -178,6 +202,9 @@ mod tests {

let value = lazycell.borrow();
assert_eq!(value, None);

let value = lazycell.get();
assert_eq!(value, None);
}

#[test]
Expand All @@ -190,6 +217,9 @@ mod tests {

let value = lazycell.borrow();
assert_eq!(value, Some(&1));

let value = lazycell.get();
assert_eq!(value, Some(1));
}

#[test]
Expand Down Expand Up @@ -242,6 +272,9 @@ mod tests {

let value = lazycell.borrow();
assert_eq!(value, None);

let value = lazycell.get();
assert_eq!(value, None);
}

#[test]
Expand All @@ -254,6 +287,9 @@ mod tests {

let value = lazycell.borrow();
assert_eq!(value, Some(&1));

let value = lazycell.get();
assert_eq!(value, Some(1));
}

#[test]
Expand Down

0 comments on commit dc8f820

Please sign in to comment.