xref: /llvm-project/libcxx/test/std/time/time.zone/time.zone.db/time.zone.db.tzdb/current_zone.pass.cpp (revision 2ba08386156ef25913b1bee170d8fe95aaceb234)
1 //===----------------------------------------------------------------------===//
2 //
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6 //
7 //===----------------------------------------------------------------------===//
8 
9 // UNSUPPORTED: c++03, c++11, c++14, c++17
10 // UNSUPPORTED: no-filesystem, no-localization, no-tzdb
11 
12 // XFAIL: libcpp-has-no-experimental-tzdb
13 // XFAIL: availability-tzdb-missing
14 
15 // <chrono>
16 
17 // struct tzdb
18 
19 // const time_zone* current_zone() const;
20 
21 #include <cassert>
22 #include <chrono>
23 #include <string_view>
24 #include <stdlib.h>
25 
26 #include "test_macros.h"
27 #include "assert_macros.h"
28 #include "concat_macros.h"
29 
30 #ifdef _WIN32
set_tz(std::string zone)31 static void set_tz(std::string zone) {
32   // Note Windows does not have setenv, only putenv
33   // https://learn.microsoft.com/en-us/cpp/c-runtime-library/reference/putenv-s-wputenv-s?view=msvc-170
34   // Unlike POSIX it does not mention the string of putenv becomes part
35   // of the environment.
36 
37   int status = _putenv_s("TZ", zone.c_str());
38   assert(status == 0);
39 }
40 
41 #else
set_tz(const std::string & zone)42 static void set_tz(const std::string& zone) {
43   int status = setenv("TZ", zone.c_str(), 1);
44   assert(status == 0);
45 }
46 #endif
47 
test_zone(const std::string & zone)48 static void test_zone(const std::string& zone) {
49   set_tz(zone);
50   const std::chrono::time_zone* tz = std::chrono::get_tzdb().current_zone();
51   assert(tz);
52   assert(tz->name() == zone);
53 }
54 
test_link(const std::string & link,std::string_view zone)55 static void test_link(const std::string& link, std::string_view zone) {
56   set_tz(link);
57   const std::chrono::time_zone* tz = std::chrono::get_tzdb().current_zone();
58   assert(tz);
59   assert(tz->name() == zone);
60 }
61 
main(int,const char **)62 int main(int, const char**) {
63   const std::chrono::time_zone* tz = std::chrono::get_tzdb().current_zone();
64   // Returns a valid time zone, the value depends on the OS settings.
65   assert(tz);
66   // setting the environment to an invalid value returns the value of
67   // the OS setting.
68   set_tz("This is not a time zone");
69   assert(tz == std::chrono::get_tzdb().current_zone());
70 
71   const std::chrono::tzdb& db = std::chrono::get_tzdb();
72   for (const auto& zone : db.zones)
73     test_zone(std::string{zone.name()});
74 
75   for (const auto& link : db.links)
76     test_link(std::string{link.name()}, link.target());
77 
78   return 0;
79 }
80