Yuri Wiitala | eb8eee7 | 2019-03-26 15:52:43 -0700 | [diff] [blame] | 1 | // Copyright 2019 The Chromium Authors. All rights reserved. |
| 2 | // Use of this source code is governed by a BSD-style license that can be |
| 3 | // found in the LICENSE file. |
| 4 | |
| 5 | #include "platform/api/time.h" |
| 6 | |
| 7 | #include <ctime> |
| 8 | |
Jordan Bayles | 2d01f17 | 2019-06-07 11:11:50 -0700 | [diff] [blame] | 9 | #include "gtest/gtest.h" |
Yuri Wiitala | eb8eee7 | 2019-03-26 15:52:43 -0700 | [diff] [blame] | 10 | |
Yuri Wiitala | eb8eee7 | 2019-03-26 15:52:43 -0700 | [diff] [blame] | 11 | namespace openscreen { |
Yuri Wiitala | eb8eee7 | 2019-03-26 15:52:43 -0700 | [diff] [blame] | 12 | |
| 13 | #if __cplusplus < 202000L |
| 14 | // Before C++20, the standard does not guarantee that time_t is the number of |
| 15 | // seconds since the UNIX epoch. It also doesn't guarantee that one tick of |
| 16 | // time_t represents one second. However, this is so universally common, it's |
| 17 | // worth assuming the platform provides this. |
| 18 | TEST(TimeTest, TimeTMeetsTheCpp20Standard) { |
| 19 | // Use the functions the standard *does* provide for calendar time |
| 20 | // conversions to determine the value of time_t at the UNIX epoch. |
| 21 | std::tm epoch_tm; |
| 22 | epoch_tm.tm_sec = 0; |
| 23 | epoch_tm.tm_min = 0; |
| 24 | epoch_tm.tm_hour = 0; |
| 25 | epoch_tm.tm_mday = 1; |
| 26 | epoch_tm.tm_mon = 0; |
| 27 | epoch_tm.tm_year = 70; // 1970 |
| 28 | epoch_tm.tm_isdst = 0; |
| 29 | // Note: std::mktime() assumes the translation is in the local time zone. |
| 30 | const std::time_t new_year_1970_in_local_tz = std::mktime(&epoch_tm); |
| 31 | // Purposely misinterpret |new_year_1970_in_local_tz| as UTC to provide |
| 32 | // information as to how to offset |epoch_tm| such that std::mktime() will |
| 33 | // be fooled into returning the value in terms of UTC. |
| 34 | std::tm* const wrong_tm = std::gmtime(&new_year_1970_in_local_tz); |
| 35 | epoch_tm.tm_sec += epoch_tm.tm_sec - wrong_tm->tm_sec; |
| 36 | epoch_tm.tm_min += epoch_tm.tm_min - wrong_tm->tm_min; |
| 37 | epoch_tm.tm_hour += epoch_tm.tm_hour - wrong_tm->tm_hour; |
| 38 | epoch_tm.tm_mday += epoch_tm.tm_mday - wrong_tm->tm_mday; |
| 39 | epoch_tm.tm_mon += epoch_tm.tm_mon - wrong_tm->tm_mon; |
| 40 | epoch_tm.tm_year += epoch_tm.tm_year - wrong_tm->tm_year; |
| 41 | |
| 42 | const std::time_t epoch = std::mktime(&epoch_tm); |
| 43 | EXPECT_EQ(seconds(0), seconds(epoch)); |
| 44 | |
| 45 | ++epoch_tm.tm_sec; |
| 46 | const std::time_t epoch_plus_one_second = std::mktime(&epoch_tm); |
| 47 | EXPECT_EQ(seconds(1), seconds(epoch_plus_one_second)); |
| 48 | } |
| 49 | #endif |
| 50 | |
Yuri Wiitala | eb8eee7 | 2019-03-26 15:52:43 -0700 | [diff] [blame] | 51 | } // namespace openscreen |