1 | // Copyright 2013 The Flutter Authors. All rights reserved. |
---|---|
2 | // Use of this source code is governed by a BSD-style license that can be |
3 | // found in the LICENSE file. |
4 | |
5 | #ifndef FLUTTER_FML_TIME_TIME_POINT_H_ |
6 | #define FLUTTER_FML_TIME_TIME_POINT_H_ |
7 | |
8 | #include <cstdint> |
9 | #include <functional> |
10 | #include <iosfwd> |
11 | |
12 | #include "flutter/fml/time/time_delta.h" |
13 | |
14 | namespace fml { |
15 | |
16 | // A TimePoint represents a point in time represented as an integer number of |
17 | // nanoseconds elapsed since an arbitrary point in the past. |
18 | // |
19 | // WARNING: This class should not be serialized across reboots, or across |
20 | // devices: the reference point is only stable for a given device between |
21 | // reboots. |
22 | class TimePoint { |
23 | public: |
24 | using ClockSource = TimePoint (*)(); |
25 | |
26 | // Default TimePoint with internal value 0 (epoch). |
27 | constexpr TimePoint() = default; |
28 | |
29 | static void SetClockSource(ClockSource source); |
30 | |
31 | static TimePoint Now(); |
32 | |
33 | static TimePoint CurrentWallTime(); |
34 | |
35 | static constexpr TimePoint Min() { |
36 | return TimePoint(std::numeric_limits<int64_t>::min()); |
37 | } |
38 | |
39 | static constexpr TimePoint Max() { |
40 | return TimePoint(std::numeric_limits<int64_t>::max()); |
41 | } |
42 | |
43 | static constexpr TimePoint FromEpochDelta(TimeDelta ticks) { |
44 | return TimePoint(ticks.ToNanoseconds()); |
45 | } |
46 | |
47 | // Expects ticks in nanos. |
48 | static constexpr TimePoint FromTicks(int64_t ticks) { |
49 | return TimePoint(ticks); |
50 | } |
51 | |
52 | TimeDelta ToEpochDelta() const { return TimeDelta::FromNanoseconds(nanos: ticks_); } |
53 | |
54 | // Compute the difference between two time points. |
55 | TimeDelta operator-(TimePoint other) const { |
56 | return TimeDelta::FromNanoseconds(nanos: ticks_ - other.ticks_); |
57 | } |
58 | |
59 | TimePoint operator+(TimeDelta duration) const { |
60 | return TimePoint(ticks_ + duration.ToNanoseconds()); |
61 | } |
62 | TimePoint operator-(TimeDelta duration) const { |
63 | return TimePoint(ticks_ - duration.ToNanoseconds()); |
64 | } |
65 | |
66 | bool operator==(TimePoint other) const { return ticks_ == other.ticks_; } |
67 | bool operator!=(TimePoint other) const { return ticks_ != other.ticks_; } |
68 | bool operator<(TimePoint other) const { return ticks_ < other.ticks_; } |
69 | bool operator<=(TimePoint other) const { return ticks_ <= other.ticks_; } |
70 | bool operator>(TimePoint other) const { return ticks_ > other.ticks_; } |
71 | bool operator>=(TimePoint other) const { return ticks_ >= other.ticks_; } |
72 | |
73 | private: |
74 | explicit constexpr TimePoint(int64_t ticks) : ticks_(ticks) {} |
75 | |
76 | int64_t ticks_ = 0; |
77 | }; |
78 | |
79 | } // namespace fml |
80 | |
81 | #endif // FLUTTER_FML_TIME_TIME_POINT_H_ |
82 |