87232df789606dc13957f692113b8a427948c9af
[pingcheck] / src / dns / timetolive.cpp
1 /*
2 The software in this package is distributed under the GNU General
3 Public License version 2 (with a special exception described below).
4
5 A copy of GNU General Public License (GPL) is included in this distribution,
6 in the file COPYING.GPL.
7
8 As a special exception, if other files instantiate templates or use macros
9 or inline functions from this file, or you compile this file and link it
10 with other works to produce a work based on this file, this file
11 does not by itself cause the resulting work to be covered
12 by the GNU General Public License.
13
14 However the source code for this file must still be made available
15 in accordance with section (3) of the GNU General Public License.
16
17 This exception does not invalidate any other reasons why a work based
18 on this file might be covered by the GNU General Public License.
19 */
20 #include "dns/timetolive.h"
21
22 #include "boost_assert_handler.h"
23
24 using boost::date_time::time_resolution_traits_adapted64_impl;
25 using boost::posix_time::microsec_clock;
26 using boost::posix_time::ptime;
27
28 //-----------------------------------------------------------------------------
29 // TimeToLive
30 //-----------------------------------------------------------------------------
31
32 TimeToLive::TimeToLive( uint32_t ttl ) :
33     Ttl( ttl ),
34     TtlSetTime( microsec_clock::universal_time() )
35 {
36 }
37
38 TimeToLive::~TimeToLive()
39 {
40 }
41
42 /**
43  * @return the original time-to-live value, as specified by the set method.
44  */
45 uint32_t TimeToLive::get_value() const
46 {
47     return Ttl;
48 }
49
50 /**
51  * @param ttl the time-to-live value.
52  */
53 void TimeToLive::set_value( const uint32_t ttl )
54 {
55     BOOST_ASSERT( 0 < ttl );
56
57     Ttl = ttl;
58     TtlSetTime = microsec_clock::universal_time();
59 }
60
61 /**
62  * @return the value of the time-to-live updated since the last set was called.
63  */
64 uint32_t TimeToLive::get_updated_value() const
65 {
66     ptime now = microsec_clock::universal_time();
67     uint32_t elapsed_seconds = static_cast<uint32_t>(
68             (now - TtlSetTime).total_seconds()
69     );
70
71     uint32_t original_ttl = get_value();
72     if (elapsed_seconds > original_ttl)
73         return 0;
74     else
75         return original_ttl - elapsed_seconds;
76 }
77
78 bool TimeToLive::was_set_before(const ptime &threshold) const
79 {
80     return TtlSetTime < threshold;
81 }