forked from python/cpython
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path_zoneinfo.c
2843 lines (2447 loc) · 77.9 KB
/
_zoneinfo.c
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
#ifndef Py_BUILD_CORE_BUILTIN
# define Py_BUILD_CORE_MODULE 1
#endif
#include "Python.h"
#include "pycore_long.h" // _PyLong_GetOne()
#include "structmember.h"
#include <ctype.h>
#include <stddef.h>
#include <stdint.h>
#include "datetime.h"
#include "clinic/_zoneinfo.c.h"
/*[clinic input]
module zoneinfo
class zoneinfo.ZoneInfo "PyObject *" "PyTypeObject *"
[clinic start generated code]*/
/*[clinic end generated code: output=da39a3ee5e6b4b0d input=d12c73c0eef36df8]*/
typedef struct TransitionRuleType TransitionRuleType;
typedef struct StrongCacheNode StrongCacheNode;
typedef struct {
PyObject *utcoff;
PyObject *dstoff;
PyObject *tzname;
long utcoff_seconds;
} _ttinfo;
typedef struct {
_ttinfo std;
_ttinfo dst;
int dst_diff;
TransitionRuleType *start;
TransitionRuleType *end;
unsigned char std_only;
} _tzrule;
typedef struct {
PyDateTime_TZInfo base;
PyObject *key;
PyObject *file_repr;
PyObject *weakreflist;
size_t num_transitions;
size_t num_ttinfos;
int64_t *trans_list_utc;
int64_t *trans_list_wall[2];
_ttinfo **trans_ttinfos; // References to the ttinfo for each transition
_ttinfo *ttinfo_before;
_tzrule tzrule_after;
_ttinfo *_ttinfos; // Unique array of ttinfos for ease of deallocation
unsigned char fixed_offset;
unsigned char source;
} PyZoneInfo_ZoneInfo;
struct TransitionRuleType {
int64_t (*year_to_timestamp)(TransitionRuleType *, int);
};
typedef struct {
TransitionRuleType base;
uint8_t month;
uint8_t week;
uint8_t day;
int8_t hour;
int8_t minute;
int8_t second;
} CalendarRule;
typedef struct {
TransitionRuleType base;
uint8_t julian;
unsigned int day;
int8_t hour;
int8_t minute;
int8_t second;
} DayRule;
struct StrongCacheNode {
StrongCacheNode *next;
StrongCacheNode *prev;
PyObject *key;
PyObject *zone;
};
typedef struct {
PyTypeObject *ZoneInfoType;
// Imports
PyObject *io_open;
PyObject *_tzpath_find_tzfile;
PyObject *_common_mod;
// Caches
PyObject *TIMEDELTA_CACHE;
PyObject *ZONEINFO_WEAK_CACHE;
StrongCacheNode *ZONEINFO_STRONG_CACHE;
_ttinfo NO_TTINFO;
} zoneinfo_state;
// Constants
static const int EPOCHORDINAL = 719163;
static int DAYS_IN_MONTH[] = {
-1, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31,
};
static int DAYS_BEFORE_MONTH[] = {
-1, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334,
};
static const int SOURCE_NOCACHE = 0;
static const int SOURCE_CACHE = 1;
static const int SOURCE_FILE = 2;
static const size_t ZONEINFO_STRONG_CACHE_MAX_SIZE = 8;
// Forward declarations
static int
load_data(zoneinfo_state *state, PyZoneInfo_ZoneInfo *self,
PyObject *file_obj);
static void
utcoff_to_dstoff(size_t *trans_idx, long *utcoffs, long *dstoffs,
unsigned char *isdsts, size_t num_transitions,
size_t num_ttinfos);
static int
ts_to_local(size_t *trans_idx, int64_t *trans_utc, long *utcoff,
int64_t *trans_local[2], size_t num_ttinfos,
size_t num_transitions);
static int
parse_tz_str(zoneinfo_state *state, PyObject *tz_str_obj, _tzrule *out);
static Py_ssize_t
parse_abbr(const char *const p, PyObject **abbr);
static Py_ssize_t
parse_tz_delta(const char *const p, long *total_seconds);
static Py_ssize_t
parse_transition_time(const char *const p, int8_t *hour, int8_t *minute,
int8_t *second);
static Py_ssize_t
parse_transition_rule(const char *const p, TransitionRuleType **out);
static _ttinfo *
find_tzrule_ttinfo(_tzrule *rule, int64_t ts, unsigned char fold, int year);
static _ttinfo *
find_tzrule_ttinfo_fromutc(_tzrule *rule, int64_t ts, int year,
unsigned char *fold);
static int
build_ttinfo(zoneinfo_state *state, long utcoffset, long dstoffset,
PyObject *tzname, _ttinfo *out);
static void
xdecref_ttinfo(_ttinfo *ttinfo);
static int
ttinfo_eq(const _ttinfo *const tti0, const _ttinfo *const tti1);
static int
build_tzrule(zoneinfo_state *state, PyObject *std_abbr, PyObject *dst_abbr,
long std_offset, long dst_offset, TransitionRuleType *start,
TransitionRuleType *end, _tzrule *out);
static void
free_tzrule(_tzrule *tzrule);
static PyObject *
load_timedelta(zoneinfo_state *state, long seconds);
static int
get_local_timestamp(PyObject *dt, int64_t *local_ts);
static _ttinfo *
find_ttinfo(zoneinfo_state *state, PyZoneInfo_ZoneInfo *self, PyObject *dt);
static int
ymd_to_ord(int y, int m, int d);
static int
is_leap_year(int year);
static size_t
_bisect(const int64_t value, const int64_t *arr, size_t size);
static int
eject_from_strong_cache(zoneinfo_state *state, const PyTypeObject *const type,
PyObject *key);
static void
clear_strong_cache(zoneinfo_state *state, const PyTypeObject *const type);
static void
update_strong_cache(zoneinfo_state *state, const PyTypeObject *const type,
PyObject *key, PyObject *zone);
static PyObject *
zone_from_strong_cache(zoneinfo_state *state, const PyTypeObject *const type,
PyObject *const key);
static inline zoneinfo_state *
zoneinfo_get_state(PyObject *mod)
{
zoneinfo_state *state = (zoneinfo_state *)PyModule_GetState(mod);
assert(state != NULL);
return state;
}
static inline zoneinfo_state *
zoneinfo_get_state_by_cls(PyTypeObject *cls)
{
zoneinfo_state *state = (zoneinfo_state *)_PyType_GetModuleState(cls);
assert(state != NULL);
return state;
}
static struct PyModuleDef zoneinfomodule;
static inline zoneinfo_state *
zoneinfo_get_state_by_self(PyTypeObject *self)
{
PyObject *mod = PyType_GetModuleByDef(self, &zoneinfomodule);
assert(mod != NULL);
return zoneinfo_get_state(mod);
}
static PyObject *
zoneinfo_new_instance(zoneinfo_state *state, PyTypeObject *type, PyObject *key)
{
PyObject *file_obj = NULL;
PyObject *file_path = NULL;
file_path = PyObject_CallFunctionObjArgs(state->_tzpath_find_tzfile,
key, NULL);
if (file_path == NULL) {
return NULL;
}
else if (file_path == Py_None) {
PyObject *meth = state->_common_mod;
file_obj = PyObject_CallMethod(meth, "load_tzdata", "O", key);
if (file_obj == NULL) {
Py_DECREF(file_path);
return NULL;
}
}
PyObject *self = (PyObject *)(type->tp_alloc(type, 0));
if (self == NULL) {
goto error;
}
if (file_obj == NULL) {
PyObject *func = state->io_open;
file_obj = PyObject_CallFunction(func, "Os", file_path, "rb");
if (file_obj == NULL) {
goto error;
}
}
if (load_data(state, (PyZoneInfo_ZoneInfo *)self, file_obj)) {
goto error;
}
PyObject *rv = PyObject_CallMethod(file_obj, "close", NULL);
Py_SETREF(file_obj, NULL);
if (rv == NULL) {
goto error;
}
Py_DECREF(rv);
((PyZoneInfo_ZoneInfo *)self)->key = Py_NewRef(key);
goto cleanup;
error:
Py_CLEAR(self);
cleanup:
if (file_obj != NULL) {
PyObject *exc = PyErr_GetRaisedException();
PyObject *tmp = PyObject_CallMethod(file_obj, "close", NULL);
_PyErr_ChainExceptions1(exc);
if (tmp == NULL) {
Py_CLEAR(self);
}
Py_XDECREF(tmp);
Py_DECREF(file_obj);
}
Py_DECREF(file_path);
return self;
}
static PyObject *
get_weak_cache(zoneinfo_state *state, PyTypeObject *type)
{
if (type == state->ZoneInfoType) {
return state->ZONEINFO_WEAK_CACHE;
}
else {
PyObject *cache =
PyObject_GetAttrString((PyObject *)type, "_weak_cache");
// We are assuming that the type lives at least as long as the function
// that calls get_weak_cache, and that it holds a reference to the
// cache, so we'll return a "borrowed reference".
Py_XDECREF(cache);
return cache;
}
}
static PyObject *
zoneinfo_new(PyTypeObject *type, PyObject *args, PyObject *kw)
{
PyObject *key = NULL;
static char *kwlist[] = {"key", NULL};
if (PyArg_ParseTupleAndKeywords(args, kw, "O", kwlist, &key) == 0) {
return NULL;
}
zoneinfo_state *state = zoneinfo_get_state_by_self(type);
PyObject *instance = zone_from_strong_cache(state, type, key);
if (instance != NULL || PyErr_Occurred()) {
return instance;
}
PyObject *weak_cache = get_weak_cache(state, type);
instance = PyObject_CallMethod(weak_cache, "get", "O", key, Py_None);
if (instance == NULL) {
return NULL;
}
if (instance == Py_None) {
Py_DECREF(instance);
PyObject *tmp = zoneinfo_new_instance(state, type, key);
if (tmp == NULL) {
return NULL;
}
instance =
PyObject_CallMethod(weak_cache, "setdefault", "OO", key, tmp);
Py_DECREF(tmp);
if (instance == NULL) {
return NULL;
}
((PyZoneInfo_ZoneInfo *)instance)->source = SOURCE_CACHE;
}
update_strong_cache(state, type, key, instance);
return instance;
}
static int
zoneinfo_traverse(PyZoneInfo_ZoneInfo *self, visitproc visit, void *arg)
{
Py_VISIT(Py_TYPE(self));
Py_VISIT(self->key);
return 0;
}
static int
zoneinfo_clear(PyZoneInfo_ZoneInfo *self)
{
Py_CLEAR(self->key);
Py_CLEAR(self->file_repr);
return 0;
}
static void
zoneinfo_dealloc(PyObject *obj_self)
{
PyZoneInfo_ZoneInfo *self = (PyZoneInfo_ZoneInfo *)obj_self;
PyTypeObject *tp = Py_TYPE(self);
PyObject_GC_UnTrack(self);
if (self->weakreflist != NULL) {
PyObject_ClearWeakRefs(obj_self);
}
if (self->trans_list_utc != NULL) {
PyMem_Free(self->trans_list_utc);
}
for (size_t i = 0; i < 2; i++) {
if (self->trans_list_wall[i] != NULL) {
PyMem_Free(self->trans_list_wall[i]);
}
}
if (self->_ttinfos != NULL) {
for (size_t i = 0; i < self->num_ttinfos; ++i) {
xdecref_ttinfo(&(self->_ttinfos[i]));
}
PyMem_Free(self->_ttinfos);
}
if (self->trans_ttinfos != NULL) {
PyMem_Free(self->trans_ttinfos);
}
free_tzrule(&(self->tzrule_after));
zoneinfo_clear(self);
tp->tp_free(obj_self);
Py_DECREF(tp);
}
/*[clinic input]
@classmethod
zoneinfo.ZoneInfo.from_file
cls: defining_class
file_obj: object
/
key: object = None
Create a ZoneInfo file from a file object.
[clinic start generated code]*/
static PyObject *
zoneinfo_ZoneInfo_from_file_impl(PyTypeObject *type, PyTypeObject *cls,
PyObject *file_obj, PyObject *key)
/*[clinic end generated code: output=77887d1d56a48324 input=d26111f29eed6863]*/
{
PyObject *file_repr = NULL;
PyZoneInfo_ZoneInfo *self = NULL;
PyObject *obj_self = (PyObject *)(type->tp_alloc(type, 0));
self = (PyZoneInfo_ZoneInfo *)obj_self;
if (self == NULL) {
return NULL;
}
file_repr = PyUnicode_FromFormat("%R", file_obj);
if (file_repr == NULL) {
goto error;
}
zoneinfo_state *state = zoneinfo_get_state_by_cls(cls);
if (load_data(state, self, file_obj)) {
goto error;
}
self->source = SOURCE_FILE;
self->file_repr = file_repr;
self->key = Py_NewRef(key);
return obj_self;
error:
Py_XDECREF(file_repr);
Py_XDECREF(self);
return NULL;
}
/*[clinic input]
@classmethod
zoneinfo.ZoneInfo.no_cache
cls: defining_class
/
key: object
Get a new instance of ZoneInfo, bypassing the cache.
[clinic start generated code]*/
static PyObject *
zoneinfo_ZoneInfo_no_cache_impl(PyTypeObject *type, PyTypeObject *cls,
PyObject *key)
/*[clinic end generated code: output=b0b09b3344c171b7 input=0238f3d56b1ea3f1]*/
{
zoneinfo_state *state = zoneinfo_get_state_by_cls(cls);
PyObject *out = zoneinfo_new_instance(state, type, key);
if (out != NULL) {
((PyZoneInfo_ZoneInfo *)out)->source = SOURCE_NOCACHE;
}
return out;
}
/*[clinic input]
@classmethod
zoneinfo.ZoneInfo.clear_cache
cls: defining_class
/
*
only_keys: object = None
Clear the ZoneInfo cache.
[clinic start generated code]*/
static PyObject *
zoneinfo_ZoneInfo_clear_cache_impl(PyTypeObject *type, PyTypeObject *cls,
PyObject *only_keys)
/*[clinic end generated code: output=114d9b7c8a22e660 input=e32ca3bb396788ba]*/
{
zoneinfo_state *state = zoneinfo_get_state_by_cls(cls);
PyObject *weak_cache = get_weak_cache(state, type);
if (only_keys == NULL || only_keys == Py_None) {
PyObject *rv = PyObject_CallMethod(weak_cache, "clear", NULL);
if (rv != NULL) {
Py_DECREF(rv);
}
clear_strong_cache(state, type);
}
else {
PyObject *item = NULL;
PyObject *pop = PyUnicode_FromString("pop");
if (pop == NULL) {
return NULL;
}
PyObject *iter = PyObject_GetIter(only_keys);
if (iter == NULL) {
Py_DECREF(pop);
return NULL;
}
while ((item = PyIter_Next(iter))) {
// Remove from strong cache
if (eject_from_strong_cache(state, type, item) < 0) {
Py_DECREF(item);
break;
}
// Remove from weak cache
PyObject *tmp = PyObject_CallMethodObjArgs(weak_cache, pop, item,
Py_None, NULL);
Py_DECREF(item);
if (tmp == NULL) {
break;
}
Py_DECREF(tmp);
}
Py_DECREF(iter);
Py_DECREF(pop);
}
if (PyErr_Occurred()) {
return NULL;
}
Py_RETURN_NONE;
}
/*[clinic input]
zoneinfo.ZoneInfo.utcoffset
cls: defining_class
dt: object
/
Retrieve a timedelta representing the UTC offset in a zone at the given datetime.
[clinic start generated code]*/
static PyObject *
zoneinfo_ZoneInfo_utcoffset_impl(PyObject *self, PyTypeObject *cls,
PyObject *dt)
/*[clinic end generated code: output=b71016c319ba1f91 input=2bb6c5364938f19c]*/
{
zoneinfo_state *state = zoneinfo_get_state_by_cls(cls);
_ttinfo *tti = find_ttinfo(state, (PyZoneInfo_ZoneInfo *)self, dt);
if (tti == NULL) {
return NULL;
}
return Py_NewRef(tti->utcoff);
}
/*[clinic input]
zoneinfo.ZoneInfo.dst
cls: defining_class
dt: object
/
Retrieve a timedelta representing the amount of DST applied in a zone at the given datetime.
[clinic start generated code]*/
static PyObject *
zoneinfo_ZoneInfo_dst_impl(PyObject *self, PyTypeObject *cls, PyObject *dt)
/*[clinic end generated code: output=cb6168d7723a6ae6 input=2167fb80cf8645c6]*/
{
zoneinfo_state *state = zoneinfo_get_state_by_cls(cls);
_ttinfo *tti = find_ttinfo(state, (PyZoneInfo_ZoneInfo *)self, dt);
if (tti == NULL) {
return NULL;
}
return Py_NewRef(tti->dstoff);
}
/*[clinic input]
zoneinfo.ZoneInfo.tzname
cls: defining_class
dt: object
/
Retrieve a string containing the abbreviation for the time zone that applies in a zone at a given datetime.
[clinic start generated code]*/
static PyObject *
zoneinfo_ZoneInfo_tzname_impl(PyObject *self, PyTypeObject *cls,
PyObject *dt)
/*[clinic end generated code: output=3b6ae6c3053ea75a input=15a59a4f92ed1f1f]*/
{
zoneinfo_state *state = zoneinfo_get_state_by_cls(cls);
_ttinfo *tti = find_ttinfo(state, (PyZoneInfo_ZoneInfo *)self, dt);
if (tti == NULL) {
return NULL;
}
return Py_NewRef(tti->tzname);
}
#define GET_DT_TZINFO PyDateTime_DATE_GET_TZINFO
static PyObject *
zoneinfo_fromutc(PyObject *obj_self, PyObject *dt)
{
if (!PyDateTime_Check(dt)) {
PyErr_SetString(PyExc_TypeError,
"fromutc: argument must be a datetime");
return NULL;
}
if (GET_DT_TZINFO(dt) != obj_self) {
PyErr_SetString(PyExc_ValueError,
"fromutc: dt.tzinfo "
"is not self");
return NULL;
}
PyZoneInfo_ZoneInfo *self = (PyZoneInfo_ZoneInfo *)obj_self;
int64_t timestamp;
if (get_local_timestamp(dt, ×tamp)) {
return NULL;
}
size_t num_trans = self->num_transitions;
_ttinfo *tti = NULL;
unsigned char fold = 0;
if (num_trans >= 1 && timestamp < self->trans_list_utc[0]) {
tti = self->ttinfo_before;
}
else if (num_trans == 0 ||
timestamp > self->trans_list_utc[num_trans - 1]) {
tti = find_tzrule_ttinfo_fromutc(&(self->tzrule_after), timestamp,
PyDateTime_GET_YEAR(dt), &fold);
// Immediately after the last manual transition, the fold/gap is
// between self->trans_ttinfos[num_transitions - 1] and whatever
// ttinfo applies immediately after the last transition, not between
// the STD and DST rules in the tzrule_after, so we may need to
// adjust the fold value.
if (num_trans) {
_ttinfo *tti_prev = NULL;
if (num_trans == 1) {
tti_prev = self->ttinfo_before;
}
else {
tti_prev = self->trans_ttinfos[num_trans - 2];
}
int64_t diff = tti_prev->utcoff_seconds - tti->utcoff_seconds;
if (diff > 0 &&
timestamp < (self->trans_list_utc[num_trans - 1] + diff)) {
fold = 1;
}
}
}
else {
size_t idx = _bisect(timestamp, self->trans_list_utc, num_trans);
_ttinfo *tti_prev = NULL;
if (idx >= 2) {
tti_prev = self->trans_ttinfos[idx - 2];
tti = self->trans_ttinfos[idx - 1];
}
else {
tti_prev = self->ttinfo_before;
tti = self->trans_ttinfos[0];
}
// Detect fold
int64_t shift =
(int64_t)(tti_prev->utcoff_seconds - tti->utcoff_seconds);
if (shift > (timestamp - self->trans_list_utc[idx - 1])) {
fold = 1;
}
}
PyObject *tmp = PyNumber_Add(dt, tti->utcoff);
if (tmp == NULL) {
return NULL;
}
if (fold) {
if (PyDateTime_CheckExact(tmp)) {
((PyDateTime_DateTime *)tmp)->fold = 1;
dt = tmp;
}
else {
PyObject *replace = PyObject_GetAttrString(tmp, "replace");
PyObject *args = PyTuple_New(0);
PyObject *kwargs = PyDict_New();
Py_DECREF(tmp);
if (args == NULL || kwargs == NULL || replace == NULL) {
Py_XDECREF(args);
Py_XDECREF(kwargs);
Py_XDECREF(replace);
return NULL;
}
dt = NULL;
if (!PyDict_SetItemString(kwargs, "fold", _PyLong_GetOne())) {
dt = PyObject_Call(replace, args, kwargs);
}
Py_DECREF(args);
Py_DECREF(kwargs);
Py_DECREF(replace);
if (dt == NULL) {
return NULL;
}
}
}
else {
dt = tmp;
}
return dt;
}
static PyObject *
zoneinfo_repr(PyZoneInfo_ZoneInfo *self)
{
PyObject *rv = NULL;
const char *type_name = Py_TYPE((PyObject *)self)->tp_name;
if (!(self->key == Py_None)) {
rv = PyUnicode_FromFormat("%s(key=%R)", type_name, self->key);
}
else {
assert(PyUnicode_Check(self->file_repr));
rv = PyUnicode_FromFormat("%s.from_file(%U)", type_name,
self->file_repr);
}
return rv;
}
static PyObject *
zoneinfo_str(PyZoneInfo_ZoneInfo *self)
{
if (!(self->key == Py_None)) {
return Py_NewRef(self->key);
}
else {
return zoneinfo_repr(self);
}
}
/* Pickles the ZoneInfo object by key and source.
*
* ZoneInfo objects are pickled by reference to the TZif file that they came
* from, which means that the exact transitions may be different or the file
* may not un-pickle if the data has changed on disk in the interim.
*
* It is necessary to include a bit indicating whether or not the object
* was constructed from the cache, because from-cache objects will hit the
* unpickling process's cache, whereas no-cache objects will bypass it.
*
* Objects constructed from ZoneInfo.from_file cannot be pickled.
*/
static PyObject *
zoneinfo_reduce(PyObject *obj_self, PyObject *unused)
{
PyZoneInfo_ZoneInfo *self = (PyZoneInfo_ZoneInfo *)obj_self;
if (self->source == SOURCE_FILE) {
// Objects constructed from files cannot be pickled.
PyObject *pickle_error =
_PyImport_GetModuleAttrString("pickle", "PicklingError");
if (pickle_error == NULL) {
return NULL;
}
PyErr_Format(pickle_error,
"Cannot pickle a ZoneInfo file from a file stream.");
Py_DECREF(pickle_error);
return NULL;
}
unsigned char from_cache = self->source == SOURCE_CACHE ? 1 : 0;
PyObject *constructor = PyObject_GetAttrString(obj_self, "_unpickle");
if (constructor == NULL) {
return NULL;
}
PyObject *rv = Py_BuildValue("O(OB)", constructor, self->key, from_cache);
Py_DECREF(constructor);
return rv;
}
/*[clinic input]
@classmethod
zoneinfo.ZoneInfo._unpickle
cls: defining_class
key: object
from_cache: unsigned_char(bitwise=True)
/
Private method used in unpickling.
[clinic start generated code]*/
static PyObject *
zoneinfo_ZoneInfo__unpickle_impl(PyTypeObject *type, PyTypeObject *cls,
PyObject *key, unsigned char from_cache)
/*[clinic end generated code: output=556712fc709deecb input=6ac8c73eed3de316]*/
{
if (from_cache) {
PyObject *val_args = Py_BuildValue("(O)", key);
if (val_args == NULL) {
return NULL;
}
PyObject *rv = zoneinfo_new(type, val_args, NULL);
Py_DECREF(val_args);
return rv;
}
else {
zoneinfo_state *state = zoneinfo_get_state_by_cls(cls);
return zoneinfo_new_instance(state, type, key);
}
}
/* It is relatively expensive to construct new timedelta objects, and in most
* cases we're looking at a relatively small number of timedeltas, such as
* integer number of hours, etc. We will keep a cache so that we construct
* a minimal number of these.
*
* Possibly this should be replaced with an LRU cache so that it's not possible
* for the memory usage to explode from this, but in order for this to be a
* serious problem, one would need to deliberately craft a malicious time zone
* file with many distinct offsets. As of tzdb 2019c, loading every single zone
* fills the cache with ~450 timedeltas for a total size of ~12kB.
*
* This returns a new reference to the timedelta.
*/
static PyObject *
load_timedelta(zoneinfo_state *state, long seconds)
{
PyObject *rv;
PyObject *pyoffset = PyLong_FromLong(seconds);
if (pyoffset == NULL) {
return NULL;
}
rv = PyDict_GetItemWithError(state->TIMEDELTA_CACHE, pyoffset);
if (rv == NULL) {
if (PyErr_Occurred()) {
goto error;
}
PyObject *tmp = PyDateTimeAPI->Delta_FromDelta(
0, seconds, 0, 1, PyDateTimeAPI->DeltaType);
if (tmp == NULL) {
goto error;
}
rv = PyDict_SetDefault(state->TIMEDELTA_CACHE, pyoffset, tmp);
Py_DECREF(tmp);
}
Py_XINCREF(rv);
Py_DECREF(pyoffset);
return rv;
error:
Py_DECREF(pyoffset);
return NULL;
}
/* Constructor for _ttinfo object - this starts by initializing the _ttinfo
* to { NULL, NULL, NULL }, so that Py_XDECREF will work on partially
* initialized _ttinfo objects.
*/
static int
build_ttinfo(zoneinfo_state *state, long utcoffset, long dstoffset,
PyObject *tzname, _ttinfo *out)
{
out->utcoff = NULL;
out->dstoff = NULL;
out->tzname = NULL;
out->utcoff_seconds = utcoffset;
out->utcoff = load_timedelta(state, utcoffset);
if (out->utcoff == NULL) {
return -1;
}
out->dstoff = load_timedelta(state, dstoffset);
if (out->dstoff == NULL) {
return -1;
}
out->tzname = Py_NewRef(tzname);
return 0;
}
/* Decrease reference count on any non-NULL members of a _ttinfo */
static void
xdecref_ttinfo(_ttinfo *ttinfo)
{
if (ttinfo != NULL) {
Py_XDECREF(ttinfo->utcoff);
Py_XDECREF(ttinfo->dstoff);
Py_XDECREF(ttinfo->tzname);
}
}
/* Equality function for _ttinfo. */
static int
ttinfo_eq(const _ttinfo *const tti0, const _ttinfo *const tti1)
{
int rv;
if ((rv = PyObject_RichCompareBool(tti0->utcoff, tti1->utcoff, Py_EQ)) <
1) {
goto end;
}
if ((rv = PyObject_RichCompareBool(tti0->dstoff, tti1->dstoff, Py_EQ)) <
1) {
goto end;
}
if ((rv = PyObject_RichCompareBool(tti0->tzname, tti1->tzname, Py_EQ)) <
1) {
goto end;
}
end:
return rv;
}
/* Given a file-like object, this populates a ZoneInfo object
*
* The current version calls into a Python function to read the data from
* file into Python objects, and this translates those Python objects into
* C values and calculates derived values (e.g. dstoff) in C.
*
* This returns 0 on success and -1 on failure.
*
* The function will never return while `self` is partially initialized —
* the object only needs to be freed / deallocated if this succeeds.
*/
static int
load_data(zoneinfo_state *state, PyZoneInfo_ZoneInfo *self, PyObject *file_obj)
{
PyObject *data_tuple = NULL;
long *utcoff = NULL;
long *dstoff = NULL;
size_t *trans_idx = NULL;
unsigned char *isdst = NULL;
self->trans_list_utc = NULL;
self->trans_list_wall[0] = NULL;
self->trans_list_wall[1] = NULL;
self->trans_ttinfos = NULL;
self->_ttinfos = NULL;
self->file_repr = NULL;
size_t ttinfos_allocated = 0;
data_tuple = PyObject_CallMethod(state->_common_mod, "load_data", "O",
file_obj);
if (data_tuple == NULL) {
goto error;
}
if (!PyTuple_CheckExact(data_tuple)) {
PyErr_Format(PyExc_TypeError, "Invalid data result type: %r",
data_tuple);
goto error;
}
// Unpack the data tuple
PyObject *trans_idx_list = PyTuple_GetItem(data_tuple, 0);
if (trans_idx_list == NULL) {
goto error;
}
PyObject *trans_utc = PyTuple_GetItem(data_tuple, 1);
if (trans_utc == NULL) {
goto error;
}
PyObject *utcoff_list = PyTuple_GetItem(data_tuple, 2);
if (utcoff_list == NULL) {
goto error;
}
PyObject *isdst_list = PyTuple_GetItem(data_tuple, 3);
if (isdst_list == NULL) {
goto error;