ptth/bare_minimum_crypto/cpp/time_helpers.cpp

76 lines
1.4 KiB
C++

#include "time_helpers.h"
#include <chrono>
#include <iostream>
namespace BareMinimumCrypto {
using namespace std;
using namespace chrono;
Instant::Instant (int64_t x): x (x) {}
Instant Instant::now () {
const auto utc_now = system_clock::now ();
return Instant {duration_cast <seconds> (utc_now.time_since_epoch ()).count ()};
}
bool TimeRange::contains (Instant x) const {
if (not_after < not_before) {
return false;
}
if (x.x < not_before) {
return false;
}
if (x.x > not_after) {
return false;
}
return true;
}
int64_t TimeRange::duration () const {
return not_after - not_before;
}
TimeRange TimeRange::from_start_and_dur (Instant start, int64_t dur) {
return TimeRange {
start.x,
start.x + dur
};
}
// Most tests will use a virtual clock. But just as a smoke test,
// make sure real time is realistic.
int test_time () {
const auto now = Instant::now ();
const auto time_of_writing = 1610844872;
const int64_t about_100_years = (int64_t)100 * 365 * 86400;
const TimeRange tr {
time_of_writing,
time_of_writing + about_100_years
};
if (! tr.contains (now)) {
cerr << "System clock is acting weird" << endl;
return 1;
}
const TimeRange bad_tr {
time_of_writing + about_100_years,
time_of_writing
};
if (bad_tr.contains (now)) {
cerr << "Invalid TimeRange should not contain any Instants" << endl;
return 1;
}
return 0;
}
}