Skip to content

Commit

Permalink
Add as_chrono_duration() utility
Browse files Browse the repository at this point in the history
This makes it easy to convert any Au duration quantity to an
exactly-equivalent `std::chrono::duration`.

Fixes #187.
  • Loading branch information
chiphogg committed Nov 25, 2023
1 parent 02b7e1a commit bc05d52
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 0 deletions.
10 changes: 10 additions & 0 deletions au/au.hh
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,14 @@ struct CorrespondingQuantity<std::chrono::duration<RepT, Period>> {
static constexpr ChronoDuration construct_from_value(Rep x) { return ChronoDuration{x}; }
};

// Convert any Au duration quantity to an equivalent `std::chrono::duration`.
template <typename U, typename R>
constexpr auto as_chrono_duration(Quantity<U, R> dt) {
constexpr auto ratio = unit_ratio(U{}, seconds);
static_assert(is_rational(ratio), "Cannot convert to chrono::duration with non-rational ratio");
return std::chrono::duration<R,
std::ratio<get_value<std::intmax_t>(numerator(ratio)),
get_value<std::intmax_t>(denominator(ratio))>>{dt};
}

} // namespace au
7 changes: 7 additions & 0 deletions au/au_test.cc
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,13 @@ TEST(DurationQuantity, InterconvertsWithIndirectlyEquivalentChronoDuration) {
EXPECT_THAT(from_chrono, SameTypeAndValue(seconds(1.234)));
}

TEST(AsChronoDuration, ProducesExpectedResults) {
constexpr auto original = milli(seconds)(12.3f);
constexpr auto result = as_chrono_duration(original);
EXPECT_THAT(result.count(), SameTypeAndValue(12.3f));
EXPECT_THAT(as_quantity(result), QuantityEquivalent(original));
}

TEST(Conversions, SupportIntMHzToU32Hz) {
constexpr QuantityU32<Hertz> freq = mega(hertz)(40);
EXPECT_THAT(freq, SameTypeAndValue(hertz(40'000'000u)));
Expand Down

0 comments on commit bc05d52

Please sign in to comment.