forked from HowardHinnant/date
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tz.cpp
3550 lines (3296 loc) · 104 KB
/
tz.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// The MIT License (MIT)
//
// Copyright (c) 2015, 2016, 2017 Howard Hinnant
// Copyright (c) 2015 Ville Voutilainen
// Copyright (c) 2016 Alexander Kormanovsky
// Copyright (c) 2016, 2017 Jiangang Zhuang
// Copyright (c) 2017 Nicolas Veloz Savino
// Copyright (c) 2017 Florian Dang
// Copyright (c) 2017 Aaron Bishop
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
//
// Our apologies. When the previous paragraph was written, lowercase had not yet
// been invented (that would involve another several millennia of evolution).
// We did not mean to shout.
#ifdef _WIN32
// Windows.h will be included directly and indirectly (e.g. by curl).
// We need to define these macros to prevent Windows.h bringing in
// more than we need and do it early so Windows.h doesn't get included
// without these macros having been defined.
// min/max macros interfere with the C++ versions.
# ifndef NOMINMAX
# define NOMINMAX
# endif
// We don't need all that Windows has to offer.
# ifndef WIN32_LEAN_AND_MEAN
# define WIN32_LEAN_AND_MEAN
# endif
// for wcstombs
# ifndef _CRT_SECURE_NO_WARNINGS
# define _CRT_SECURE_NO_WARNINGS
# endif
// None of this happens with the MS SDK (at least VS14 which I tested), but:
// Compiling with mingw, we get "error: 'KF_FLAG_DEFAULT' was not declared in this scope."
// and error: 'SHGetKnownFolderPath' was not declared in this scope.".
// It seems when using mingw NTDDI_VERSION is undefined and that
// causes KNOWN_FOLDER_FLAG and the KF_ flags to not get defined.
// So we must define NTDDI_VERSION to get those flags on mingw.
// The docs say though here:
// https://msdn.microsoft.com/en-nz/library/windows/desktop/aa383745(v=vs.85).aspx
// that "If you define NTDDI_VERSION, you must also define _WIN32_WINNT."
// So we declare we require Vista or greater.
# ifdef __MINGW32__
# ifndef NTDDI_VERSION
# define NTDDI_VERSION 0x06000000
# define _WIN32_WINNT _WIN32_WINNT_VISTA
# elif NTDDI_VERSION < 0x06000000
# warning "If this fails to compile NTDDI_VERSION may be to low. See comments above."
# endif
// But once we define the values above we then get this linker error:
// "tz.cpp:(.rdata$.refptr.FOLDERID_Downloads[.refptr.FOLDERID_Downloads]+0x0): "
// "undefined reference to `FOLDERID_Downloads'"
// which #include <initguid.h> cures see:
// https://support.microsoft.com/en-us/kb/130869
# include <initguid.h>
// But with <initguid.h> included, the error moves on to:
// error: 'FOLDERID_Downloads' was not declared in this scope
// Which #include <knownfolders.h> cures.
# include <knownfolders.h>
# endif // __MINGW32__
# include <Windows.h>
#endif // _WIN32
#include "tz_private.h"
#include "ios.h"
#if USE_OS_TZDB
# include <dirent.h>
#endif
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <cstring>
#include <fstream>
#include <iostream>
#include <iterator>
#include <memory>
#if USE_OS_TZDB
# include <queue>
#endif
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#include <sys/stat.h>
// unistd.h is used on some platforms as part of the the means to get
// the current time zone. On Win32 Windows.h provides a means to do it.
// gcc/mingw supports unistd.h on Win32 but MSVC does not.
#ifdef _WIN32
# include <io.h> // _unlink etc.
# if defined(__clang__)
struct IUnknown; // fix for issue with static_cast<> in objbase.h
// (see https://github.com/philsquared/Catch/issues/690)
# endif
# include <ShlObj.h> // CoTaskFree, ShGetKnownFolderPath etc.
# if HAS_REMOTE_API
# include <direct.h> // _mkdir
# include <Shellapi.h> // ShFileOperation etc.
# endif // HAS_REMOTE_API
#else // !_WIN32
# include <unistd.h>
# include <wordexp.h>
# include <limits.h>
# include <string.h>
# if !USE_SHELL_API
# include <sys/stat.h>
# include <sys/fcntl.h>
# include <dirent.h>
# include <cstring>
# include <sys/wait.h>
# include <sys/types.h>
# endif //!USE_SHELL_API
#endif // !_WIN32
#if HAS_REMOTE_API
// Note curl includes windows.h so we must include curl AFTER definitions of things
// that effect windows.h such as NOMINMAX.
# include <curl/curl.h>
#endif
#ifdef _WIN32
static CONSTDATA char folder_delimiter = '\\';
#else // !_WIN32
static CONSTDATA char folder_delimiter = '/';
#endif // !_WIN32
#if defined(__GNUC__) && __GNUC__ < 5
// GCC 4.9 Bug 61489 Wrong warning with -Wmissing-field-initializers
# pragma GCC diagnostic push
# pragma GCC diagnostic ignored "-Wmissing-field-initializers"
#endif // defined(__GNUC__) && __GNUC__ < 5
#if !USE_OS_TZDB
# ifdef _WIN32
namespace
{
struct task_mem_deleter
{
void operator()(wchar_t buf[])
{
if (buf != nullptr)
CoTaskMemFree(buf);
}
};
using co_task_mem_ptr = std::unique_ptr<wchar_t[], task_mem_deleter>;
}
// We might need to know certain locations even if not using the remote API,
// so keep these routines out of that block for now.
static
std::string
get_known_folder(const GUID& folderid)
{
std::string folder;
PWSTR pfolder = nullptr;
HRESULT hr = SHGetKnownFolderPath(folderid, KF_FLAG_DEFAULT, NULL, &pfolder);
if (SUCCEEDED(hr))
{
co_task_mem_ptr folder_ptr(pfolder);
folder = std::string(folder_ptr.get(), folder_ptr.get() + wcslen(folder_ptr.get()));
}
return folder;
}
// Usually something like "c:\Users\username\Downloads".
static
std::string
get_download_folder()
{
return get_known_folder(FOLDERID_Downloads);
}
# else // !_WIN32
# if !defined(INSTALL) || HAS_REMOTE_API
static
std::string
expand_path(std::string path)
{
# if TARGET_OS_IPHONE
return date::iOSUtils::get_tzdata_path();
# else // !TARGET_OS_IPHONE
::wordexp_t w{};
::wordexp(path.c_str(), &w, 0);
assert(w.we_wordc == 1);
path = w.we_wordv[0];
::wordfree(&w);
return path;
# endif // !TARGET_OS_IPHONE
}
static
std::string
get_download_folder()
{
return expand_path("~/Downloads");
}
# endif // !defined(INSTALL) || HAS_REMOTE_API
# endif // !_WIN32
#endif // !USE_OS_TZDB
namespace date
{
// +---------------------+
// | Begin Configuration |
// +---------------------+
using namespace detail;
#if !USE_OS_TZDB
static
std::string&
access_install()
{
static std::string install
#ifndef INSTALL
= get_download_folder() + folder_delimiter + "tzdata";
#else // !INSTALL
# define STRINGIZEIMP(x) #x
# define STRINGIZE(x) STRINGIZEIMP(x)
= STRINGIZE(INSTALL) + std::string(1, folder_delimiter) + "tzdata";
#endif // !INSTALL
return install;
}
void
set_install(const std::string& s)
{
access_install() = s;
}
static
const std::string&
get_install()
{
static const std::string& ref = access_install();
return ref;
}
#if HAS_REMOTE_API
static
std::string
get_download_gz_file(const std::string& version)
{
auto file = get_install() + version + ".tar.gz";
return file;
}
#endif // HAS_REMOTE_API
#endif // !USE_OS_TZDB
// These can be used to reduce the range of the database to save memory
CONSTDATA auto min_year = date::year::min();
CONSTDATA auto max_year = date::year::max();
CONSTDATA auto min_day = date::jan/1;
CONSTDATA auto max_day = date::dec/31;
#if USE_OS_TZDB
CONSTCD14 const sys_seconds min_seconds = sys_days(min_year/min_day);
#endif // USE_OS_TZDB
#ifndef _WIN32
constexpr const char tz_dir[] = "/usr/share/zoneinfo";
#endif
// +-------------------+
// | End Configuration |
// +-------------------+
namespace detail
{
struct undocumented {explicit undocumented() = default;};
}
#ifndef _MSC_VER
static_assert(min_year <= max_year, "Configuration error");
#endif
static
TZ_DB&
access_tzdb()
{
static TZ_DB tz_db;
return tz_db;
}
#if !USE_OS_TZDB
#ifdef _WIN32
static
void
sort_zone_mappings(std::vector<date::detail::timezone_mapping>& mappings)
{
std::sort(mappings.begin(), mappings.end(),
[](const date::detail::timezone_mapping& lhs,
const date::detail::timezone_mapping& rhs)->bool
{
auto other_result = lhs.other.compare(rhs.other);
if (other_result < 0)
return true;
else if (other_result == 0)
{
auto territory_result = lhs.territory.compare(rhs.territory);
if (territory_result < 0)
return true;
else if (territory_result == 0)
{
if (lhs.type < rhs.type)
return true;
}
}
return false;
});
}
static
bool
native_to_standard_timezone_name(const std::string& native_tz_name,
std::string& standard_tz_name)
{
// TOOD! Need be a case insensitive compare?
if (native_tz_name == "UTC")
{
standard_tz_name = "Etc/UTC";
return true;
}
standard_tz_name.clear();
// TODO! we can improve on linear search.
const auto& mappings = date::get_tzdb().mappings;
for (const auto& tzm : mappings)
{
if (tzm.other == native_tz_name)
{
standard_tz_name = tzm.type;
return true;
}
}
return false;
}
// Parse this XML file:
// http://unicode.org/repos/cldr/trunk/common/supplemental/windowsZones.xml
// The parsing method is designed to be simple and quick. It is not overly
// forgiving of change but it should diagnose basic format issues.
// See timezone_mapping structure for more info.
static
std::vector<detail::timezone_mapping>
load_timezone_mappings_from_xml_file(const std::string& input_path)
{
std::size_t line_num = 0;
std::vector<detail::timezone_mapping> mappings;
std::string line;
std::ifstream is(input_path);
if (!is.is_open())
{
// We don't emit file exceptions because that's an implementation detail.
std::string msg = "Error opening time zone mapping file \"";
msg += input_path;
msg += "\".";
throw std::runtime_error(msg);
}
auto error = [&input_path, &line_num](const char* info)
{
std::string msg = "Error loading time zone mapping file \"";
msg += input_path;
msg += "\" at line ";
msg += std::to_string(line_num);
msg += ": ";
msg += info;
throw std::runtime_error(msg);
};
// [optional space]a="b"
auto read_attribute = [&line_num, &line, &error]
(const char* name, std::string& value, std::size_t startPos)
->std::size_t
{
value.clear();
// Skip leading space before attribute name.
std::size_t spos = line.find_first_not_of(' ', startPos);
if (spos == std::string::npos)
spos = startPos;
// Assume everything up to next = is the attribute name
// and that an = will always delimit that.
std::size_t epos = line.find('=', spos);
if (epos == std::string::npos)
error("Expected \'=\' right after attribute name.");
std::size_t name_len = epos - spos;
// Expect the name we find matches the name we expect.
if (line.compare(spos, name_len, name) != 0)
{
std::string msg;
msg = "Expected attribute name \'";
msg += name;
msg += "\' around position ";
msg += std::to_string(spos);
msg += " but found something else.";
error(msg.c_str());
}
++epos; // Skip the '=' that is after the attribute name.
spos = epos;
if (spos < line.length() && line[spos] == '\"')
++spos; // Skip the quote that is before the attribute value.
else
{
std::string msg = "Expected '\"' to begin value of attribute \'";
msg += name;
msg += "\'.";
error(msg.c_str());
}
epos = line.find('\"', spos);
if (epos == std::string::npos)
{
std::string msg = "Expected '\"' to end value of attribute \'";
msg += name;
msg += "\'.";
error(msg.c_str());
}
// Extract everything in between the quotes. Note no escaping is done.
std::size_t value_len = epos - spos;
value.assign(line, spos, value_len);
++epos; // Skip the quote that is after the attribute value;
return epos;
};
// Quick but not overly forgiving XML mapping file processing.
bool mapTimezonesOpenTagFound = false;
bool mapTimezonesCloseTagFound = false;
std::size_t mapZonePos = std::string::npos;
std::size_t mapTimezonesPos = std::string::npos;
CONSTDATA char mapTimeZonesOpeningTag[] = { "<mapTimezones " };
CONSTDATA char mapZoneOpeningTag[] = { "<mapZone " };
CONSTDATA std::size_t mapZoneOpeningTagLen = sizeof(mapZoneOpeningTag) /
sizeof(mapZoneOpeningTag[0]) - 1;
while (!mapTimezonesOpenTagFound)
{
std::getline(is, line);
++line_num;
if (is.eof())
{
// If there is no mapTimezones tag is it an error?
// Perhaps if there are no mapZone mappings it might be ok for
// its parent mapTimezones element to be missing?
// We treat this as an error though on the assumption that if there
// really are no mappings we should still get a mapTimezones parent
// element but no mapZone elements inside. Assuming we must
// find something will hopefully at least catch more drastic formatting
// changes or errors than if we don't do this and assume nothing found.
error("Expected a mapTimezones opening tag.");
}
mapTimezonesPos = line.find(mapTimeZonesOpeningTag);
mapTimezonesOpenTagFound = (mapTimezonesPos != std::string::npos);
}
// NOTE: We could extract the version info that follows the opening
// mapTimezones tag and compare that to the version of other data we have.
// I would have expected them to be kept in synch but testing has shown
// it is typically does not match anyway. So what's the point?
while (!mapTimezonesCloseTagFound)
{
std::ws(is);
std::getline(is, line);
++line_num;
if (is.eof())
error("Expected a mapTimezones closing tag.");
if (line.empty())
continue;
mapZonePos = line.find(mapZoneOpeningTag);
if (mapZonePos != std::string::npos)
{
mapZonePos += mapZoneOpeningTagLen;
detail::timezone_mapping zm{};
std::size_t pos = read_attribute("other", zm.other, mapZonePos);
pos = read_attribute("territory", zm.territory, pos);
read_attribute("type", zm.type, pos);
mappings.push_back(std::move(zm));
continue;
}
mapTimezonesPos = line.find("</mapTimezones>");
mapTimezonesCloseTagFound = (mapTimezonesPos != std::string::npos);
if (!mapTimezonesCloseTagFound)
{
std::size_t commentPos = line.find("<!--");
if (commentPos == std::string::npos)
error("Unexpected mapping record found. A xml mapZone or comment "
"attribute or mapTimezones closing tag was expected.");
}
}
is.close();
return mappings;
}
#endif // _WIN32
// Parsing helpers
static
std::string
parse3(std::istream& in)
{
std::string r(3, ' ');
ws(in);
r[0] = static_cast<char>(in.get());
r[1] = static_cast<char>(in.get());
r[2] = static_cast<char>(in.get());
return r;
}
static
unsigned
parse_dow(std::istream& in)
{
CONSTDATA char*const dow_names[] =
{"Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"};
auto s = parse3(in);
auto dow = std::find(std::begin(dow_names), std::end(dow_names), s) - dow_names;
if (dow >= std::end(dow_names) - std::begin(dow_names))
throw std::runtime_error("oops: bad dow name: " + s);
return static_cast<unsigned>(dow);
}
static
unsigned
parse_month(std::istream& in)
{
CONSTDATA char*const month_names[] =
{"Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"};
auto s = parse3(in);
auto m = std::find(std::begin(month_names), std::end(month_names), s) - month_names;
if (m >= std::end(month_names) - std::begin(month_names))
throw std::runtime_error("oops: bad month name: " + s);
return static_cast<unsigned>(++m);
}
static
std::chrono::seconds
parse_unsigned_time(std::istream& in)
{
using namespace std::chrono;
int x;
in >> x;
auto r = seconds{hours{x}};
if (!in.eof() && in.peek() == ':')
{
in.get();
in >> x;
r += minutes{x};
if (!in.eof() && in.peek() == ':')
{
in.get();
in >> x;
r += seconds{x};
}
}
return r;
}
static
std::chrono::seconds
parse_signed_time(std::istream& in)
{
ws(in);
auto sign = 1;
if (in.peek() == '-')
{
sign = -1;
in.get();
}
else if (in.peek() == '+')
in.get();
return sign * parse_unsigned_time(in);
}
// MonthDayTime
detail::MonthDayTime::MonthDayTime(local_seconds tp, tz timezone)
: zone_(timezone)
{
using namespace date;
const auto dp = date::floor<days>(tp);
const auto hms = make_time(tp - dp);
const auto ymd = year_month_day(dp);
u = ymd.month() / ymd.day();
h_ = hms.hours();
m_ = hms.minutes();
s_ = hms.seconds();
}
detail::MonthDayTime::MonthDayTime(const date::month_day& md, tz timezone)
: zone_(timezone)
{
u = md;
}
date::day
detail::MonthDayTime::day() const
{
switch (type_)
{
case month_day:
return u.month_day_.day();
case month_last_dow:
return date::day{31};
case lteq:
case gteq:
break;
}
return u.month_day_weekday_.month_day_.day();
}
date::month
detail::MonthDayTime::month() const
{
switch (type_)
{
case month_day:
return u.month_day_.month();
case month_last_dow:
return u.month_weekday_last_.month();
case lteq:
case gteq:
break;
}
return u.month_day_weekday_.month_day_.month();
}
int
detail::MonthDayTime::compare(date::year y, const MonthDayTime& x, date::year yx,
std::chrono::seconds offset, std::chrono::minutes prev_save) const
{
if (zone_ != x.zone_)
{
auto dp0 = to_sys_days(y);
auto dp1 = x.to_sys_days(yx);
if (std::abs((dp0-dp1).count()) > 1)
return dp0 < dp1 ? -1 : 1;
if (zone_ == tz::local)
{
auto tp0 = to_time_point(y) - prev_save;
if (x.zone_ == tz::utc)
tp0 -= offset;
auto tp1 = x.to_time_point(yx);
return tp0 < tp1 ? -1 : tp0 == tp1 ? 0 : 1;
}
else if (zone_ == tz::standard)
{
auto tp0 = to_time_point(y);
auto tp1 = x.to_time_point(yx);
if (x.zone_ == tz::local)
tp1 -= prev_save;
else
tp0 -= offset;
return tp0 < tp1 ? -1 : tp0 == tp1 ? 0 : 1;
}
// zone_ == tz::utc
auto tp0 = to_time_point(y);
auto tp1 = x.to_time_point(yx);
if (x.zone_ == tz::local)
tp1 -= offset + prev_save;
else
tp1 -= offset;
return tp0 < tp1 ? -1 : tp0 == tp1 ? 0 : 1;
}
auto const t0 = to_time_point(y);
auto const t1 = x.to_time_point(yx);
return t0 < t1 ? -1 : t0 == t1 ? 0 : 1;
}
sys_seconds
detail::MonthDayTime::to_sys(date::year y, std::chrono::seconds offset,
std::chrono::seconds save) const
{
using namespace date;
using namespace std::chrono;
auto until_utc = to_time_point(y);
if (zone_ == tz::standard)
until_utc -= offset;
else if (zone_ == tz::local)
until_utc -= offset + save;
return until_utc;
}
detail::MonthDayTime::U&
detail::MonthDayTime::U::operator=(const date::month_day& x)
{
month_day_ = x;
return *this;
}
detail::MonthDayTime::U&
detail::MonthDayTime::U::operator=(const date::month_weekday_last& x)
{
month_weekday_last_ = x;
return *this;
}
detail::MonthDayTime::U&
detail::MonthDayTime::U::operator=(const pair& x)
{
month_day_weekday_ = x;
return *this;
}
date::sys_days
detail::MonthDayTime::to_sys_days(date::year y) const
{
using namespace std::chrono;
using namespace date;
switch (type_)
{
case month_day:
return sys_days(y/u.month_day_);
case month_last_dow:
return sys_days(y/u.month_weekday_last_);
case lteq:
{
auto const x = y/u.month_day_weekday_.month_day_;
auto const wd1 = weekday(static_cast<sys_days>(x));
auto const wd0 = u.month_day_weekday_.weekday_;
return sys_days(x) - (wd1-wd0);
}
case gteq:
break;
}
auto const x = y/u.month_day_weekday_.month_day_;
auto const wd1 = u.month_day_weekday_.weekday_;
auto const wd0 = weekday(static_cast<sys_days>(x));
return sys_days(x) + (wd1-wd0);
}
sys_seconds
detail::MonthDayTime::to_time_point(date::year y) const
{
// Add seconds first to promote to largest rep early to prevent overflow
return to_sys_days(y) + s_ + h_ + m_;
}
void
detail::MonthDayTime::canonicalize(date::year y)
{
using namespace std::chrono;
using namespace date;
switch (type_)
{
case month_day:
return;
case month_last_dow:
{
auto const ymd = year_month_day(sys_days(y/u.month_weekday_last_));
u.month_day_ = ymd.month()/ymd.day();
type_ = month_day;
return;
}
case lteq:
{
auto const x = y/u.month_day_weekday_.month_day_;
auto const wd1 = weekday(static_cast<sys_days>(x));
auto const wd0 = u.month_day_weekday_.weekday_;
auto const ymd = year_month_day(sys_days(x) - (wd1-wd0));
u.month_day_ = ymd.month()/ymd.day();
type_ = month_day;
return;
}
case gteq:
{
auto const x = y/u.month_day_weekday_.month_day_;
auto const wd1 = u.month_day_weekday_.weekday_;
auto const wd0 = weekday(static_cast<sys_days>(x));
auto const ymd = year_month_day(sys_days(x) + (wd1-wd0));
u.month_day_ = ymd.month()/ymd.day();
type_ = month_day;
return;
}
}
}
std::istream&
detail::operator>>(std::istream& is, MonthDayTime& x)
{
using namespace date;
using namespace std::chrono;
x = MonthDayTime{};
if (!is.eof() && ws(is) && !is.eof() && is.peek() != '#')
{
auto m = parse_month(is);
if (!is.eof() && ws(is) && !is.eof() && is.peek() != '#')
{
if (is.peek() == 'l')
{
for (int i = 0; i < 4; ++i)
is.get();
auto dow = parse_dow(is);
x.type_ = MonthDayTime::month_last_dow;
x.u = date::month(m)/weekday(dow)[last];
}
else if (std::isalpha(is.peek()))
{
auto dow = parse_dow(is);
char c;
is >> c;
if (c == '<' || c == '>')
{
char c2;
is >> c2;
if (c2 != '=')
throw std::runtime_error(std::string("bad operator: ") + c + c2);
int d;
is >> d;
if (d < 1 || d > 31)
throw std::runtime_error(std::string("bad operator: ") + c + c2
+ std::to_string(d));
x.type_ = c == '<' ? MonthDayTime::lteq : MonthDayTime::gteq;
x.u = MonthDayTime::pair{ date::month(m) / d, date::weekday(dow) };
}
else
throw std::runtime_error(std::string("bad operator: ") + c);
}
else // if (std::isdigit(is.peek())
{
int d;
is >> d;
if (d < 1 || d > 31)
throw std::runtime_error(std::string("day of month: ")
+ std::to_string(d));
x.type_ = MonthDayTime::month_day;
x.u = date::month(m)/d;
}
if (!is.eof() && ws(is) && !is.eof() && is.peek() != '#')
{
int t;
is >> t;
x.h_ = hours{t};
if (!is.eof() && is.peek() == ':')
{
is.get();
is >> t;
x.m_ = minutes{t};
if (!is.eof() && is.peek() == ':')
{
is.get();
is >> t;
x.s_ = seconds{t};
}
}
if (!is.eof() && std::isalpha(is.peek()))
{
char c;
is >> c;
switch (c)
{
case 's':
x.zone_ = tz::standard;
break;
case 'u':
x.zone_ = tz::utc;
break;
}
}
}
}
else
{
x.u = month{m}/1;
}
}
return is;
}
std::ostream&
detail::operator<<(std::ostream& os, const MonthDayTime& x)
{
switch (x.type_)
{
case MonthDayTime::month_day:
os << x.u.month_day_ << " ";
break;
case MonthDayTime::month_last_dow:
os << x.u.month_weekday_last_ << " ";
break;
case MonthDayTime::lteq:
os << x.u.month_day_weekday_.weekday_ << " on or before "
<< x.u.month_day_weekday_.month_day_ << " ";
break;
case MonthDayTime::gteq:
if ((static_cast<unsigned>(x.day()) - 1) % 7 == 0)
{
os << (x.u.month_day_weekday_.month_day_.month() /
x.u.month_day_weekday_.weekday_[
(static_cast<unsigned>(x.day()) - 1)/7+1]) << " ";
}
else
{
os << x.u.month_day_weekday_.weekday_ << " on or after "
<< x.u.month_day_weekday_.month_day_ << " ";
}
break;
}
os << date::make_time(x.s_ + x.h_ + x.m_);
if (x.zone_ == tz::utc)
os << "UTC ";
else if (x.zone_ == tz::standard)
os << "STD ";
else
os << " ";
return os;
}
// Rule
detail::Rule::Rule(const std::string& s)
{
try
{
using namespace date;
using namespace std::chrono;
std::istringstream in(s);
in.exceptions(std::ios::failbit | std::ios::badbit);
std::string word;
in >> word >> name_;
int x;
ws(in);
if (std::isalpha(in.peek()))
{
in >> word;
if (word == "min")
{
starting_year_ = year::min();
}
else
throw std::runtime_error("Didn't find expected word: " + word);
}
else
{
in >> x;
starting_year_ = year{x};
}
std::ws(in);
if (std::isalpha(in.peek()))
{
in >> word;
if (word == "only")
{
ending_year_ = starting_year_;
}
else if (word == "max")
{
ending_year_ = year::max();
}
else
throw std::runtime_error("Didn't find expected word: " + word);
}
else