Advertisement
Guest User

Untitled

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