SampleReceiver/src/Timestamp.h

113 lines
2.5 KiB
C++

//
// Created by epagris on 2021. 11. 01..
//
#ifndef WFR_TIMESTAMP_H
#define WFR_TIMESTAMP_H
#include <cstdint>
class Timestamp {
public:
static constexpr uint32_t NANO_PREFIX = 1E+09;
public:
int64_t s, ns; // time data
public:
// constr.
explicit Timestamp(int64_t s = 0, int64_t ns = 0): s(s), ns(ns) {};
// initialization with initializer list
Timestamp(const std::initializer_list<int64_t>& il) : s(0), ns(0) {
this->operator=(il);
}
// assignment
Timestamp& operator=(const std::initializer_list<int64_t>& il) {
if (il.size() >= 2) {
s = *il.begin();
ns = *(il.begin() + 1);
}
return *this;
}
Timestamp& operator=(const Timestamp& other) {
s = other.s;
ns = other.ns;
return *this;
}
// is it empty?
bool empty() const {
return (s == 0) && (ns == 0);
}
// convert to nanoseconds
int64_t to_ns() const {
return (int64_t)NANO_PREFIX * s + ns;
}
// convert from nanoseconds
void from_ns(int64_t ns) {
this->s = ns / (int64_t)NANO_PREFIX;
this->ns = (ns - s * NANO_PREFIX);
}
// add timestamps
Timestamp& operator+=(const Timestamp& other) {
int64_t sum_ns = to_ns() + other.to_ns();
from_ns(sum_ns);
return *this;
}
// multiply timestamp
Timestamp operator*(double c) const {
Timestamp ts;
ts.from_ns((int64_t)(c * this->to_ns()));
return ts;
}
// divide timestamp by scalar
Timestamp operator/(double d) const {
return this->operator*(1 / d);
}
// substract timestamps
Timestamp& operator-=(const Timestamp& other) {
return this->operator+=(other * (-1.0));
}
// add timestamps
Timestamp operator+(const Timestamp& other) const {
Timestamp ts;
ts.from_ns(this->to_ns() + other.to_ns());
return ts;
}
// substract timestamps
Timestamp operator-(const Timestamp& other) const {
Timestamp ts = *this + other * (-1);
return ts;
}
// comparison
bool operator>(const Timestamp& other) const {
return this->to_ns() > other.to_ns();
}
bool operator<(const Timestamp& other) const {
return this->to_ns() < other.to_ns();
}
bool operator==(const Timestamp& other) const {
return this->to_ns() == other.to_ns();
}
bool operator!=(const Timestamp& other) const {
return !this->operator==(other);
}
};
#endif //WFR_TIMESTAMP_H