1//===----------------------------------------------------------------------===//
2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
3// See https://llvm.org/LICENSE.txt for license information.
4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
5//
6//===----------------------------------------------------------------------===//
7
8// UNSUPPORTED: c++03, c++11, c++14, c++17
9
10// <chrono>
11
12// template <class _Tm, class _ChronoT>
13// _LIBCPP_HIDE_FROM_ABI _Tm __convert_to_tm(const _ChronoT& __value)
14
15// Most of the code is tested indirectly in the chrono formatters. This only
16// tests the hour overflow.
17
18#include <__chrono/convert_to_tm.h>
19#include <chrono>
20#include <cassert>
21#include <format>
22#include <string_view>
23
24#include "test_macros.h"
25
26// libc++ uses a long as representation in std::chrono::hours.
27// std::tm uses an int for its integral members. The overflow in the hour
28// conversion can only occur on platforms where sizeof(long) > sizeof(int).
29// Instead emulate this error by using a "tm" with shorts.
30// (The function is already templated to this is quite easy to do,)
31struct minimal_short_tm {
32 short tm_sec;
33 short tm_min;
34 short tm_hour;
35 const char* tm_zone;
36};
37
38int main(int, char**) {
39 { // Test with the maximum number of hours that fit in a short.
40 std::chrono::hh_mm_ss time{std::chrono::hours{32767}};
41 minimal_short_tm result = std::__convert_to_tm<minimal_short_tm>(time);
42 assert(result.tm_sec == 0);
43 assert(result.tm_min == 0);
44 assert(result.tm_hour == 32767);
45 }
46
47#ifndef TEST_HAS_NO_EXCEPTIONS
48 { // Test above the maximum number of hours that fit in a short.
49 std::chrono::hh_mm_ss time{std::chrono::hours{32768}};
50 try {
51 TEST_IGNORE_NODISCARD std::__convert_to_tm<minimal_short_tm>(time);
52 assert(false);
53 } catch ([[maybe_unused]] const std::format_error& e) {
54 LIBCPP_ASSERT(e.what() == std::string_view("Formatting hh_mm_ss, encountered an hour overflow"));
55 return 0;
56 }
57 assert(false);
58 }
59#endif // TEST_HAS_NO_EXCEPTIONS
60
61 return 0;
62}
63

source code of libcxx/test/libcxx/time/convert_to_tm.pass.cpp