Time: Implement duration_cast from DeltaTimeval to std::chrono::duration

This will allow us to migrate step-by-step from DeltaTimeval to std::chrono.
This commit is contained in:
Peter Keresztes Schmidt 2021-06-06 14:41:56 +02:00
parent 2a32f75a24
commit 154b17d5f3
1 changed files with 28 additions and 0 deletions

View File

@ -247,7 +247,28 @@ struct posix_duration_cast<timeval, std::chrono::duration<Rep, Period>> {
} }
}; };
// chrono -> DeltaTimeval caster
template<typename Rep, typename Period>
struct posix_duration_cast<std::chrono::duration<Rep, Period>, DeltaTimeval> {
template<uint32 Prec>
static DeltaTimeval cast(std::chrono::duration<Rep, Period> const &d) {
typedef std::chrono::duration<int64, std::ratio<1, Prec>> fsec_t;
DeltaTimeval res = {};
Seconds secs = std::chrono::duration_cast<Seconds>(d);
fsec_t fsec = std::chrono::duration_cast<fsec_t, int64, std::ratio<1, Prec>>(d - secs);
res.positive = fsec >= Seconds::zero();
res.delta = abs((secs + fsec).count());
res.sec = secs.count();
res.fsec = fsec.count();
res.prec = Prec;
return res;
}
};
} }
// chrono -> timeval // chrono -> timeval
template<typename T, typename Rep, typename Period> template<typename T, typename Rep, typename Period>
auto duration_cast(std::chrono::duration<Rep, Period> const &d) auto duration_cast(std::chrono::duration<Rep, Period> const &d)
@ -260,6 +281,13 @@ template<typename Duration>
Duration duration_cast(timeval const &tv) { Duration duration_cast(timeval const &tv) {
return impl::posix_duration_cast<timeval, Duration>::cast(tv); return impl::posix_duration_cast<timeval, Duration>::cast(tv);
} }
// chrono -> DeltaTimeval
template<typename T, uint32 Prec, typename Rep, typename Period>
auto duration_cast(std::chrono::duration<Rep, Period> const &d)
-> typename std::enable_if<std::is_same<T, DeltaTimeval>::value, DeltaTimeval>::type {
return impl::posix_duration_cast<std::chrono::duration<Rep, Period>, DeltaTimeval>::template cast<Prec>(d);
}
} }
} }