Honeycomb  0.1
Component-Model Framework
Lazy.h
Go to the documentation of this file.
1 // Honeycomb, Copyright (C) 2015 NewGamePlus Inc. Distributed under the Boost Software License v1.0.
2 #pragma once
3 
5 
6 namespace honey
7 {
8 
10 template<class T, class Eval = function<void(T&)>, class Pred = function<bool()>>
11 class lazy
12 {
13 public:
22  lazy(const Eval& eval = nullptr, const Pred& pred = nullptr)
23  : _dirty(true), _pred(pred), _eval(eval) {}
24 
25  void setDirty(bool dirty) { _dirty = dirty; }
26  bool isDirty() const { return _dirty; }
27 
28  void setPred(const Pred& pred) { _pred = pred; }
29  void setEval(const Eval& eval) { _eval = eval; }
30 
32  const T& raw() const { return _val; }
33  T& raw() { return _val; }
34 
36  const T& operator*() const { return get(); }
37  T& operator*() { return get(); }
38  const T* operator->() const { return &get(); }
39  T* operator->() { return &get(); }
41  operator const T&() const { return get(); }
42  operator T&() { return get(); }
43 
45  template<class... Args>
46  T& get(Args&&... args)
47  {
48  SpinLock::Scoped _(_lock);
49  if (!(isDirty() || (_pred && _pred(args...)))) return _val;
50  _eval(_val, args...);
51  _dirty = false;
52  return _val;
53  }
54 
55  template<class... Args>
56  const T& get(Args&&... args) const { return const_cast<lazy*>(this)->get(forward<Args>(args)...); }
57 
58 private:
59  T _val;
60  Atomic<bool> _dirty;
61  Pred _pred;
62  Eval _eval;
63  SpinLock _lock;
64 };
65 
67 
68 template<class Eval>
69 auto lazyCreate(Eval&& eval) -> lazy<decltype(eval())>
70 {
71  typedef decltype(eval()) R;
72  return lazy<R>([=](R& val) mutable { val = eval(); });
73 }
74 
75 }
lazy(const Eval &eval=nullptr, const Pred &pred=nullptr)
Definition: Lazy.h:22
A thread lock where the lock is acquired through a busy wait loop.
Definition: Spin.h:17
Wraps a value so that it is calculated only when needed. A lock synchronizes access.
Definition: Lazy.h:11
auto lazyCreate(Eval &&eval) -> lazy< decltype(eval())>
Create a lazy value from a function that returns a value. Ex. auto lazy = lazyCreate([] { return T();...
Definition: Lazy.h:69
bool isDirty() const
Definition: Lazy.h:26
void setDirty(bool dirty)
Definition: Lazy.h:25
T & operator*()
Definition: Lazy.h:37
T & raw()
Definition: Lazy.h:33
static auto _
Definition: Module.cpp:8
T * operator->()
Definition: Lazy.h:39
void setPred(const Pred &pred)
Definition: Lazy.h:28
const T * operator->() const
Definition: Lazy.h:38
void setEval(const Eval &eval)
Definition: Lazy.h:29
const T & operator*() const
Evaluate the lazy value.
Definition: Lazy.h:36
const T & raw() const
Direct access to the wrapped value (ie. does not evaluate)
Definition: Lazy.h:32
Global Honeycomb namespace.