diff --git a/chrono/datetime.h b/chrono/datetime.h index 1d98bc8..fef2713 100644 --- a/chrono/datetime.h +++ b/chrono/datetime.h @@ -486,4 +486,14 @@ inline DateTime &DateTime::operator -=(const TimeSpan &timeSpan) } +namespace std { +template<> struct hash +{ + inline size_t operator()(const ChronoUtilities::DateTime &dateTime) const + { + return hash()(dateTime.totalTicks()); + } +}; +} + #endif // CHRONO_UTILITIES_DATETIME_H diff --git a/chrono/timespan.h b/chrono/timespan.h index 109bee7..ae2fc1a 100644 --- a/chrono/timespan.h +++ b/chrono/timespan.h @@ -363,4 +363,14 @@ constexpr inline bool TimeSpan::isInfinity() const } +namespace std { +template<> struct hash +{ + inline size_t operator()(const ChronoUtilities::TimeSpan &timeSpan) const + { + return hash()(timeSpan.totalTicks()); + } +}; +} + #endif // CHRONO_UTILITIES_TIMESPAN_H diff --git a/tests/chronotests.cpp b/tests/chronotests.cpp index c7c3726..761a115 100644 --- a/tests/chronotests.cpp +++ b/tests/chronotests.cpp @@ -24,6 +24,7 @@ class ChronoTests : public TestFixture CPPUNIT_TEST(testDateTime); CPPUNIT_TEST(testTimeSpan); CPPUNIT_TEST(testOperators); + CPPUNIT_TEST(testHashing); CPPUNIT_TEST_SUITE_END(); public: @@ -33,6 +34,7 @@ public: void testDateTime(); void testTimeSpan(); void testOperators(); + void testHashing(); }; CPPUNIT_TEST_SUITE_REGISTRATION(ChronoTests); @@ -116,3 +118,21 @@ void ChronoTests::testOperators() CPPUNIT_ASSERT_EQUAL(5, dateTime.day()); CPPUNIT_ASSERT_EQUAL(2, Period(dateTime, dateTime + TimeSpan::fromDays(62)).months()); } + +/*! + * \brief Tests hashing DateTime / TimeSpan by using in a set. + */ +void ChronoTests::testHashing() +{ + set dateTimes; + dateTimes.emplace(DateTime::fromDate(2500, 2, 1)); + dateTimes.emplace(DateTime::fromDate(2500, 2, 2)); + dateTimes.emplace(DateTime::fromDate(2500, 2, 1)); + CPPUNIT_ASSERT_EQUAL(2ul, dateTimes.size()); + + set timeSpans; + timeSpans.emplace(TimeSpan::fromDays(5)); + timeSpans.emplace(TimeSpan::fromDays(10)); + timeSpans.emplace(TimeSpan::fromDays(5)); + CPPUNIT_ASSERT_EQUAL(2ul, timeSpans.size()); +}