forked from HowardHinnant/date
-
Notifications
You must be signed in to change notification settings - Fork 0
/
tz.cpp
2233 lines (2094 loc) · 66.4 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 Howard Hinnant
// Copyright (c) 2015 Ville Voutilainen
//
// 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.
#include "tz_private.h"
#include <algorithm>
#include <cctype>
#include <cstdlib>
#include <fstream>
#include <iostream>
#include <iterator>
#include <memory>
#include <sstream>
#include <string>
#include <tuple>
#include <vector>
#include <sys/stat.h>
#ifdef _WIN32
#include <locale>
#include <codecvt>
#endif
#if TIMEZONE_MAPPING
// Timezone mapping maps native (e.g. Windows) timezone names to the "Standard" names
// used by this library.
// The mapping process parses a CSV file of mapping data and uses std::quoted to do that.
// Because std::quoted is a C++14 feature found in <iomanip> any platforms using
// the mapping process require C++14.
// Windows uses the mapping process so C++14 is required on Windows.
// VS2015 supports std::quoted but there is no -std=c++14 flag required to enable it.
// MinGW on Windows also requires the mapping process so -std=c++14 is required
// when using g++ or clang.
// On Linux/Mac, no mapping / CSV file is required so std::quoted and C++14 isn't needed
// and so on these platforms C++11 should work but C++14 is preferred even there too
// because the date library in general works better with C++14.
#include <iomanip>
#endif
// 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
// Prevent windows defining min/max macros that will interfere with C++ versions.
#ifndef NOMINMAX
#define NOMINMAX
#endif
// We don't need everything Windows.h has to offer.
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN
#endif
#include <Windows.h>
#include <io.h>
#else
#include <unistd.h>
#endif
namespace date
{
// +---------------------+
// | Begin Configuration |
// +---------------------+
#if _WIN32 // TODO: sensible default for all platforms.
static std::string install{ "c:\\tzdata" };
#else
static std::string install{ "/Users/howardhinnant/Downloads/tzdata2016a" };
#endif
static const std::vector<std::string> files =
{
"africa", "antarctica", "asia", "australasia", "backward", "etcetera", "europe",
"pacificnew", "northamerica", "southamerica", "systemv", "leapseconds"
};
// 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();
// Arbitrary day of the year that will be away from any limits.
// Used with year::min() and year::max().
CONSTDATA auto boring_day = date::aug/18;
// +-------------------+
// | End Configuration |
// +-------------------+
#if _MSC_VER && ! defined(__clang__) && ! defined( __GNUG__)
// We can't use static_assert here for MSVC (yet) because
// the expression isn't constexpr in MSVC yet.
// FIXME! Remove this when MSVC's constexpr support improves.
#else
static_assert(min_year <= max_year, "Configuration error");
#endif
#if __cplusplus >= 201402
static_assert(boring_day.ok(), "Configuration error");
#endif
// Until filesystem arrives.
static const char folder_delimiter =
#ifdef _WIN32
'\\';
#else
'/';
#endif
static bool file_exists(const std::string& filename)
{
#ifdef _WIN32
return ::_access(filename.c_str(), 0) == 0;
#else
return ::access(filename.c_str(), F_OK) == 0;
#endif
}
#ifdef _WIN32
// Win32 support requires calling OS functions.
// This routine maps OS error codes to readable text strngs.
static std::string get_win32_message(DWORD error_code)
{
struct free_message {
void operator()(char buf[]) {
if (buf != nullptr)
{
auto result = HeapFree(GetProcessHeap(), 0, buf);
assert(result != 0);
}
}
};
char* msg = nullptr;
auto result = FormatMessageA(
FORMAT_MESSAGE_ALLOCATE_BUFFER | FORMAT_MESSAGE_FROM_SYSTEM
| FORMAT_MESSAGE_IGNORE_INSERTS,
nullptr, error_code, MAKELANGID(LANG_NEUTRAL, SUBLANG_DEFAULT),
reinterpret_cast<char*>(&msg), 0, nullptr );
std::unique_ptr<char[], free_message> message_buffer(msg);
if (result == 0) // If there is no error message, still give the code.
{
std::string err = "Error getting message for error number ";
err += std::to_string(error_code);
return err;
}
assert(message_buffer.get() != nullptr);
return std::string(message_buffer.get());
}
#endif
#if TIMEZONE_MAPPING
namespace // Put types in an anonymous name space.
{
// A simple type to manage RAII for key handles and to
// implement the trivial registry interface we need.
// Not intended to be general-purpose.
class reg_key
{
private:
// Note there is no value documented to be an invalid handle value.
// Not NULL nor INVALID_HANDLE_VALUE. We must rely on is_open.
HKEY m_key = nullptr;
bool m_is_open = false;
public:
HKEY handle()
{
return m_key;
}
bool is_open() const
{
return m_is_open;
}
LONG open(const wchar_t* key_name)
{
LONG result;
result = RegOpenKeyExW(HKEY_LOCAL_MACHINE, key_name, 0, KEY_READ, &m_key);
if (result == ERROR_SUCCESS)
m_is_open = true;
return result;
}
LONG close()
{
if (m_is_open)
{
auto result = RegCloseKey(m_key);
assert(result == ERROR_SUCCESS);
if (result == ERROR_SUCCESS)
{
m_is_open = false;
m_key = nullptr;
}
return result;
}
return ERROR_SUCCESS;
}
// WARNING: this function has a hard-coded value size limit.
// It is not a general-purpose function.
// It should be sufficient for our use cases.
// The function could be made workable for any size string
// but we don't need the complexity of implementing that
// for our meagre purposes right now.
bool get_string(const wchar_t* key_name, std::string& value)
{
value.clear();
wchar_t value_buffer[256];
// in/out parameter. Documentation say that size is a count of bytes not chars.
DWORD size = sizeof(value_buffer);
DWORD tzi_type = REG_SZ;
if (RegQueryValueExW(handle(), key_name, nullptr, &tzi_type,
reinterpret_cast<LPBYTE>(value_buffer), &size) == ERROR_SUCCESS)
{
// Function does not guarantee to null terminate.
value_buffer[size] = L'\0';
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
value = converter.to_bytes(value_buffer);
return true;
}
return false;
}
bool get_binary(const wchar_t* key_name, void* value, int value_size)
{
DWORD size = value_size;
DWORD type = REG_BINARY;
if (RegQueryValueExW(handle(), key_name, nullptr, &type,
reinterpret_cast<LPBYTE>(value), &size) == ERROR_SUCCESS
&& (int) size == value_size)
return true;
return false;
}
~reg_key()
{
close();
}
};
} // anonymous namespace
template < typename T, size_t N >
static inline size_t countof(T(&arr)[N])
{
return std::extent< T[N] >::value;
}
// This function returns an exhaustive list of time zone information
// from the Windows registry.
// The routine tries to load as many time zone entries as possible despite errors.
// We don't want to fail to load the whole database just because one record can't be read.
static void get_windows_timezone_info(std::vector<timezone_info>& tz_list)
{
tz_list.clear();
LONG result;
// Open the parent time zone key that has the list of timezones in.
reg_key zones_key;
static const wchar_t zones_key_name[] =
{ L"SOFTWARE\\Microsoft\\Windows NT\\CurrentVersion\\Time Zones" };
result = zones_key.open(zones_key_name);
// TODO! Review if this should happen here or be signalled later.
// We don't want the process to fail on startup because of this.
if (result != ERROR_SUCCESS)
throw std::runtime_error("Time Zone registry key could not be opened: "
+ get_win32_message(result));
DWORD size;
wchar_t zone_key_name[256];
std::wstring value;
// Iterate through the list of keys of the parent time zones key to get
// each key that identifies each individual timezone.
std::wstring full_zone_key_name;
for (DWORD zone_index = 0; ; ++zone_index)
{
timezone_info tz;
size = (DWORD) sizeof(zone_key_name);
auto status = RegEnumKeyExW(zones_key.handle(), zone_index, zone_key_name, &size,
nullptr, nullptr, nullptr, nullptr);
if (status != ERROR_SUCCESS && status != ERROR_NO_MORE_ITEMS)
throw std::runtime_error("Can't enumerate time zone registry key"
+ get_win32_message(status));
if (status == ERROR_NO_MORE_ITEMS)
break;
zone_key_name[size] = L'\0';
std::wstring_convert<std::codecvt_utf8_utf16<wchar_t>> converter;
tz.timezone_id = converter.to_bytes(zone_key_name);
full_zone_key_name = zones_key_name;
full_zone_key_name += L'\\';
full_zone_key_name += zone_key_name;
// If any field fails to be found, consider the whole time zone
// entry corrupt and move onto the next. See comments
// at the top of function.
reg_key zone_key;
if (zone_key.open(full_zone_key_name.c_str()) != ERROR_SUCCESS)
continue;
if (!zone_key.get_string(L"Std", tz.standard_name))
continue;
#if 0
// TBD these fields are not required yet.
// They might be useful for test cases though.
if (!zone_key.get_string("Display", tz.display_name))
continue;
if (!zone_key.get_binary("TZI", &tz.tzi, sizeof(TZI)))
continue;
#endif
zone_key.close();
tz_list.push_back(std::move(tz));
}
result = zones_key.close();
}
// standard_name is the StandardName field from the Windows
// TIME_ZONE_INFORMATION structure.
// See the Windows API function GetTimeZoneInformation.
// The standard_name is also the value from STD field of
// under the windows registry key Time Zones.
// To be clear, standard_name does NOT represent a windows timezone id
// or an IANA tzid
static const timezone_info* find_native_timezone_by_standard_name(
const std::string& standard_name)
{
// TODO! we can improve on linear search.
const auto& native_zones = get_tzdb().native_zones;
for (const auto& tz : native_zones)
{
if (tz.standard_name == standard_name)
return &tz;
}
return nullptr;
}
// Read CSV file of "other","territory","type".
// See timezone_mapping structure for more info.
// This function should be kept in sync with the code that writes this file.
static std::vector<timezone_mapping>
load_timezone_mappings_from_csv_file(const std::string& input_path)
{
size_t line = 1;
std::vector<timezone_mapping> mappings;
std::ifstream is(input_path, std::ios_base::in | std::ios_base::binary);
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;
throw std::runtime_error(msg);
}
auto error = [&](const char* info)
{
std::string msg = "Error reading zone mapping file at line ";
msg += std::to_string(line);
msg += ": ";
msg += info;
throw std::runtime_error(msg);
};
auto read_field_delim = [&]()
{
char field_delim;
is.read(&field_delim, 1);
if (is.gcount() != 1 || field_delim != ',')
error("delimiter ',' expected");
};
std::string copyright;
for (int i = 0; i < 4; ++i)
getline(is, copyright);
for (;;)
{
timezone_mapping zm{};
char ch;
is.read(&ch, 1);
if (is.eof())
break;
std::getline(is, zm.other, '\"');
read_field_delim();
is.read(&ch, 1);
std::getline(is, zm.territory, '\"');
read_field_delim();
is.read(&ch, 1);
std::getline(is, zm.type, '\"');
is.read(&ch, 1);
if (is.gcount() != 1 || ch != '\n')
error("record delimiter LF expected");
if (is.fail() || is.eof())
error("unexpected end of file, file read error or formatting error.");
++line;
mappings.push_back(std::move(zm));
}
is.close();
return mappings;
}
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;
}
#endif
// 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)
{
const 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)
{
const 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
MonthDayTime::MonthDayTime(second_point tp, tz timezone)
: zone_(timezone)
{
using namespace date;
const auto dp = 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();
}
MonthDayTime::MonthDayTime(const date::month_day& md, tz timezone)
: zone_(timezone)
{
u = md;
}
date::day
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
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
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_day_point(y);
auto dp1 = x.to_day_point(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;
}
second_point
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;
}
MonthDayTime::U&
MonthDayTime::U::operator=(const date::month_day& x)
{
month_day_ = x;
return *this;
}
MonthDayTime::U&
MonthDayTime::U::operator=(const date::month_weekday_last& x)
{
month_weekday_last_ = x;
return *this;
}
MonthDayTime::U&
MonthDayTime::U::operator=(const pair& x)
{
month_day_weekday_ = x;
return *this;
}
date::day_point
MonthDayTime::to_day_point(date::year y) const
{
using namespace std::chrono;
using namespace date;
switch (type_)
{
case month_day:
return day_point(y/u.month_day_);
case month_last_dow:
return day_point(y/u.month_weekday_last_);
case lteq:
{
auto const x = y/u.month_day_weekday_.month_day_;
auto const wd1 = weekday(x);
auto const wd0 = u.month_day_weekday_.weekday_;
return day_point(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(x);
return day_point(x) + (wd1-wd0);
}
second_point
MonthDayTime::to_time_point(date::year y) const
{
return to_day_point(y) + h_ + m_ + s_;
}
void
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(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(x);
auto const wd0 = u.month_day_weekday_.weekday_;
auto const ymd = year_month_day(day_point(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(x);
auto const ymd = year_month_day(day_point(x) + (wd1-wd0));
u.month_day_ = ymd.month()/ymd.day();
type_ = month_day;
return;
}
}
}
std::istream&
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&
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.h_ + x.m_ + x.s_);
if (x.zone_ == tz::utc)
os << "UTC ";
else if (x.zone_ == tz::standard)
os << "STD ";
else
os << " ";
return os;
}
// Rule
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
{
in >> x;
ending_year_ = year{x};
}
in >> word; // TYPE (always "-")
assert(word == "-");
in >> starting_at_;
save_ = duration_cast<minutes>(parse_signed_time(in));
in >> abbrev_;
if (abbrev_ == "-")
abbrev_.clear();
assert(hours{0} <= save_ && save_ <= hours{2});
}
catch (...)
{
std::cerr << s << '\n';
std::cerr << *this << '\n';
throw;
}
}
Rule::Rule(const Rule& r, date::year starting_year, date::year ending_year)
: name_(r.name_)
, starting_year_(starting_year)
, ending_year_(ending_year)
, starting_at_(r.starting_at_)
, save_(r.save_)
, abbrev_(r.abbrev_)
{
}
bool
operator==(const Rule& x, const Rule& y)
{
if (std::tie(x.name_, x.save_, x.starting_year_, x.ending_year_) ==
std::tie(y.name_, y.save_, y.starting_year_, y.ending_year_))
return x.month() == y.month() && x.day() == y.day();
return false;
}
bool
operator<(const Rule& x, const Rule& y)
{
using namespace std::chrono;
auto const xm = x.month();
auto const ym = y.month();
if (std::tie(x.name_, x.starting_year_, xm, x.ending_year_) <
std::tie(y.name_, y.starting_year_, ym, y.ending_year_))
return true;
if (std::tie(x.name_, x.starting_year_, xm, x.ending_year_) >
std::tie(y.name_, y.starting_year_, ym, y.ending_year_))
return false;
return x.day() < y.day();
}
bool
operator==(const Rule& x, const date::year& y)
{
return x.starting_year_ <= y && y <= x.ending_year_;
}
bool
operator<(const Rule& x, const date::year& y)
{
return x.ending_year_ < y;
}
bool
operator==(const date::year& x, const Rule& y)
{
return y.starting_year_ <= x && x <= y.ending_year_;
}
bool
operator<(const date::year& x, const Rule& y)
{
return x < y.starting_year_;
}
bool
operator==(const Rule& x, const std::string& y)
{
return x.name() == y;
}
bool
operator<(const Rule& x, const std::string& y)
{
return x.name() < y;
}