owlps/owlps-positioning/src/timestamp.cc

179 lines
2.8 KiB
C++

#include "timestamp.hh"
#include <boost/functional/hash.hpp>
/* *** Constructors *** */
Timestamp::Timestamp()
{
clear() ;
}
Timestamp::Timestamp(const struct timespec &source)
{
set(source) ;
}
Timestamp::Timestamp(const owl_timestamp &source)
{
set(source) ;
}
Timestamp::Timestamp(const uint_fast32_t source_s,
const uint_fast32_t source_ns)
{
set(source_s, source_ns) ;
}
Timestamp::Timestamp(const uint64_t source)
{
set(source) ;
}
Timestamp::Timestamp(const Timestamp &source)
{
set(source.timestamp) ;
}
/* *** Internal accessors *** */
inline void Timestamp::set(const struct timespec &source)
{
timestamp = source ;
}
inline void Timestamp::set(const owl_timestamp &source)
{
set(source.tv_sec, source.tv_nsec) ;
}
inline void Timestamp::set(const uint_fast32_t source_s,
const uint_fast32_t source_ns)
{
timestamp.tv_sec = source_s ;
timestamp.tv_nsec = source_ns ;
}
inline void Timestamp::set(const uint64_t source_ms)
{
timestamp.tv_sec = source_ms / 1000 ;
timestamp.tv_nsec = (source_ms - timestamp.tv_sec * 1000) * 1000000 ;
}
/* *** Operations *** */
bool Timestamp::now()
{
return clock_gettime(CLOCK_REALTIME, &timestamp) == 0 ;
}
/**
* #timestamp nanosecond field precision is set to ms, but the value
* is still in ns.
*/
inline void Timestamp::round_to_ms()
{
timestamp.tv_nsec = timestamp.tv_nsec / 1000000 * 1000000 ;
}
/* *** Internal comparison functions *** */
bool Timestamp::equals(const struct timespec &source) const
{
return
timestamp.tv_sec == source.tv_sec &&
timestamp.tv_nsec == source.tv_nsec ;
}
bool Timestamp::equals(const uint64_t source) const
{
Timestamp tmp(source) ;
Timestamp me(*this) ;
me.round_to_ms() ;
return me == tmp ;
}
bool Timestamp::less_than(const struct timespec &source) const
{
if (timestamp.tv_sec < source.tv_sec)
return true ;
if (timestamp.tv_sec > source.tv_sec)
return false ;
// Second values are equal
if (timestamp.tv_nsec < source.tv_nsec)
return true ;
return false ;
}
bool Timestamp::greater_than(const struct timespec &source) const
{
if (equals(source))
return false ;
return ! less_than(source) ;
}
/* *** Operators *** */
const Timestamp& Timestamp::operator=(const Timestamp &source)
{
if (this == &source)
return *this ;
set(source.timestamp) ;
return *this ;
}
bool Timestamp::operator==(const Timestamp &source) const
{
if (this == &source)
return true ;
return equals(source.timestamp) ;
}
std::ostream& operator<<(std::ostream &os, const Timestamp &t)
{
os << t.timestamp.tv_sec << '.' << t.timestamp.tv_nsec ;
return os ;
}
size_t hash_value(const Timestamp &source)
{
return boost::hash_value(static_cast<uint64_t>(source)) ;
}