Skip to content

Instantly share code, notes, and snippets.

@techgeek1
Created April 26, 2019 20:09
Show Gist options
  • Save techgeek1/6ee4442764a968e4c0c98058a7a97daa to your computer and use it in GitHub Desktop.
Save techgeek1/6ee4442764a968e4c0c98058a7a97daa to your computer and use it in GitHub Desktop.
A lazily evaluated value store
use std::cell::Cell;
/// A thunk used for lazy generation and caching of values
struct Thunk<T: Copy> {
/// Cached value stored in the thunk
value: Cell<Option<T>>,
/// Generator function to generate a missing value
generator: fn() -> T
}
impl<T: Copy> Thunk<T> {
/// Create a new thunk with the provided generator
pub fn new(generator: fn() -> T) -> Self {
Self {
value: Cell::new(None),
generator: generator
}
}
/// Get the value of this thunk, create it from the generator if not already generated
pub fn value(&self) -> T {
if self.value.get().is_none() {
self.value.set(
Some((self.generator)())
);
}
self.value.get()
.unwrap()
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment