Advertisement
Guest User

Untitled

a guest
Aug 19th, 2019
116
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 0.99 KB | None | 0 0
  1. use std::hint;
  2.  
  3. pub struct Cache<F, V>
  4. where F: FnOnce() -> V
  5. {
  6. calculation_fn: Option<F>,
  7. value: Option<V>,
  8. }
  9.  
  10. impl<F, V> Cache<F, V>
  11. where F: FnOnce() -> V
  12. {
  13. pub fn new(calculation: F) -> Cache<F, V> {
  14. Cache {
  15. calculation_fn: Some(calculation),
  16. value: None,
  17. }
  18. }
  19.  
  20. pub fn value(&mut self) -> &V {
  21. match &self.value {
  22. None => {
  23. let calculation_fn = self.calculation_fn.take().unwrap();
  24. let calculation = (calculation_fn)();
  25. self.value = Some(calculation);
  26. ()
  27. },
  28. _ => (),
  29. };
  30.  
  31. match &self.value {
  32. Some(ref v) => v,
  33. None => unsafe { hint::unreachable_unchecked() },
  34. }
  35. }
  36. }
  37.  
  38. fn main() {
  39. let mut counter = 0;
  40. let mut sut = Cache::new(|| {
  41. counter += 1;
  42. 42
  43. });
  44.  
  45. sut.value();
  46. sut.value();
  47.  
  48. assert_eq!(42, *sut.value());
  49. assert_eq!(counter, 1);
  50. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement