diff options
Diffstat (limited to 'core/time.hpp')
-rw-r--r-- | core/time.hpp | 98 |
1 files changed, 98 insertions, 0 deletions
diff --git a/core/time.hpp b/core/time.hpp new file mode 100644 index 0000000..827772b --- /dev/null +++ b/core/time.hpp @@ -0,0 +1,98 @@ +#ifndef yg0goL5EwkwiF99Qqt5ozzKAq9U +#define yg0goL5EwkwiF99Qqt5ozzKAq9U + +#include <assert.h> +#include <math.h> +#include <iostream> +#include <limits> + +struct Time { + typedef double type; + type time; + + Time() {} + Time(type time) : time(time) {} + +#define Op(op) \ + Time operator op (const Time & arg) const { return Time(time op arg.time); } \ + Time& operator op##= (const Time & arg) { time op##= arg.time; return *this; } + Op(+); + Op(-); + Op(*); + Op(/); + // Op(%); +#undef Op + // WARN: wrong for time/t < epsilon + inline unsigned long ceilDiv(const Time & t) const { return ceil(time / t.time); } + + +#define CmpOp(op) inline bool operator op (const Time & arg) const \ + { return time op arg.time; } + CmpOp(==); + CmpOp(!=); + CmpOp(<=); + CmpOp(>=); + CmpOp(<); + CmpOp(>); +#undef CmpOp + + void operator= (type t) { time = t; } + + inline type operator() () const { return time; } + + // used as a hack in creating global events; see event_intent.hpp + static inline Time never() { + return Time(std::numeric_limits<type>::infinity()); + } + + static inline Time beforeAll() { + return Time(- std::numeric_limits<type>::infinity()); + } + + // a small value, large enough that t + epsilon > t will always hold + // during sane simulations + static inline Time epsilon() { + return Time(0.000001); // leaves approx. 10 digits for time + } +}; + +namespace std { + ostream& operator<< (ostream &os, Time val) { + return os << val.time; + } +} + + +struct TimeSpan { + TimeSpan(Time start, Time end, Time delta) : start(start), end(end), delta(delta) { + assert(start <= end); + assert(delta > 0); + }; + Time start, end, delta; + + struct iterator { + const TimeSpan &timeSpan; + Time current; + + iterator(TimeSpan &parent) : timeSpan(parent), current(timeSpan.start) {} + + bool hasNext() { return current < timeSpan.end; } + Time & operator() () { return current; } + iterator & operator++() { current = fmin(current.time + timeSpan.delta.time, timeSpan.end.time); return *this; } + }; + + iterator begin() { return iterator(*this); } +}; + +struct FakeTime { + FakeTime() {} + FakeTime(const Time) {}; +}; + +namespace std { + ostream& operator<< (ostream &os, FakeTime val) { + return os << "(FakeTime)"; + } +} + +#endif // yg0goL5EwkwiF99Qqt5ozzKAq9U |