4 * Created on: Aug 10, 2012
20 TimerData() : time(0), target(0), refCount(0), justHit(false), repeat(false) { }
21 TimerData(Time target, bool repeat) : time(0), target(target), refCount(0), justHit(false), repeat(repeat) { }
37 ~Timer() { if (data) --data->refCount; }
38 Timer(TimerData<Time> *data) : data(data) { ++data->refCount; }
39 Timer(const Timer<Time> &other)
40 : data(other.data) { if (data) ++(data->refCount); }
41 Timer<Time> &operator =(const Timer<Time> &other) {
42 Timer<Time> temp(other);
46 void Swap(Timer<Time> &other) {
47 std::swap(data, other.data);
51 bool Started() const {
54 bool Finished() const {
55 return data && data->target != Time() && !data->repeat && data->time >= data->target;
57 bool Running() const {
58 return data && !Finished();
60 Time Elapsed() const {
61 return data ? data->time : Time();
63 Time Remaining() const {
64 return data ? (data->target - data->time) : Time();
66 int Iteration() const {
67 return (data && data->target > Time()) ? std::floor(data->time / data->target) : Time();
69 bool JustHit() const {
70 return data && data->justHit;
80 if (data) data->time = Time();
84 if (data->target > Time() && data->justHit) {
85 data->time -= data->target;
93 TimerData<Time> *data;
105 void Update(Time delta) {
106 for (typename std::list<TimerData<Time> >::iterator i(data.begin()), end(data.end()); i != end;) {
108 Time intervalTime(i->time);
109 if (i->repeat) while (intervalTime > i->target) intervalTime -= i->target;
110 i->justHit = intervalTime < i->target && intervalTime + delta >= i->target;
113 if (i->refCount <= 0) {
120 Timer<Time> StartTimer() {
121 data.push_back(TimerData<Time>());
122 return Timer<Time>(&data.back());
124 Timer<Time> StartCountdown(Time duration) {
125 data.push_back(TimerData<Time>(duration, false));
126 return Timer<Time>(&data.back());
128 Timer<Time> StartInterval(Time duration) {
129 data.push_back(TimerData<Time>(duration, true));
130 return Timer<Time>(&data.back());
134 std::list<TimerData<Time> > data;
140 #endif /* APP_TIMER_H_ */