Created
April 26, 2019 20:09
-
-
Save techgeek1/6ee4442764a968e4c0c98058a7a97daa to your computer and use it in GitHub Desktop.
A lazily evaluated value store
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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