Vanetza
 
Loading...
Searching...
No Matches
timestamp.cpp
1#include "timestamp.hpp"
2#include "vanetza/common/byte_order.hpp"
3#include <boost/date_time/gregorian/gregorian.hpp>
4#include <cassert>
5#include <chrono>
6#include <limits>
7
8namespace vanetza
9{
10namespace geonet
11{
12
13Timestamp::unit_type Timestamp::millisecond()
14{
15 return Timestamp::unit_type();
16}
17
18boost::posix_time::ptime Timestamp::start_time()
19{
20 static const boost::posix_time::ptime start {
21 boost::gregorian::date(2004, 1, 1),
22 boost::posix_time::milliseconds(0)
23 };
24 return start;
25}
26
27Timestamp::Timestamp(const Clock::time_point& time)
28{
29 using namespace std::chrono;
30 const auto since_epoch = time.time_since_epoch();
31 const auto since_epoch_ms = duration_cast<milliseconds>(since_epoch);
32 m_timestamp = since_epoch_ms.count() * absolute_unit_type();
33}
34
35Timestamp::Timestamp(const boost::posix_time::ptime& time)
36{
37 assert(time >= start_time());
38 const value_type since_start_ms = (time - start_time()).total_milliseconds();
39 m_timestamp = since_start_ms * absolute_unit_type();
40}
41
42Timestamp& Timestamp::operator+=(duration_type rhs)
43{
44 m_timestamp += rhs;
45 return *this;
46}
47
48Timestamp& Timestamp::operator-=(duration_type rhs)
49{
50 m_timestamp -= rhs;
51 return *this;
52}
53
54Timestamp operator+(Timestamp lhs, Timestamp::duration_type rhs)
55{
56 lhs += rhs;
57 return lhs;
58}
59
60Timestamp operator-(Timestamp lhs, Timestamp::duration_type rhs)
61{
62 lhs -= rhs;
63 return lhs;
64}
65
66Timestamp::duration_type operator-(Timestamp lhs, Timestamp rhs)
67{
68 return lhs.quantity() - rhs.quantity();
69}
70
71bool Timestamp::before(const Timestamp& other) const
72{
73 return *this < other;
74}
75
76bool Timestamp::after(const Timestamp& other) const
77{
78 return *this > other;
79}
80
81bool is_greater(Timestamp lhs, Timestamp rhs)
82{
83 const auto max = std::numeric_limits<Timestamp::value_type>::max();
84 const Timestamp::value_type lhs_raw = lhs.raw();
85 const Timestamp::value_type rhs_raw = rhs.raw();
86
87 if ((lhs_raw > rhs_raw && lhs_raw - rhs_raw <= max/2) ||
88 (rhs_raw > lhs_raw && rhs_raw - lhs_raw > max/2)) {
89 return true;
90 } else {
91 return false;
92 }
93}
94
95bool operator<(Timestamp lhs, Timestamp rhs)
96{
97 return (!is_greater(lhs, rhs) && lhs != rhs);
98}
99
100bool operator==(Timestamp lhs, Timestamp rhs)
101{
102 return lhs.raw() == rhs.raw();
103}
104
105void serialize(const Timestamp& ts, OutputArchive& ar)
106{
107 serialize(host_cast(ts.raw()), ar);
108}
109
110void deserialize(Timestamp& ts, InputArchive& ar)
111{
112 Timestamp::value_type tmp;
113 deserialize(tmp, ar);
114 ts = Timestamp { Timestamp::time_type::from_value(tmp) };
115}
116
117} // namespace geonet
118} // namespace vanetza
119
bool after(const Timestamp &other) const
Definition: timestamp.cpp:76
bool before(const Timestamp &other) const
Definition: timestamp.cpp:71