]> git.localhorst.tv Git - l2e.git/blob - src/app/Timer.h
added timer facility
[l2e.git] / src / app / Timer.h
1 /*
2  * Timer.h
3  *
4  *  Created on: Aug 10, 2012
5  *      Author: holy
6  */
7
8 #ifndef APP_TIMER_H_
9 #define APP_TIMER_H_
10
11 #include <algorithm>
12 #include <list>
13
14 namespace app {
15
16 template<class Time>
17 struct TimerData {
18
19         TimerData() : time(0), target(0), refCount(0) { }
20         TimerData(Time target) : time(0), target(target), refCount(0) { }
21
22         Time time;
23         Time target;
24         int refCount;
25
26 };
27
28
29 template<class Time>
30 class Timer {
31
32 public:
33         Timer() : data(0) { }
34         ~Timer() { if (data) --data->refCount; }
35         Timer(TimerData<Time> *data) : data(data) { ++data->refCount; }
36         Timer(const Timer<Time> &other)
37         : data(other.data) { if (data) ++(data->refCount); }
38         Timer<Time> &operator =(const Timer<Time> &other) {
39                 Timer<Time> temp(other);
40                 Swap(temp);
41                 return *this;
42         }
43         void Swap(Timer<Time> &other) {
44                 std::swap(data, other.data);
45         }
46
47 public:
48         bool Running() const {
49                 return data;
50         }
51         bool Finished() const {
52                 return data ? data->time >= data->target : false;
53         }
54         Time Elapsed() const {
55                 return data ? data->time : Time();
56         }
57         Time Remaining() const {
58                 return data ? (data->target - data->time) : Time();
59         }
60
61 private:
62         TimerData<Time> *data;
63
64 };
65
66
67 template<class Time>
68 class Timers {
69
70 public:
71         Timers() { }
72
73 public:
74         void Update(Time delta) {
75                 for (typename std::list<TimerData<Time> >::iterator i(data.begin()), end(data.end()); i != end;) {
76                         i->time += delta;
77                         if (i->refCount <= 0) {
78                                 i = data.erase(i);
79                         } else {
80                                 ++i;
81                         }
82                 }
83         }
84         Timer<Time> StartTimer() {
85                 data.push_back(TimerData<Time>());
86                 return Timer<Time>(&data.back());
87         }
88         Timer<Time> StartCountdown(Time duration) {
89                 data.push_back(TimerData<Time>(duration));
90                 return Timer<Time>(&data.back());
91         }
92
93 private:
94         std::list<TimerData<Time> > data;
95
96 };
97
98 }
99
100 #endif /* APP_TIMER_H_ */