| 1 | #ifndef _WIN32 |
| 2 | |
| 3 | #include "timestamp.h" |
| 4 | #include "timeconv.h" |
| 5 | |
| 6 | void get_current_time(timespec *ts) { |
| 7 | // CLOCK_MONOTONIC ensures that we never get timestamps that go backward in |
| 8 | // time due to clock adjustment. https://github.com/r-lib/later/issues/150 |
| 9 | clock_gettime(CLOCK_MONOTONIC, ts); |
| 10 | } |
| 11 | |
| 12 | class TimestampImplPosix : public TimestampImpl { |
| 13 | private: |
| 14 | timespec time; |
| 15 | |
| 16 | public: |
| 17 | TimestampImplPosix() { |
| 18 | get_current_time(&this->time); |
| 19 | } |
| 20 | |
| 21 | TimestampImplPosix(double secs) { |
| 22 | get_current_time(&this->time); |
| 23 | |
| 24 | this->time = addSeconds(this->time, secs); |
| 25 | } |
| 26 | |
| 27 | virtual bool future() const { |
| 28 | timespec now; |
| 29 | get_current_time(&now); |
| 30 | return this->time.tv_sec > now.tv_sec || |
| 31 | (this->time.tv_sec == now.tv_sec && this->time.tv_nsec > now.tv_nsec); |
| 32 | } |
| 33 | |
| 34 | virtual bool less(const TimestampImpl* other) const { |
| 35 | const TimestampImplPosix* other_impl = dynamic_cast<const TimestampImplPosix*>(other); |
| 36 | return this->time.tv_sec < other_impl->time.tv_sec || |
| 37 | (this->time.tv_sec == other_impl->time.tv_sec && this->time.tv_nsec < other_impl->time.tv_nsec); |
| 38 | } |
| 39 | |
| 40 | virtual bool greater(const TimestampImpl* other) const { |
| 41 | const TimestampImplPosix* other_impl = dynamic_cast<const TimestampImplPosix*>(other); |
| 42 | return this->time.tv_sec > other_impl->time.tv_sec || |
| 43 | (this->time.tv_sec == other_impl->time.tv_sec && this->time.tv_nsec > other_impl->time.tv_nsec); |
| 44 | } |
| 45 | |
| 46 | virtual double diff_secs(const TimestampImpl* other) const { |
| 47 | const TimestampImplPosix* other_impl = dynamic_cast<const TimestampImplPosix*>(other); |
| 48 | double sec_diff = this->time.tv_sec - other_impl->time.tv_sec; |
| 49 | sec_diff += (this->time.tv_nsec - other_impl->time.tv_nsec) / 1.0e9; |
| 50 | return sec_diff; |
| 51 | } |
| 52 | }; |
| 53 | |
| 54 | Timestamp::Timestamp() : p_impl(new TimestampImplPosix()) {} |
| 55 | Timestamp::Timestamp(double secs) : p_impl(new TimestampImplPosix(secs)) {} |
| 56 | |
| 57 | #endif // _WIN32 |