• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*  C implementation for the date/time type documented at
2  *  http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
3  */
4 
5 #define PY_SSIZE_T_CLEAN
6 
7 #include "Python.h"
8 #include "modsupport.h"
9 #include "structmember.h"
10 
11 #include <time.h>
12 
13 #include "timefuncs.h"
14 
15 /* Differentiate between building the core module and building extension
16  * modules.
17  */
18 #ifndef Py_BUILD_CORE
19 #define Py_BUILD_CORE
20 #endif
21 #include "datetime.h"
22 #undef Py_BUILD_CORE
23 
24 /* We require that C int be at least 32 bits, and use int virtually
25  * everywhere.  In just a few cases we use a temp long, where a Python
26  * API returns a C long.  In such cases, we have to ensure that the
27  * final result fits in a C int (this can be an issue on 64-bit boxes).
28  */
29 #if SIZEOF_INT < 4
30 #       error "datetime.c requires that C int have at least 32 bits"
31 #endif
32 
33 #define MINYEAR 1
34 #define MAXYEAR 9999
35 #define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */
36 
37 /* Nine decimal digits is easy to communicate, and leaves enough room
38  * so that two delta days can be added w/o fear of overflowing a signed
39  * 32-bit int, and with plenty of room left over to absorb any possible
40  * carries from adding seconds.
41  */
42 #define MAX_DELTA_DAYS 999999999
43 
44 /* Rename the long macros in datetime.h to more reasonable short names. */
45 #define GET_YEAR                PyDateTime_GET_YEAR
46 #define GET_MONTH               PyDateTime_GET_MONTH
47 #define GET_DAY                 PyDateTime_GET_DAY
48 #define DATE_GET_HOUR           PyDateTime_DATE_GET_HOUR
49 #define DATE_GET_MINUTE         PyDateTime_DATE_GET_MINUTE
50 #define DATE_GET_SECOND         PyDateTime_DATE_GET_SECOND
51 #define DATE_GET_MICROSECOND    PyDateTime_DATE_GET_MICROSECOND
52 
53 /* Date accessors for date and datetime. */
54 #define SET_YEAR(o, v)          (((o)->data[0] = ((v) & 0xff00) >> 8), \
55                  ((o)->data[1] = ((v) & 0x00ff)))
56 #define SET_MONTH(o, v)         (PyDateTime_GET_MONTH(o) = (v))
57 #define SET_DAY(o, v)           (PyDateTime_GET_DAY(o) = (v))
58 
59 /* Date/Time accessors for datetime. */
60 #define DATE_SET_HOUR(o, v)     (PyDateTime_DATE_GET_HOUR(o) = (v))
61 #define DATE_SET_MINUTE(o, v)   (PyDateTime_DATE_GET_MINUTE(o) = (v))
62 #define DATE_SET_SECOND(o, v)   (PyDateTime_DATE_GET_SECOND(o) = (v))
63 #define DATE_SET_MICROSECOND(o, v)      \
64     (((o)->data[7] = ((v) & 0xff0000) >> 16), \
65      ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
66      ((o)->data[9] = ((v) & 0x0000ff)))
67 
68 /* Time accessors for time. */
69 #define TIME_GET_HOUR           PyDateTime_TIME_GET_HOUR
70 #define TIME_GET_MINUTE         PyDateTime_TIME_GET_MINUTE
71 #define TIME_GET_SECOND         PyDateTime_TIME_GET_SECOND
72 #define TIME_GET_MICROSECOND    PyDateTime_TIME_GET_MICROSECOND
73 #define TIME_SET_HOUR(o, v)     (PyDateTime_TIME_GET_HOUR(o) = (v))
74 #define TIME_SET_MINUTE(o, v)   (PyDateTime_TIME_GET_MINUTE(o) = (v))
75 #define TIME_SET_SECOND(o, v)   (PyDateTime_TIME_GET_SECOND(o) = (v))
76 #define TIME_SET_MICROSECOND(o, v)      \
77     (((o)->data[3] = ((v) & 0xff0000) >> 16), \
78      ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
79      ((o)->data[5] = ((v) & 0x0000ff)))
80 
81 /* Delta accessors for timedelta. */
82 #define GET_TD_DAYS(o)          (((PyDateTime_Delta *)(o))->days)
83 #define GET_TD_SECONDS(o)       (((PyDateTime_Delta *)(o))->seconds)
84 #define GET_TD_MICROSECONDS(o)  (((PyDateTime_Delta *)(o))->microseconds)
85 
86 #define SET_TD_DAYS(o, v)       ((o)->days = (v))
87 #define SET_TD_SECONDS(o, v)    ((o)->seconds = (v))
88 #define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
89 
90 /* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
91  * p->hastzinfo.
92  */
93 #define HASTZINFO(p)            (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
94 
95 /* M is a char or int claiming to be a valid month.  The macro is equivalent
96  * to the two-sided Python test
97  *      1 <= M <= 12
98  */
99 #define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
100 
101 /* Forward declarations. */
102 static PyTypeObject PyDateTime_DateType;
103 static PyTypeObject PyDateTime_DateTimeType;
104 static PyTypeObject PyDateTime_DeltaType;
105 static PyTypeObject PyDateTime_TimeType;
106 static PyTypeObject PyDateTime_TZInfoType;
107 
108 /* ---------------------------------------------------------------------------
109  * Math utilities.
110  */
111 
112 /* k = i+j overflows iff k differs in sign from both inputs,
113  * iff k^i has sign bit set and k^j has sign bit set,
114  * iff (k^i)&(k^j) has sign bit set.
115  */
116 #define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
117     ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
118 
119 /* Compute Python divmod(x, y), returning the quotient and storing the
120  * remainder into *r.  The quotient is the floor of x/y, and that's
121  * the real point of this.  C will probably truncate instead (C99
122  * requires truncation; C89 left it implementation-defined).
123  * Simplification:  we *require* that y > 0 here.  That's appropriate
124  * for all the uses made of it.  This simplifies the code and makes
125  * the overflow case impossible (divmod(LONG_MIN, -1) is the only
126  * overflow case).
127  */
128 static int
divmod(int x,int y,int * r)129 divmod(int x, int y, int *r)
130 {
131     int quo;
132 
133     assert(y > 0);
134     quo = x / y;
135     *r = x - quo * y;
136     if (*r < 0) {
137         --quo;
138         *r += y;
139     }
140     assert(0 <= *r && *r < y);
141     return quo;
142 }
143 
144 /* Round a double to the nearest long.  |x| must be small enough to fit
145  * in a C long; this is not checked.
146  */
147 static long
round_to_long(double x)148 round_to_long(double x)
149 {
150     if (x >= 0.0)
151         x = floor(x + 0.5);
152     else
153         x = ceil(x - 0.5);
154     return (long)x;
155 }
156 
157 /* ---------------------------------------------------------------------------
158  * General calendrical helper functions
159  */
160 
161 /* For each month ordinal in 1..12, the number of days in that month,
162  * and the number of days before that month in the same year.  These
163  * are correct for non-leap years only.
164  */
165 static int _days_in_month[] = {
166     0, /* unused; this vector uses 1-based indexing */
167     31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
168 };
169 
170 static int _days_before_month[] = {
171     0, /* unused; this vector uses 1-based indexing */
172     0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
173 };
174 
175 /* year -> 1 if leap year, else 0. */
176 static int
is_leap(int year)177 is_leap(int year)
178 {
179     /* Cast year to unsigned.  The result is the same either way, but
180      * C can generate faster code for unsigned mod than for signed
181      * mod (especially for % 4 -- a good compiler should just grab
182      * the last 2 bits when the LHS is unsigned).
183      */
184     const unsigned int ayear = (unsigned int)year;
185     return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
186 }
187 
188 /* year, month -> number of days in that month in that year */
189 static int
days_in_month(int year,int month)190 days_in_month(int year, int month)
191 {
192     assert(month >= 1);
193     assert(month <= 12);
194     if (month == 2 && is_leap(year))
195         return 29;
196     else
197         return _days_in_month[month];
198 }
199 
200 /* year, month -> number of days in year preceding first day of month */
201 static int
days_before_month(int year,int month)202 days_before_month(int year, int month)
203 {
204     int days;
205 
206     assert(month >= 1);
207     assert(month <= 12);
208     days = _days_before_month[month];
209     if (month > 2 && is_leap(year))
210         ++days;
211     return days;
212 }
213 
214 /* year -> number of days before January 1st of year.  Remember that we
215  * start with year 1, so days_before_year(1) == 0.
216  */
217 static int
days_before_year(int year)218 days_before_year(int year)
219 {
220     int y = year - 1;
221     /* This is incorrect if year <= 0; we really want the floor
222      * here.  But so long as MINYEAR is 1, the smallest year this
223      * can see is 0 (this can happen in some normalization endcases),
224      * so we'll just special-case that.
225      */
226     assert (year >= 0);
227     if (y >= 0)
228         return y*365 + y/4 - y/100 + y/400;
229     else {
230         assert(y == -1);
231         return -366;
232     }
233 }
234 
235 /* Number of days in 4, 100, and 400 year cycles.  That these have
236  * the correct values is asserted in the module init function.
237  */
238 #define DI4Y    1461    /* days_before_year(5); days in 4 years */
239 #define DI100Y  36524   /* days_before_year(101); days in 100 years */
240 #define DI400Y  146097  /* days_before_year(401); days in 400 years  */
241 
242 /* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
243 static void
ord_to_ymd(int ordinal,int * year,int * month,int * day)244 ord_to_ymd(int ordinal, int *year, int *month, int *day)
245 {
246     int n, n1, n4, n100, n400, leapyear, preceding;
247 
248     /* ordinal is a 1-based index, starting at 1-Jan-1.  The pattern of
249      * leap years repeats exactly every 400 years.  The basic strategy is
250      * to find the closest 400-year boundary at or before ordinal, then
251      * work with the offset from that boundary to ordinal.  Life is much
252      * clearer if we subtract 1 from ordinal first -- then the values
253      * of ordinal at 400-year boundaries are exactly those divisible
254      * by DI400Y:
255      *
256      *    D  M   Y            n              n-1
257      *    -- --- ----        ----------     ----------------
258      *    31 Dec -400        -DI400Y       -DI400Y -1
259      *     1 Jan -399         -DI400Y +1   -DI400Y      400-year boundary
260      *    ...
261      *    30 Dec  000        -1             -2
262      *    31 Dec  000         0             -1
263      *     1 Jan  001         1              0          400-year boundary
264      *     2 Jan  001         2              1
265      *     3 Jan  001         3              2
266      *    ...
267      *    31 Dec  400         DI400Y        DI400Y -1
268      *     1 Jan  401         DI400Y +1     DI400Y      400-year boundary
269      */
270     assert(ordinal >= 1);
271     --ordinal;
272     n400 = ordinal / DI400Y;
273     n = ordinal % DI400Y;
274     *year = n400 * 400 + 1;
275 
276     /* Now n is the (non-negative) offset, in days, from January 1 of
277      * year, to the desired date.  Now compute how many 100-year cycles
278      * precede n.
279      * Note that it's possible for n100 to equal 4!  In that case 4 full
280      * 100-year cycles precede the desired day, which implies the
281      * desired day is December 31 at the end of a 400-year cycle.
282      */
283     n100 = n / DI100Y;
284     n = n % DI100Y;
285 
286     /* Now compute how many 4-year cycles precede it. */
287     n4 = n / DI4Y;
288     n = n % DI4Y;
289 
290     /* And now how many single years.  Again n1 can be 4, and again
291      * meaning that the desired day is December 31 at the end of the
292      * 4-year cycle.
293      */
294     n1 = n / 365;
295     n = n % 365;
296 
297     *year += n100 * 100 + n4 * 4 + n1;
298     if (n1 == 4 || n100 == 4) {
299         assert(n == 0);
300         *year -= 1;
301         *month = 12;
302         *day = 31;
303         return;
304     }
305 
306     /* Now the year is correct, and n is the offset from January 1.  We
307      * find the month via an estimate that's either exact or one too
308      * large.
309      */
310     leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
311     assert(leapyear == is_leap(*year));
312     *month = (n + 50) >> 5;
313     preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
314     if (preceding > n) {
315         /* estimate is too large */
316         *month -= 1;
317         preceding -= days_in_month(*year, *month);
318     }
319     n -= preceding;
320     assert(0 <= n);
321     assert(n < days_in_month(*year, *month));
322 
323     *day = n + 1;
324 }
325 
326 /* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
327 static int
ymd_to_ord(int year,int month,int day)328 ymd_to_ord(int year, int month, int day)
329 {
330     return days_before_year(year) + days_before_month(year, month) + day;
331 }
332 
333 /* Day of week, where Monday==0, ..., Sunday==6.  1/1/1 was a Monday. */
334 static int
weekday(int year,int month,int day)335 weekday(int year, int month, int day)
336 {
337     return (ymd_to_ord(year, month, day) + 6) % 7;
338 }
339 
340 /* Ordinal of the Monday starting week 1 of the ISO year.  Week 1 is the
341  * first calendar week containing a Thursday.
342  */
343 static int
iso_week1_monday(int year)344 iso_week1_monday(int year)
345 {
346     int first_day = ymd_to_ord(year, 1, 1);     /* ord of 1/1 */
347     /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
348     int first_weekday = (first_day + 6) % 7;
349     /* ordinal of closest Monday at or before 1/1 */
350     int week1_monday  = first_day - first_weekday;
351 
352     if (first_weekday > 3)      /* if 1/1 was Fri, Sat, Sun */
353         week1_monday += 7;
354     return week1_monday;
355 }
356 
357 /* ---------------------------------------------------------------------------
358  * Range checkers.
359  */
360 
361 /* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS.  If so, return 0.
362  * If not, raise OverflowError and return -1.
363  */
364 static int
check_delta_day_range(int days)365 check_delta_day_range(int days)
366 {
367     if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
368         return 0;
369     PyErr_Format(PyExc_OverflowError,
370                  "days=%d; must have magnitude <= %d",
371                  days, MAX_DELTA_DAYS);
372     return -1;
373 }
374 
375 /* Check that date arguments are in range.  Return 0 if they are.  If they
376  * aren't, raise ValueError and return -1.
377  */
378 static int
check_date_args(int year,int month,int day)379 check_date_args(int year, int month, int day)
380 {
381 
382     if (year < MINYEAR || year > MAXYEAR) {
383         PyErr_SetString(PyExc_ValueError,
384                         "year is out of range");
385         return -1;
386     }
387     if (month < 1 || month > 12) {
388         PyErr_SetString(PyExc_ValueError,
389                         "month must be in 1..12");
390         return -1;
391     }
392     if (day < 1 || day > days_in_month(year, month)) {
393         PyErr_SetString(PyExc_ValueError,
394                         "day is out of range for month");
395         return -1;
396     }
397     return 0;
398 }
399 
400 /* Check that time arguments are in range.  Return 0 if they are.  If they
401  * aren't, raise ValueError and return -1.
402  */
403 static int
check_time_args(int h,int m,int s,int us)404 check_time_args(int h, int m, int s, int us)
405 {
406     if (h < 0 || h > 23) {
407         PyErr_SetString(PyExc_ValueError,
408                         "hour must be in 0..23");
409         return -1;
410     }
411     if (m < 0 || m > 59) {
412         PyErr_SetString(PyExc_ValueError,
413                         "minute must be in 0..59");
414         return -1;
415     }
416     if (s < 0 || s > 59) {
417         PyErr_SetString(PyExc_ValueError,
418                         "second must be in 0..59");
419         return -1;
420     }
421     if (us < 0 || us > 999999) {
422         PyErr_SetString(PyExc_ValueError,
423                         "microsecond must be in 0..999999");
424         return -1;
425     }
426     return 0;
427 }
428 
429 /* ---------------------------------------------------------------------------
430  * Normalization utilities.
431  */
432 
433 /* One step of a mixed-radix conversion.  A "hi" unit is equivalent to
434  * factor "lo" units.  factor must be > 0.  If *lo is less than 0, or
435  * at least factor, enough of *lo is converted into "hi" units so that
436  * 0 <= *lo < factor.  The input values must be such that int overflow
437  * is impossible.
438  */
439 static void
normalize_pair(int * hi,int * lo,int factor)440 normalize_pair(int *hi, int *lo, int factor)
441 {
442     assert(factor > 0);
443     assert(lo != hi);
444     if (*lo < 0 || *lo >= factor) {
445         const int num_hi = divmod(*lo, factor, lo);
446         const int new_hi = *hi + num_hi;
447         assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
448         *hi = new_hi;
449     }
450     assert(0 <= *lo && *lo < factor);
451 }
452 
453 /* Fiddle days (d), seconds (s), and microseconds (us) so that
454  *      0 <= *s < 24*3600
455  *      0 <= *us < 1000000
456  * The input values must be such that the internals don't overflow.
457  * The way this routine is used, we don't get close.
458  */
459 static void
normalize_d_s_us(int * d,int * s,int * us)460 normalize_d_s_us(int *d, int *s, int *us)
461 {
462     if (*us < 0 || *us >= 1000000) {
463         normalize_pair(s, us, 1000000);
464         /* |s| can't be bigger than about
465          * |original s| + |original us|/1000000 now.
466          */
467 
468     }
469     if (*s < 0 || *s >= 24*3600) {
470         normalize_pair(d, s, 24*3600);
471         /* |d| can't be bigger than about
472          * |original d| +
473          * (|original s| + |original us|/1000000) / (24*3600) now.
474          */
475     }
476     assert(0 <= *s && *s < 24*3600);
477     assert(0 <= *us && *us < 1000000);
478 }
479 
480 /* Fiddle years (y), months (m), and days (d) so that
481  *      1 <= *m <= 12
482  *      1 <= *d <= days_in_month(*y, *m)
483  * The input values must be such that the internals don't overflow.
484  * The way this routine is used, we don't get close.
485  */
486 static int
normalize_y_m_d(int * y,int * m,int * d)487 normalize_y_m_d(int *y, int *m, int *d)
488 {
489     int dim;            /* # of days in month */
490 
491     /* This gets muddy:  the proper range for day can't be determined
492      * without knowing the correct month and year, but if day is, e.g.,
493      * plus or minus a million, the current month and year values make
494      * no sense (and may also be out of bounds themselves).
495      * Saying 12 months == 1 year should be non-controversial.
496      */
497     if (*m < 1 || *m > 12) {
498         --*m;
499         normalize_pair(y, m, 12);
500         ++*m;
501         /* |y| can't be bigger than about
502          * |original y| + |original m|/12 now.
503          */
504     }
505     assert(1 <= *m && *m <= 12);
506 
507     /* Now only day can be out of bounds (year may also be out of bounds
508      * for a datetime object, but we don't care about that here).
509      * If day is out of bounds, what to do is arguable, but at least the
510      * method here is principled and explainable.
511      */
512     dim = days_in_month(*y, *m);
513     if (*d < 1 || *d > dim) {
514         /* Move day-1 days from the first of the month.  First try to
515          * get off cheap if we're only one day out of range
516          * (adjustments for timezone alone can't be worse than that).
517          */
518         if (*d == 0) {
519             --*m;
520             if (*m > 0)
521                 *d = days_in_month(*y, *m);
522             else {
523                 --*y;
524                 *m = 12;
525                 *d = 31;
526             }
527         }
528         else if (*d == dim + 1) {
529             /* move forward a day */
530             ++*m;
531             *d = 1;
532             if (*m > 12) {
533                 *m = 1;
534                 ++*y;
535             }
536         }
537         else {
538             int ordinal = ymd_to_ord(*y, *m, 1) +
539                                       *d - 1;
540             if (ordinal < 1 || ordinal > MAXORDINAL) {
541                 goto error;
542             } else {
543                 ord_to_ymd(ordinal, y, m, d);
544                 return 0;
545             }
546         }
547     }
548     assert(*m > 0);
549     assert(*d > 0);
550     if (MINYEAR <= *y && *y <= MAXYEAR)
551         return 0;
552  error:
553     PyErr_SetString(PyExc_OverflowError,
554             "date value out of range");
555     return -1;
556 
557 }
558 
559 /* Fiddle out-of-bounds months and days so that the result makes some kind
560  * of sense.  The parameters are both inputs and outputs.  Returns < 0 on
561  * failure, where failure means the adjusted year is out of bounds.
562  */
563 static int
normalize_date(int * year,int * month,int * day)564 normalize_date(int *year, int *month, int *day)
565 {
566     return normalize_y_m_d(year, month, day);
567 }
568 
569 /* Force all the datetime fields into range.  The parameters are both
570  * inputs and outputs.  Returns < 0 on error.
571  */
572 static int
normalize_datetime(int * year,int * month,int * day,int * hour,int * minute,int * second,int * microsecond)573 normalize_datetime(int *year, int *month, int *day,
574                    int *hour, int *minute, int *second,
575                    int *microsecond)
576 {
577     normalize_pair(second, microsecond, 1000000);
578     normalize_pair(minute, second, 60);
579     normalize_pair(hour, minute, 60);
580     normalize_pair(day, hour, 24);
581     return normalize_date(year, month, day);
582 }
583 
584 /* ---------------------------------------------------------------------------
585  * Basic object allocation:  tp_alloc implementations.  These allocate
586  * Python objects of the right size and type, and do the Python object-
587  * initialization bit.  If there's not enough memory, they return NULL after
588  * setting MemoryError.  All data members remain uninitialized trash.
589  *
590  * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
591  * member is needed.  This is ugly, imprecise, and possibly insecure.
592  * tp_basicsize for the time and datetime types is set to the size of the
593  * struct that has room for the tzinfo member, so subclasses in Python will
594  * allocate enough space for a tzinfo member whether or not one is actually
595  * needed.  That's the "ugly and imprecise" parts.  The "possibly insecure"
596  * part is that PyType_GenericAlloc() (which subclasses in Python end up
597  * using) just happens today to effectively ignore the nitems argument
598  * when tp_itemsize is 0, which it is for these type objects.  If that
599  * changes, perhaps the callers of tp_alloc slots in this file should
600  * be changed to force a 0 nitems argument unless the type being allocated
601  * is a base type implemented in this file (so that tp_alloc is time_alloc
602  * or datetime_alloc below, which know about the nitems abuse).
603  */
604 
605 static PyObject *
time_alloc(PyTypeObject * type,Py_ssize_t aware)606 time_alloc(PyTypeObject *type, Py_ssize_t aware)
607 {
608     PyObject *self;
609 
610     self = (PyObject *)
611         PyObject_MALLOC(aware ?
612                         sizeof(PyDateTime_Time) :
613                 sizeof(_PyDateTime_BaseTime));
614     if (self == NULL)
615         return (PyObject *)PyErr_NoMemory();
616     (void)PyObject_INIT(self, type);
617     return self;
618 }
619 
620 static PyObject *
datetime_alloc(PyTypeObject * type,Py_ssize_t aware)621 datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
622 {
623     PyObject *self;
624 
625     self = (PyObject *)
626         PyObject_MALLOC(aware ?
627                         sizeof(PyDateTime_DateTime) :
628                 sizeof(_PyDateTime_BaseDateTime));
629     if (self == NULL)
630         return (PyObject *)PyErr_NoMemory();
631     (void)PyObject_INIT(self, type);
632     return self;
633 }
634 
635 /* ---------------------------------------------------------------------------
636  * Helpers for setting object fields.  These work on pointers to the
637  * appropriate base class.
638  */
639 
640 /* For date and datetime. */
641 static void
set_date_fields(PyDateTime_Date * self,int y,int m,int d)642 set_date_fields(PyDateTime_Date *self, int y, int m, int d)
643 {
644     self->hashcode = -1;
645     SET_YEAR(self, y);
646     SET_MONTH(self, m);
647     SET_DAY(self, d);
648 }
649 
650 /* ---------------------------------------------------------------------------
651  * Create various objects, mostly without range checking.
652  */
653 
654 /* Create a date instance with no range checking. */
655 static PyObject *
new_date_ex(int year,int month,int day,PyTypeObject * type)656 new_date_ex(int year, int month, int day, PyTypeObject *type)
657 {
658     PyDateTime_Date *self;
659 
660     self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
661     if (self != NULL)
662         set_date_fields(self, year, month, day);
663     return (PyObject *) self;
664 }
665 
666 #define new_date(year, month, day) \
667     new_date_ex(year, month, day, &PyDateTime_DateType)
668 
669 /* Create a datetime instance with no range checking. */
670 static PyObject *
new_datetime_ex(int year,int month,int day,int hour,int minute,int second,int usecond,PyObject * tzinfo,PyTypeObject * type)671 new_datetime_ex(int year, int month, int day, int hour, int minute,
672              int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
673 {
674     PyDateTime_DateTime *self;
675     char aware = tzinfo != Py_None;
676 
677     self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
678     if (self != NULL) {
679         self->hastzinfo = aware;
680         set_date_fields((PyDateTime_Date *)self, year, month, day);
681         DATE_SET_HOUR(self, hour);
682         DATE_SET_MINUTE(self, minute);
683         DATE_SET_SECOND(self, second);
684         DATE_SET_MICROSECOND(self, usecond);
685         if (aware) {
686             Py_INCREF(tzinfo);
687             self->tzinfo = tzinfo;
688         }
689     }
690     return (PyObject *)self;
691 }
692 
693 #define new_datetime(y, m, d, hh, mm, ss, us, tzinfo)           \
694     new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo,            \
695                     &PyDateTime_DateTimeType)
696 
697 /* Create a time instance with no range checking. */
698 static PyObject *
new_time_ex(int hour,int minute,int second,int usecond,PyObject * tzinfo,PyTypeObject * type)699 new_time_ex(int hour, int minute, int second, int usecond,
700             PyObject *tzinfo, PyTypeObject *type)
701 {
702     PyDateTime_Time *self;
703     char aware = tzinfo != Py_None;
704 
705     self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
706     if (self != NULL) {
707         self->hastzinfo = aware;
708         self->hashcode = -1;
709         TIME_SET_HOUR(self, hour);
710         TIME_SET_MINUTE(self, minute);
711         TIME_SET_SECOND(self, second);
712         TIME_SET_MICROSECOND(self, usecond);
713         if (aware) {
714             Py_INCREF(tzinfo);
715             self->tzinfo = tzinfo;
716         }
717     }
718     return (PyObject *)self;
719 }
720 
721 #define new_time(hh, mm, ss, us, tzinfo)                \
722     new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
723 
724 /* Create a timedelta instance.  Normalize the members iff normalize is
725  * true.  Passing false is a speed optimization, if you know for sure
726  * that seconds and microseconds are already in their proper ranges.  In any
727  * case, raises OverflowError and returns NULL if the normalized days is out
728  * of range).
729  */
730 static PyObject *
new_delta_ex(int days,int seconds,int microseconds,int normalize,PyTypeObject * type)731 new_delta_ex(int days, int seconds, int microseconds, int normalize,
732              PyTypeObject *type)
733 {
734     PyDateTime_Delta *self;
735 
736     if (normalize)
737         normalize_d_s_us(&days, &seconds, &microseconds);
738     assert(0 <= seconds && seconds < 24*3600);
739     assert(0 <= microseconds && microseconds < 1000000);
740 
741     if (check_delta_day_range(days) < 0)
742         return NULL;
743 
744     self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
745     if (self != NULL) {
746         self->hashcode = -1;
747         SET_TD_DAYS(self, days);
748         SET_TD_SECONDS(self, seconds);
749         SET_TD_MICROSECONDS(self, microseconds);
750     }
751     return (PyObject *) self;
752 }
753 
754 #define new_delta(d, s, us, normalize)  \
755     new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
756 
757 /* ---------------------------------------------------------------------------
758  * tzinfo helpers.
759  */
760 
761 /* Ensure that p is None or of a tzinfo subclass.  Return 0 if OK; if not
762  * raise TypeError and return -1.
763  */
764 static int
check_tzinfo_subclass(PyObject * p)765 check_tzinfo_subclass(PyObject *p)
766 {
767     if (p == Py_None || PyTZInfo_Check(p))
768         return 0;
769     PyErr_Format(PyExc_TypeError,
770                  "tzinfo argument must be None or of a tzinfo subclass, "
771                  "not type '%s'",
772                  Py_TYPE(p)->tp_name);
773     return -1;
774 }
775 
776 /* Return tzinfo.methname(tzinfoarg), without any checking of results.
777  * If tzinfo is None, returns None.
778  */
779 static PyObject *
call_tzinfo_method(PyObject * tzinfo,char * methname,PyObject * tzinfoarg)780 call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
781 {
782     PyObject *result;
783 
784     assert(tzinfo && methname && tzinfoarg);
785     assert(check_tzinfo_subclass(tzinfo) >= 0);
786     if (tzinfo == Py_None) {
787         result = Py_None;
788         Py_INCREF(result);
789     }
790     else
791         result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
792     return result;
793 }
794 
795 /* If self has a tzinfo member, return a BORROWED reference to it.  Else
796  * return NULL, which is NOT AN ERROR.  There are no error returns here,
797  * and the caller must not decref the result.
798  */
799 static PyObject *
get_tzinfo_member(PyObject * self)800 get_tzinfo_member(PyObject *self)
801 {
802     PyObject *tzinfo = NULL;
803 
804     if (PyDateTime_Check(self) && HASTZINFO(self))
805         tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
806     else if (PyTime_Check(self) && HASTZINFO(self))
807         tzinfo = ((PyDateTime_Time *)self)->tzinfo;
808 
809     return tzinfo;
810 }
811 
812 /* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
813  * result.  tzinfo must be an instance of the tzinfo class.  If the method
814  * returns None, this returns 0 and sets *none to 1.  If the method doesn't
815  * return None or timedelta, TypeError is raised and this returns -1.  If it
816  * returnsa timedelta and the value is out of range or isn't a whole number
817  * of minutes, ValueError is raised and this returns -1.
818  * Else *none is set to 0 and the integer method result is returned.
819  */
820 static int
call_utc_tzinfo_method(PyObject * tzinfo,char * name,PyObject * tzinfoarg,int * none)821 call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
822                        int *none)
823 {
824     PyObject *u;
825     int result = -1;
826 
827     assert(tzinfo != NULL);
828     assert(PyTZInfo_Check(tzinfo));
829     assert(tzinfoarg != NULL);
830 
831     *none = 0;
832     u = call_tzinfo_method(tzinfo, name, tzinfoarg);
833     if (u == NULL)
834         return -1;
835 
836     else if (u == Py_None) {
837         result = 0;
838         *none = 1;
839     }
840     else if (PyDelta_Check(u)) {
841         const int days = GET_TD_DAYS(u);
842         if (days < -1 || days > 0)
843             result = 24*60;             /* trigger ValueError below */
844         else {
845             /* next line can't overflow because we know days
846              * is -1 or 0 now
847              */
848             int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
849             result = divmod(ss, 60, &ss);
850             if (ss || GET_TD_MICROSECONDS(u)) {
851                 PyErr_Format(PyExc_ValueError,
852                              "tzinfo.%s() must return a "
853                              "whole number of minutes",
854                              name);
855                 result = -1;
856             }
857         }
858     }
859     else {
860         PyErr_Format(PyExc_TypeError,
861                      "tzinfo.%s() must return None or "
862                      "timedelta, not '%s'",
863                      name, Py_TYPE(u)->tp_name);
864     }
865 
866     Py_DECREF(u);
867     if (result < -1439 || result > 1439) {
868         PyErr_Format(PyExc_ValueError,
869                      "tzinfo.%s() returned %d; must be in "
870                      "-1439 .. 1439",
871                      name, result);
872         result = -1;
873     }
874     return result;
875 }
876 
877 /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
878  * result.  tzinfo must be an instance of the tzinfo class.  If utcoffset()
879  * returns None, call_utcoffset returns 0 and sets *none to 1.  If uctoffset()
880  * doesn't return None or timedelta, TypeError is raised and this returns -1.
881  * If utcoffset() returns an invalid timedelta (out of range, or not a whole
882  * # of minutes), ValueError is raised and this returns -1.  Else *none is
883  * set to 0 and the offset is returned (as int # of minutes east of UTC).
884  */
885 static int
call_utcoffset(PyObject * tzinfo,PyObject * tzinfoarg,int * none)886 call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
887 {
888     return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
889 }
890 
891 /* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
892  */
893 static PyObject *
offset_as_timedelta(PyObject * tzinfo,char * name,PyObject * tzinfoarg)894 offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
895     PyObject *result;
896 
897     assert(tzinfo && name && tzinfoarg);
898     if (tzinfo == Py_None) {
899         result = Py_None;
900         Py_INCREF(result);
901     }
902     else {
903         int none;
904         int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
905                                             &none);
906         if (offset < 0 && PyErr_Occurred())
907             return NULL;
908         if (none) {
909             result = Py_None;
910             Py_INCREF(result);
911         }
912         else
913             result = new_delta(0, offset * 60, 0, 1);
914     }
915     return result;
916 }
917 
918 /* Call tzinfo.dst(tzinfoarg), and extract an integer from the
919  * result.  tzinfo must be an instance of the tzinfo class.  If dst()
920  * returns None, call_dst returns 0 and sets *none to 1.  If dst()
921  & doesn't return None or timedelta, TypeError is raised and this
922  * returns -1.  If dst() returns an invalid timedelta for a UTC offset,
923  * ValueError is raised and this returns -1.  Else *none is set to 0 and
924  * the offset is returned (as an int # of minutes east of UTC).
925  */
926 static int
call_dst(PyObject * tzinfo,PyObject * tzinfoarg,int * none)927 call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
928 {
929     return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
930 }
931 
932 /* Call tzinfo.tzname(tzinfoarg), and return the result.  tzinfo must be
933  * an instance of the tzinfo class or None.  If tzinfo isn't None, and
934  * tzname() doesn't return None or a string, TypeError is raised and this
935  * returns NULL.
936  */
937 static PyObject *
call_tzname(PyObject * tzinfo,PyObject * tzinfoarg)938 call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
939 {
940     PyObject *result;
941 
942     assert(tzinfo != NULL);
943     assert(check_tzinfo_subclass(tzinfo) >= 0);
944     assert(tzinfoarg != NULL);
945 
946     if (tzinfo == Py_None) {
947         result = Py_None;
948         Py_INCREF(result);
949     }
950     else
951         result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
952 
953     if (result != NULL && result != Py_None && ! PyString_Check(result)) {
954         PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
955                      "return None or a string, not '%s'",
956                      Py_TYPE(result)->tp_name);
957         Py_DECREF(result);
958         result = NULL;
959     }
960     return result;
961 }
962 
963 typedef enum {
964               /* an exception has been set; the caller should pass it on */
965           OFFSET_ERROR,
966 
967           /* type isn't date, datetime, or time subclass */
968           OFFSET_UNKNOWN,
969 
970           /* date,
971            * datetime with !hastzinfo
972            * datetime with None tzinfo,
973            * datetime where utcoffset() returns None
974            * time with !hastzinfo
975            * time with None tzinfo,
976            * time where utcoffset() returns None
977            */
978           OFFSET_NAIVE,
979 
980           /* time or datetime where utcoffset() doesn't return None */
981           OFFSET_AWARE
982 } naivety;
983 
984 /* Classify an object as to whether it's naive or offset-aware.  See
985  * the "naivety" typedef for details.  If the type is aware, *offset is set
986  * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
987  * If the type is offset-naive (or unknown, or error), *offset is set to 0.
988  * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
989  */
990 static naivety
classify_utcoffset(PyObject * op,PyObject * tzinfoarg,int * offset)991 classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
992 {
993     int none;
994     PyObject *tzinfo;
995 
996     assert(tzinfoarg != NULL);
997     *offset = 0;
998     tzinfo = get_tzinfo_member(op);     /* NULL means no tzinfo, not error */
999     if (tzinfo == Py_None)
1000         return OFFSET_NAIVE;
1001     if (tzinfo == NULL) {
1002         /* note that a datetime passes the PyDate_Check test */
1003         return (PyTime_Check(op) || PyDate_Check(op)) ?
1004                OFFSET_NAIVE : OFFSET_UNKNOWN;
1005     }
1006     *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1007     if (*offset == -1 && PyErr_Occurred())
1008         return OFFSET_ERROR;
1009     return none ? OFFSET_NAIVE : OFFSET_AWARE;
1010 }
1011 
1012 /* Classify two objects as to whether they're naive or offset-aware.
1013  * This isn't quite the same as calling classify_utcoffset() twice:  for
1014  * binary operations (comparison and subtraction), we generally want to
1015  * ignore the tzinfo members if they're identical.  This is by design,
1016  * so that results match "naive" expectations when mixing objects from a
1017  * single timezone.  So in that case, this sets both offsets to 0 and
1018  * both naiveties to OFFSET_NAIVE.
1019  * The function returns 0 if everything's OK, and -1 on error.
1020  */
1021 static int
classify_two_utcoffsets(PyObject * o1,int * offset1,naivety * n1,PyObject * tzinfoarg1,PyObject * o2,int * offset2,naivety * n2,PyObject * tzinfoarg2)1022 classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
1023                         PyObject *tzinfoarg1,
1024                         PyObject *o2, int *offset2, naivety *n2,
1025                         PyObject *tzinfoarg2)
1026 {
1027     if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1028         *offset1 = *offset2 = 0;
1029         *n1 = *n2 = OFFSET_NAIVE;
1030     }
1031     else {
1032         *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
1033         if (*n1 == OFFSET_ERROR)
1034             return -1;
1035         *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
1036         if (*n2 == OFFSET_ERROR)
1037             return -1;
1038     }
1039     return 0;
1040 }
1041 
1042 /* repr is like "someclass(arg1, arg2)".  If tzinfo isn't None,
1043  * stuff
1044  *     ", tzinfo=" + repr(tzinfo)
1045  * before the closing ")".
1046  */
1047 static PyObject *
append_keyword_tzinfo(PyObject * repr,PyObject * tzinfo)1048 append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1049 {
1050     PyObject *temp;
1051 
1052     assert(PyString_Check(repr));
1053     assert(tzinfo);
1054     if (tzinfo == Py_None)
1055         return repr;
1056     /* Get rid of the trailing ')'. */
1057     assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
1058     temp = PyString_FromStringAndSize(PyString_AsString(repr),
1059                                       PyString_Size(repr) - 1);
1060     Py_DECREF(repr);
1061     if (temp == NULL)
1062         return NULL;
1063     repr = temp;
1064 
1065     /* Append ", tzinfo=". */
1066     PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
1067 
1068     /* Append repr(tzinfo). */
1069     PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
1070 
1071     /* Add a closing paren. */
1072     PyString_ConcatAndDel(&repr, PyString_FromString(")"));
1073     return repr;
1074 }
1075 
1076 /* ---------------------------------------------------------------------------
1077  * String format helpers.
1078  */
1079 
1080 static PyObject *
format_ctime(PyDateTime_Date * date,int hours,int minutes,int seconds)1081 format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
1082 {
1083     static const char *DayNames[] = {
1084         "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1085     };
1086     static const char *MonthNames[] = {
1087         "Jan", "Feb", "Mar", "Apr", "May", "Jun",
1088         "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1089     };
1090 
1091     char buffer[128];
1092     int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1093 
1094     PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
1095                   DayNames[wday], MonthNames[GET_MONTH(date) - 1],
1096                   GET_DAY(date), hours, minutes, seconds,
1097                   GET_YEAR(date));
1098     return PyString_FromString(buffer);
1099 }
1100 
1101 /* Add an hours & minutes UTC offset string to buf.  buf has no more than
1102  * buflen bytes remaining.  The UTC offset is gotten by calling
1103  * tzinfo.uctoffset(tzinfoarg).  If that returns None, \0 is stored into
1104  * *buf, and that's all.  Else the returned value is checked for sanity (an
1105  * integer in range), and if that's OK it's converted to an hours & minutes
1106  * string of the form
1107  *   sign HH sep MM
1108  * Returns 0 if everything is OK.  If the return value from utcoffset() is
1109  * bogus, an appropriate exception is set and -1 is returned.
1110  */
1111 static int
format_utcoffset(char * buf,size_t buflen,const char * sep,PyObject * tzinfo,PyObject * tzinfoarg)1112 format_utcoffset(char *buf, size_t buflen, const char *sep,
1113                 PyObject *tzinfo, PyObject *tzinfoarg)
1114 {
1115     int offset;
1116     int hours;
1117     int minutes;
1118     char sign;
1119     int none;
1120 
1121     assert(buflen >= 1);
1122 
1123     offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1124     if (offset == -1 && PyErr_Occurred())
1125         return -1;
1126     if (none) {
1127         *buf = '\0';
1128         return 0;
1129     }
1130     sign = '+';
1131     if (offset < 0) {
1132         sign = '-';
1133         offset = - offset;
1134     }
1135     hours = divmod(offset, 60, &minutes);
1136     PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1137     return 0;
1138 }
1139 
1140 static PyObject *
make_freplacement(PyObject * object)1141 make_freplacement(PyObject *object)
1142 {
1143     char freplacement[64];
1144     if (PyTime_Check(object))
1145         sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1146     else if (PyDateTime_Check(object))
1147         sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1148     else
1149         sprintf(freplacement, "%06d", 0);
1150 
1151     return PyString_FromStringAndSize(freplacement, strlen(freplacement));
1152 }
1153 
1154 /* I sure don't want to reproduce the strftime code from the time module,
1155  * so this imports the module and calls it.  All the hair is due to
1156  * giving special meanings to the %z, %Z and %f format codes via a
1157  * preprocessing step on the format string.
1158  * tzinfoarg is the argument to pass to the object's tzinfo method, if
1159  * needed.
1160  */
1161 static PyObject *
wrap_strftime(PyObject * object,const char * format,size_t format_len,PyObject * timetuple,PyObject * tzinfoarg)1162 wrap_strftime(PyObject *object, const char *format, size_t format_len,
1163                 PyObject *timetuple, PyObject *tzinfoarg)
1164 {
1165     PyObject *result = NULL;            /* guilty until proved innocent */
1166 
1167     PyObject *zreplacement = NULL;      /* py string, replacement for %z */
1168     PyObject *Zreplacement = NULL;      /* py string, replacement for %Z */
1169     PyObject *freplacement = NULL;      /* py string, replacement for %f */
1170 
1171     const char *pin;            /* pointer to next char in input format */
1172     char ch;                    /* next char in input format */
1173 
1174     PyObject *newfmt = NULL;            /* py string, the output format */
1175     char *pnew;         /* pointer to available byte in output format */
1176     size_t totalnew;            /* number bytes total in output format buffer,
1177                                exclusive of trailing \0 */
1178     size_t usednew;     /* number bytes used so far in output format buffer */
1179 
1180     const char *ptoappend;      /* ptr to string to append to output buffer */
1181     size_t ntoappend;           /* # of bytes to append to output buffer */
1182 
1183     assert(object && format && timetuple);
1184 
1185     /* Give up if the year is before 1900.
1186      * Python strftime() plays games with the year, and different
1187      * games depending on whether envar PYTHON2K is set.  This makes
1188      * years before 1900 a nightmare, even if the platform strftime
1189      * supports them (and not all do).
1190      * We could get a lot farther here by avoiding Python's strftime
1191      * wrapper and calling the C strftime() directly, but that isn't
1192      * an option in the Python implementation of this module.
1193      */
1194     {
1195         long year;
1196         PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1197         if (pyyear == NULL) return NULL;
1198         assert(PyInt_Check(pyyear));
1199         year = PyInt_AsLong(pyyear);
1200         Py_DECREF(pyyear);
1201         if (year < 1900) {
1202             PyErr_Format(PyExc_ValueError, "year=%ld is before "
1203                          "1900; the datetime strftime() "
1204                          "methods require year >= 1900",
1205                          year);
1206             return NULL;
1207         }
1208     }
1209 
1210     /* Scan the input format, looking for %z/%Z/%f escapes, building
1211      * a new format.  Since computing the replacements for those codes
1212      * is expensive, don't unless they're actually used.
1213      */
1214     if (format_len > INT_MAX - 1) {
1215         PyErr_NoMemory();
1216         goto Done;
1217     }
1218 
1219     totalnew = format_len + 1;          /* realistic if no %z/%Z/%f */
1220     newfmt = PyString_FromStringAndSize(NULL, totalnew);
1221     if (newfmt == NULL) goto Done;
1222     pnew = PyString_AsString(newfmt);
1223     usednew = 0;
1224 
1225     pin = format;
1226     while ((ch = *pin++) != '\0') {
1227         if (ch != '%') {
1228             ptoappend = pin - 1;
1229             ntoappend = 1;
1230         }
1231         else if ((ch = *pin++) == '\0') {
1232             /* There's a lone trailing %; doesn't make sense. */
1233             PyErr_SetString(PyExc_ValueError, "strftime format "
1234                             "ends with raw %");
1235             goto Done;
1236         }
1237         /* A % has been seen and ch is the character after it. */
1238         else if (ch == 'z') {
1239             if (zreplacement == NULL) {
1240                 /* format utcoffset */
1241                 char buf[100];
1242                 PyObject *tzinfo = get_tzinfo_member(object);
1243                 zreplacement = PyString_FromString("");
1244                 if (zreplacement == NULL) goto Done;
1245                 if (tzinfo != Py_None && tzinfo != NULL) {
1246                     assert(tzinfoarg != NULL);
1247                     if (format_utcoffset(buf,
1248                                          sizeof(buf),
1249                                          "",
1250                                          tzinfo,
1251                                          tzinfoarg) < 0)
1252                         goto Done;
1253                     Py_DECREF(zreplacement);
1254                     zreplacement = PyString_FromString(buf);
1255                     if (zreplacement == NULL) goto Done;
1256                 }
1257             }
1258             assert(zreplacement != NULL);
1259             ptoappend = PyString_AS_STRING(zreplacement);
1260             ntoappend = PyString_GET_SIZE(zreplacement);
1261         }
1262         else if (ch == 'Z') {
1263             /* format tzname */
1264             if (Zreplacement == NULL) {
1265                 PyObject *tzinfo = get_tzinfo_member(object);
1266                 Zreplacement = PyString_FromString("");
1267                 if (Zreplacement == NULL) goto Done;
1268                 if (tzinfo != Py_None && tzinfo != NULL) {
1269                     PyObject *temp;
1270                     assert(tzinfoarg != NULL);
1271                     temp = call_tzname(tzinfo, tzinfoarg);
1272                     if (temp == NULL) goto Done;
1273                     if (temp != Py_None) {
1274                         assert(PyString_Check(temp));
1275                         /* Since the tzname is getting
1276                          * stuffed into the format, we
1277                          * have to double any % signs
1278                          * so that strftime doesn't
1279                          * treat them as format codes.
1280                          */
1281                         Py_DECREF(Zreplacement);
1282                         Zreplacement = PyObject_CallMethod(
1283                             temp, "replace",
1284                             "ss", "%", "%%");
1285                         Py_DECREF(temp);
1286                         if (Zreplacement == NULL)
1287                             goto Done;
1288                         if (!PyString_Check(Zreplacement)) {
1289                             PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1290                             goto Done;
1291                         }
1292                     }
1293                     else
1294                         Py_DECREF(temp);
1295                 }
1296             }
1297             assert(Zreplacement != NULL);
1298             ptoappend = PyString_AS_STRING(Zreplacement);
1299             ntoappend = PyString_GET_SIZE(Zreplacement);
1300         }
1301         else if (ch == 'f') {
1302             /* format microseconds */
1303             if (freplacement == NULL) {
1304                 freplacement = make_freplacement(object);
1305                 if (freplacement == NULL)
1306                     goto Done;
1307             }
1308             assert(freplacement != NULL);
1309             assert(PyString_Check(freplacement));
1310             ptoappend = PyString_AS_STRING(freplacement);
1311             ntoappend = PyString_GET_SIZE(freplacement);
1312         }
1313         else {
1314             /* percent followed by neither z nor Z */
1315             ptoappend = pin - 2;
1316             ntoappend = 2;
1317         }
1318 
1319         /* Append the ntoappend chars starting at ptoappend to
1320          * the new format.
1321          */
1322         assert(ptoappend != NULL);
1323         assert(ntoappend >= 0);
1324         if (ntoappend == 0)
1325             continue;
1326         while (usednew + ntoappend > totalnew) {
1327             size_t bigger = totalnew << 1;
1328             if ((bigger >> 1) != totalnew) { /* overflow */
1329                 PyErr_NoMemory();
1330                 goto Done;
1331             }
1332             if (_PyString_Resize(&newfmt, bigger) < 0)
1333                 goto Done;
1334             totalnew = bigger;
1335             pnew = PyString_AsString(newfmt) + usednew;
1336         }
1337         memcpy(pnew, ptoappend, ntoappend);
1338         pnew += ntoappend;
1339         usednew += ntoappend;
1340         assert(usednew <= totalnew);
1341     }  /* end while() */
1342 
1343     if (_PyString_Resize(&newfmt, usednew) < 0)
1344         goto Done;
1345     {
1346         PyObject *time = PyImport_ImportModuleNoBlock("time");
1347         if (time == NULL)
1348             goto Done;
1349         result = PyObject_CallMethod(time, "strftime", "OO",
1350                                      newfmt, timetuple);
1351         Py_DECREF(time);
1352     }
1353  Done:
1354     Py_XDECREF(freplacement);
1355     Py_XDECREF(zreplacement);
1356     Py_XDECREF(Zreplacement);
1357     Py_XDECREF(newfmt);
1358     return result;
1359 }
1360 
1361 static char *
isoformat_date(PyDateTime_Date * dt,char buffer[],int bufflen)1362 isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1363 {
1364     int x;
1365     x = PyOS_snprintf(buffer, bufflen,
1366                       "%04d-%02d-%02d",
1367                       GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1368     assert(bufflen >= x);
1369     return buffer + x;
1370 }
1371 
1372 static char *
isoformat_time(PyDateTime_DateTime * dt,char buffer[],int bufflen)1373 isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1374 {
1375     int x;
1376     int us = DATE_GET_MICROSECOND(dt);
1377 
1378     x = PyOS_snprintf(buffer, bufflen,
1379                       "%02d:%02d:%02d",
1380                       DATE_GET_HOUR(dt),
1381                       DATE_GET_MINUTE(dt),
1382                       DATE_GET_SECOND(dt));
1383     assert(bufflen >= x);
1384     if (us)
1385         x += PyOS_snprintf(buffer + x, bufflen - x, ".%06d", us);
1386     assert(bufflen >= x);
1387     return buffer + x;
1388 }
1389 
1390 /* ---------------------------------------------------------------------------
1391  * Wrap functions from the time module.  These aren't directly available
1392  * from C.  Perhaps they should be.
1393  */
1394 
1395 /* Call time.time() and return its result (a Python float). */
1396 static PyObject *
time_time(void)1397 time_time(void)
1398 {
1399     PyObject *result = NULL;
1400     PyObject *time = PyImport_ImportModuleNoBlock("time");
1401 
1402     if (time != NULL) {
1403         result = PyObject_CallMethod(time, "time", "()");
1404         Py_DECREF(time);
1405     }
1406     return result;
1407 }
1408 
1409 /* Build a time.struct_time.  The weekday and day number are automatically
1410  * computed from the y,m,d args.
1411  */
1412 static PyObject *
build_struct_time(int y,int m,int d,int hh,int mm,int ss,int dstflag)1413 build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1414 {
1415     PyObject *time;
1416     PyObject *result = NULL;
1417 
1418     time = PyImport_ImportModuleNoBlock("time");
1419     if (time != NULL) {
1420         result = PyObject_CallMethod(time, "struct_time",
1421                                      "((iiiiiiiii))",
1422                                      y, m, d,
1423                                      hh, mm, ss,
1424                                      weekday(y, m, d),
1425                                      days_before_month(y, m) + d,
1426                                      dstflag);
1427         Py_DECREF(time);
1428     }
1429     return result;
1430 }
1431 
1432 /* ---------------------------------------------------------------------------
1433  * Miscellaneous helpers.
1434  */
1435 
1436 /* For obscure reasons, we need to use tp_richcompare instead of tp_compare.
1437  * The comparisons here all most naturally compute a cmp()-like result.
1438  * This little helper turns that into a bool result for rich comparisons.
1439  */
1440 static PyObject *
diff_to_bool(int diff,int op)1441 diff_to_bool(int diff, int op)
1442 {
1443     PyObject *result;
1444     int istrue;
1445 
1446     switch (op) {
1447         case Py_EQ: istrue = diff == 0; break;
1448         case Py_NE: istrue = diff != 0; break;
1449         case Py_LE: istrue = diff <= 0; break;
1450         case Py_GE: istrue = diff >= 0; break;
1451         case Py_LT: istrue = diff < 0; break;
1452         case Py_GT: istrue = diff > 0; break;
1453         default:
1454             assert(! "op unknown");
1455             istrue = 0; /* To shut up compiler */
1456     }
1457     result = istrue ? Py_True : Py_False;
1458     Py_INCREF(result);
1459     return result;
1460 }
1461 
1462 /* Raises a "can't compare" TypeError and returns NULL. */
1463 static PyObject *
cmperror(PyObject * a,PyObject * b)1464 cmperror(PyObject *a, PyObject *b)
1465 {
1466     PyErr_Format(PyExc_TypeError,
1467                  "can't compare %s to %s",
1468                  Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1469     return NULL;
1470 }
1471 
1472 /* ---------------------------------------------------------------------------
1473  * Cached Python objects; these are set by the module init function.
1474  */
1475 
1476 /* Conversion factors. */
1477 static PyObject *us_per_us = NULL;      /* 1 */
1478 static PyObject *us_per_ms = NULL;      /* 1000 */
1479 static PyObject *us_per_second = NULL;  /* 1000000 */
1480 static PyObject *us_per_minute = NULL;  /* 1e6 * 60 as Python int */
1481 static PyObject *us_per_hour = NULL;    /* 1e6 * 3600 as Python long */
1482 static PyObject *us_per_day = NULL;     /* 1e6 * 3600 * 24 as Python long */
1483 static PyObject *us_per_week = NULL;    /* 1e6*3600*24*7 as Python long */
1484 static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1485 
1486 /* ---------------------------------------------------------------------------
1487  * Class implementations.
1488  */
1489 
1490 /*
1491  * PyDateTime_Delta implementation.
1492  */
1493 
1494 /* Convert a timedelta to a number of us,
1495  *      (24*3600*self.days + self.seconds)*1000000 + self.microseconds
1496  * as a Python int or long.
1497  * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1498  * due to ubiquitous overflow possibilities.
1499  */
1500 static PyObject *
delta_to_microseconds(PyDateTime_Delta * self)1501 delta_to_microseconds(PyDateTime_Delta *self)
1502 {
1503     PyObject *x1 = NULL;
1504     PyObject *x2 = NULL;
1505     PyObject *x3 = NULL;
1506     PyObject *result = NULL;
1507 
1508     x1 = PyInt_FromLong(GET_TD_DAYS(self));
1509     if (x1 == NULL)
1510         goto Done;
1511     x2 = PyNumber_Multiply(x1, seconds_per_day);        /* days in seconds */
1512     if (x2 == NULL)
1513         goto Done;
1514     Py_DECREF(x1);
1515     x1 = NULL;
1516 
1517     /* x2 has days in seconds */
1518     x1 = PyInt_FromLong(GET_TD_SECONDS(self));          /* seconds */
1519     if (x1 == NULL)
1520         goto Done;
1521     x3 = PyNumber_Add(x1, x2);          /* days and seconds in seconds */
1522     if (x3 == NULL)
1523         goto Done;
1524     Py_DECREF(x1);
1525     Py_DECREF(x2);
1526     x2 = NULL;
1527 
1528     /* x3 has days+seconds in seconds */
1529     x1 = PyNumber_Multiply(x3, us_per_second);          /* us */
1530     if (x1 == NULL)
1531         goto Done;
1532     Py_DECREF(x3);
1533     x3 = NULL;
1534 
1535     /* x1 has days+seconds in us */
1536     x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1537     if (x2 == NULL)
1538         goto Done;
1539     result = PyNumber_Add(x1, x2);
1540     assert(result == NULL || _PyAnyInt_CheckExact(result));
1541 
1542 Done:
1543     Py_XDECREF(x1);
1544     Py_XDECREF(x2);
1545     Py_XDECREF(x3);
1546     return result;
1547 }
1548 
1549 /* Convert a number of us (as a Python int or long) to a timedelta.
1550  */
1551 static PyObject *
microseconds_to_delta_ex(PyObject * pyus,PyTypeObject * type)1552 microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
1553 {
1554     int us;
1555     int s;
1556     int d;
1557     long temp;
1558 
1559     PyObject *tuple = NULL;
1560     PyObject *num = NULL;
1561     PyObject *result = NULL;
1562 
1563     assert(_PyAnyInt_CheckExact(pyus));
1564     tuple = PyNumber_Divmod(pyus, us_per_second);
1565     if (tuple == NULL)
1566         goto Done;
1567 
1568     num = PyTuple_GetItem(tuple, 1);            /* us */
1569     if (num == NULL)
1570         goto Done;
1571     temp = PyLong_AsLong(num);
1572     num = NULL;
1573     if (temp == -1 && PyErr_Occurred())
1574         goto Done;
1575     assert(0 <= temp && temp < 1000000);
1576     us = (int)temp;
1577     if (us < 0) {
1578         /* The divisor was positive, so this must be an error. */
1579         assert(PyErr_Occurred());
1580         goto Done;
1581     }
1582 
1583     num = PyTuple_GetItem(tuple, 0);            /* leftover seconds */
1584     if (num == NULL)
1585         goto Done;
1586     Py_INCREF(num);
1587     Py_DECREF(tuple);
1588 
1589     tuple = PyNumber_Divmod(num, seconds_per_day);
1590     if (tuple == NULL)
1591         goto Done;
1592     Py_DECREF(num);
1593 
1594     num = PyTuple_GetItem(tuple, 1);            /* seconds */
1595     if (num == NULL)
1596         goto Done;
1597     temp = PyLong_AsLong(num);
1598     num = NULL;
1599     if (temp == -1 && PyErr_Occurred())
1600         goto Done;
1601     assert(0 <= temp && temp < 24*3600);
1602     s = (int)temp;
1603 
1604     if (s < 0) {
1605         /* The divisor was positive, so this must be an error. */
1606         assert(PyErr_Occurred());
1607         goto Done;
1608     }
1609 
1610     num = PyTuple_GetItem(tuple, 0);            /* leftover days */
1611     if (num == NULL)
1612         goto Done;
1613     Py_INCREF(num);
1614     temp = PyLong_AsLong(num);
1615     if (temp == -1 && PyErr_Occurred())
1616         goto Done;
1617     d = (int)temp;
1618     if ((long)d != temp) {
1619         PyErr_SetString(PyExc_OverflowError, "normalized days too "
1620                         "large to fit in a C int");
1621         goto Done;
1622     }
1623     result = new_delta_ex(d, s, us, 0, type);
1624 
1625 Done:
1626     Py_XDECREF(tuple);
1627     Py_XDECREF(num);
1628     return result;
1629 }
1630 
1631 #define microseconds_to_delta(pymicros) \
1632     microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1633 
1634 static PyObject *
multiply_int_timedelta(PyObject * intobj,PyDateTime_Delta * delta)1635 multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1636 {
1637     PyObject *pyus_in;
1638     PyObject *pyus_out;
1639     PyObject *result;
1640 
1641     pyus_in = delta_to_microseconds(delta);
1642     if (pyus_in == NULL)
1643         return NULL;
1644 
1645     pyus_out = PyNumber_Multiply(pyus_in, intobj);
1646     Py_DECREF(pyus_in);
1647     if (pyus_out == NULL)
1648         return NULL;
1649 
1650     result = microseconds_to_delta(pyus_out);
1651     Py_DECREF(pyus_out);
1652     return result;
1653 }
1654 
1655 static PyObject *
divide_timedelta_int(PyDateTime_Delta * delta,PyObject * intobj)1656 divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1657 {
1658     PyObject *pyus_in;
1659     PyObject *pyus_out;
1660     PyObject *result;
1661 
1662     pyus_in = delta_to_microseconds(delta);
1663     if (pyus_in == NULL)
1664         return NULL;
1665 
1666     pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1667     Py_DECREF(pyus_in);
1668     if (pyus_out == NULL)
1669         return NULL;
1670 
1671     result = microseconds_to_delta(pyus_out);
1672     Py_DECREF(pyus_out);
1673     return result;
1674 }
1675 
1676 static PyObject *
delta_add(PyObject * left,PyObject * right)1677 delta_add(PyObject *left, PyObject *right)
1678 {
1679     PyObject *result = Py_NotImplemented;
1680 
1681     if (PyDelta_Check(left) && PyDelta_Check(right)) {
1682         /* delta + delta */
1683         /* The C-level additions can't overflow because of the
1684          * invariant bounds.
1685          */
1686         int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1687         int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1688         int microseconds = GET_TD_MICROSECONDS(left) +
1689                            GET_TD_MICROSECONDS(right);
1690         result = new_delta(days, seconds, microseconds, 1);
1691     }
1692 
1693     if (result == Py_NotImplemented)
1694         Py_INCREF(result);
1695     return result;
1696 }
1697 
1698 static PyObject *
delta_negative(PyDateTime_Delta * self)1699 delta_negative(PyDateTime_Delta *self)
1700 {
1701     return new_delta(-GET_TD_DAYS(self),
1702                      -GET_TD_SECONDS(self),
1703                      -GET_TD_MICROSECONDS(self),
1704                      1);
1705 }
1706 
1707 static PyObject *
delta_positive(PyDateTime_Delta * self)1708 delta_positive(PyDateTime_Delta *self)
1709 {
1710     /* Could optimize this (by returning self) if this isn't a
1711      * subclass -- but who uses unary + ?  Approximately nobody.
1712      */
1713     return new_delta(GET_TD_DAYS(self),
1714                      GET_TD_SECONDS(self),
1715                      GET_TD_MICROSECONDS(self),
1716                      0);
1717 }
1718 
1719 static PyObject *
delta_abs(PyDateTime_Delta * self)1720 delta_abs(PyDateTime_Delta *self)
1721 {
1722     PyObject *result;
1723 
1724     assert(GET_TD_MICROSECONDS(self) >= 0);
1725     assert(GET_TD_SECONDS(self) >= 0);
1726 
1727     if (GET_TD_DAYS(self) < 0)
1728         result = delta_negative(self);
1729     else
1730         result = delta_positive(self);
1731 
1732     return result;
1733 }
1734 
1735 static PyObject *
delta_subtract(PyObject * left,PyObject * right)1736 delta_subtract(PyObject *left, PyObject *right)
1737 {
1738     PyObject *result = Py_NotImplemented;
1739 
1740     if (PyDelta_Check(left) && PyDelta_Check(right)) {
1741         /* delta - delta */
1742         /* The C-level additions can't overflow because of the
1743          * invariant bounds.
1744          */
1745         int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);
1746         int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);
1747         int microseconds = GET_TD_MICROSECONDS(left) -
1748                            GET_TD_MICROSECONDS(right);
1749         result = new_delta(days, seconds, microseconds, 1);
1750     }
1751 
1752     if (result == Py_NotImplemented)
1753         Py_INCREF(result);
1754     return result;
1755 }
1756 
1757 /* This is more natural as a tp_compare, but doesn't work then:  for whatever
1758  * reason, Python's try_3way_compare ignores tp_compare unless
1759  * PyInstance_Check returns true, but these aren't old-style classes.
1760  */
1761 static PyObject *
delta_richcompare(PyDateTime_Delta * self,PyObject * other,int op)1762 delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
1763 {
1764     int diff = 42;      /* nonsense */
1765 
1766     if (PyDelta_Check(other)) {
1767         diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1768         if (diff == 0) {
1769             diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);
1770             if (diff == 0)
1771                 diff = GET_TD_MICROSECONDS(self) -
1772                        GET_TD_MICROSECONDS(other);
1773         }
1774     }
1775     else if (op == Py_EQ || op == Py_NE)
1776         diff = 1;               /* any non-zero value will do */
1777 
1778     else /* stop this from falling back to address comparison */
1779         return cmperror((PyObject *)self, other);
1780 
1781     return diff_to_bool(diff, op);
1782 }
1783 
1784 static PyObject *delta_getstate(PyDateTime_Delta *self);
1785 
1786 static long
delta_hash(PyDateTime_Delta * self)1787 delta_hash(PyDateTime_Delta *self)
1788 {
1789     if (self->hashcode == -1) {
1790         PyObject *temp = delta_getstate(self);
1791         if (temp != NULL) {
1792             self->hashcode = PyObject_Hash(temp);
1793             Py_DECREF(temp);
1794         }
1795     }
1796     return self->hashcode;
1797 }
1798 
1799 static PyObject *
delta_multiply(PyObject * left,PyObject * right)1800 delta_multiply(PyObject *left, PyObject *right)
1801 {
1802     PyObject *result = Py_NotImplemented;
1803 
1804     if (PyDelta_Check(left)) {
1805         /* delta * ??? */
1806         if (_PyAnyInt_Check(right))
1807             result = multiply_int_timedelta(right,
1808                             (PyDateTime_Delta *) left);
1809     }
1810     else if (_PyAnyInt_Check(left))
1811         result = multiply_int_timedelta(left,
1812                                         (PyDateTime_Delta *) right);
1813 
1814     if (result == Py_NotImplemented)
1815         Py_INCREF(result);
1816     return result;
1817 }
1818 
1819 static PyObject *
delta_divide(PyObject * left,PyObject * right)1820 delta_divide(PyObject *left, PyObject *right)
1821 {
1822     PyObject *result = Py_NotImplemented;
1823 
1824     if (PyDelta_Check(left)) {
1825         /* delta * ??? */
1826         if (_PyAnyInt_Check(right))
1827             result = divide_timedelta_int(
1828                             (PyDateTime_Delta *)left,
1829                             right);
1830     }
1831 
1832     if (result == Py_NotImplemented)
1833         Py_INCREF(result);
1834     return result;
1835 }
1836 
1837 /* Fold in the value of the tag ("seconds", "weeks", etc) component of a
1838  * timedelta constructor.  sofar is the # of microseconds accounted for
1839  * so far, and there are factor microseconds per current unit, the number
1840  * of which is given by num.  num * factor is added to sofar in a
1841  * numerically careful way, and that's the result.  Any fractional
1842  * microseconds left over (this can happen if num is a float type) are
1843  * added into *leftover.
1844  * Note that there are many ways this can give an error (NULL) return.
1845  */
1846 static PyObject *
accum(const char * tag,PyObject * sofar,PyObject * num,PyObject * factor,double * leftover)1847 accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,
1848       double *leftover)
1849 {
1850     PyObject *prod;
1851     PyObject *sum;
1852 
1853     assert(num != NULL);
1854 
1855     if (_PyAnyInt_Check(num)) {
1856         prod = PyNumber_Multiply(factor, num);
1857         if (prod == NULL)
1858             return NULL;
1859         assert(_PyAnyInt_CheckExact(prod));
1860         sum = PyNumber_Add(sofar, prod);
1861         Py_DECREF(prod);
1862         assert(sum == NULL || _PyAnyInt_CheckExact(sum));
1863         return sum;
1864     }
1865 
1866     if (PyFloat_Check(num)) {
1867         double dnum;
1868         double fracpart;
1869         double intpart;
1870         PyObject *x;
1871         PyObject *y;
1872 
1873         /* The Plan:  decompose num into an integer part and a
1874          * fractional part, num = intpart + fracpart.
1875          * Then num * factor ==
1876          *      intpart * factor + fracpart * factor
1877          * and the LHS can be computed exactly in long arithmetic.
1878          * The RHS is again broken into an int part and frac part.
1879          * and the frac part is added into *leftover.
1880          */
1881         dnum = PyFloat_AsDouble(num);
1882         if (dnum == -1.0 && PyErr_Occurred())
1883             return NULL;
1884         fracpart = modf(dnum, &intpart);
1885         x = PyLong_FromDouble(intpart);
1886         if (x == NULL)
1887             return NULL;
1888 
1889         prod = PyNumber_Multiply(x, factor);
1890         Py_DECREF(x);
1891         if (prod == NULL)
1892             return NULL;
1893 
1894         sum = PyNumber_Add(sofar, prod);
1895         Py_DECREF(prod);
1896         if (sum == NULL)
1897             return NULL;
1898 
1899         if (fracpart == 0.0)
1900             return sum;
1901         /* So far we've lost no information.  Dealing with the
1902          * fractional part requires float arithmetic, and may
1903          * lose a little info.
1904          */
1905         assert(_PyAnyInt_CheckExact(factor));
1906         if (PyInt_Check(factor))
1907             dnum = (double)PyInt_AsLong(factor);
1908         else
1909             dnum = PyLong_AsDouble(factor);
1910 
1911         dnum *= fracpart;
1912         fracpart = modf(dnum, &intpart);
1913         x = PyLong_FromDouble(intpart);
1914         if (x == NULL) {
1915             Py_DECREF(sum);
1916             return NULL;
1917         }
1918 
1919         y = PyNumber_Add(sum, x);
1920         Py_DECREF(sum);
1921         Py_DECREF(x);
1922         *leftover += fracpart;
1923         assert(y == NULL || _PyAnyInt_CheckExact(y));
1924         return y;
1925     }
1926 
1927     PyErr_Format(PyExc_TypeError,
1928                  "unsupported type for timedelta %s component: %s",
1929                  tag, Py_TYPE(num)->tp_name);
1930     return NULL;
1931 }
1932 
1933 static PyObject *
delta_new(PyTypeObject * type,PyObject * args,PyObject * kw)1934 delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)
1935 {
1936     PyObject *self = NULL;
1937 
1938     /* Argument objects. */
1939     PyObject *day = NULL;
1940     PyObject *second = NULL;
1941     PyObject *us = NULL;
1942     PyObject *ms = NULL;
1943     PyObject *minute = NULL;
1944     PyObject *hour = NULL;
1945     PyObject *week = NULL;
1946 
1947     PyObject *x = NULL;         /* running sum of microseconds */
1948     PyObject *y = NULL;         /* temp sum of microseconds */
1949     double leftover_us = 0.0;
1950 
1951     static char *keywords[] = {
1952         "days", "seconds", "microseconds", "milliseconds",
1953         "minutes", "hours", "weeks", NULL
1954     };
1955 
1956     if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",
1957                                     keywords,
1958                                     &day, &second, &us,
1959                                     &ms, &minute, &hour, &week) == 0)
1960         goto Done;
1961 
1962     x = PyInt_FromLong(0);
1963     if (x == NULL)
1964         goto Done;
1965 
1966 #define CLEANUP         \
1967     Py_DECREF(x);       \
1968     x = y;              \
1969     if (x == NULL)      \
1970         goto Done
1971 
1972     if (us) {
1973         y = accum("microseconds", x, us, us_per_us, &leftover_us);
1974         CLEANUP;
1975     }
1976     if (ms) {
1977         y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);
1978         CLEANUP;
1979     }
1980     if (second) {
1981         y = accum("seconds", x, second, us_per_second, &leftover_us);
1982         CLEANUP;
1983     }
1984     if (minute) {
1985         y = accum("minutes", x, minute, us_per_minute, &leftover_us);
1986         CLEANUP;
1987     }
1988     if (hour) {
1989         y = accum("hours", x, hour, us_per_hour, &leftover_us);
1990         CLEANUP;
1991     }
1992     if (day) {
1993         y = accum("days", x, day, us_per_day, &leftover_us);
1994         CLEANUP;
1995     }
1996     if (week) {
1997         y = accum("weeks", x, week, us_per_week, &leftover_us);
1998         CLEANUP;
1999     }
2000     if (leftover_us) {
2001         /* Round to nearest whole # of us, and add into x. */
2002         PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));
2003         if (temp == NULL) {
2004             Py_DECREF(x);
2005             goto Done;
2006         }
2007         y = PyNumber_Add(x, temp);
2008         Py_DECREF(temp);
2009         CLEANUP;
2010     }
2011 
2012     self = microseconds_to_delta_ex(x, type);
2013     Py_DECREF(x);
2014 Done:
2015     return self;
2016 
2017 #undef CLEANUP
2018 }
2019 
2020 static int
delta_nonzero(PyDateTime_Delta * self)2021 delta_nonzero(PyDateTime_Delta *self)
2022 {
2023     return (GET_TD_DAYS(self) != 0
2024         || GET_TD_SECONDS(self) != 0
2025         || GET_TD_MICROSECONDS(self) != 0);
2026 }
2027 
2028 static PyObject *
delta_repr(PyDateTime_Delta * self)2029 delta_repr(PyDateTime_Delta *self)
2030 {
2031     if (GET_TD_MICROSECONDS(self) != 0)
2032         return PyString_FromFormat("%s(%d, %d, %d)",
2033                                    Py_TYPE(self)->tp_name,
2034                                    GET_TD_DAYS(self),
2035                                    GET_TD_SECONDS(self),
2036                                    GET_TD_MICROSECONDS(self));
2037     if (GET_TD_SECONDS(self) != 0)
2038         return PyString_FromFormat("%s(%d, %d)",
2039                                    Py_TYPE(self)->tp_name,
2040                                    GET_TD_DAYS(self),
2041                                    GET_TD_SECONDS(self));
2042 
2043     return PyString_FromFormat("%s(%d)",
2044                                Py_TYPE(self)->tp_name,
2045                                GET_TD_DAYS(self));
2046 }
2047 
2048 static PyObject *
delta_str(PyDateTime_Delta * self)2049 delta_str(PyDateTime_Delta *self)
2050 {
2051     int days = GET_TD_DAYS(self);
2052     int seconds = GET_TD_SECONDS(self);
2053     int us = GET_TD_MICROSECONDS(self);
2054     int hours;
2055     int minutes;
2056     char buf[100];
2057     char *pbuf = buf;
2058     size_t buflen = sizeof(buf);
2059     int n;
2060 
2061     minutes = divmod(seconds, 60, &seconds);
2062     hours = divmod(minutes, 60, &minutes);
2063 
2064     if (days) {
2065         n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,
2066                           (days == 1 || days == -1) ? "" : "s");
2067         if (n < 0 || (size_t)n >= buflen)
2068             goto Fail;
2069         pbuf += n;
2070         buflen -= (size_t)n;
2071     }
2072 
2073     n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",
2074                       hours, minutes, seconds);
2075     if (n < 0 || (size_t)n >= buflen)
2076         goto Fail;
2077     pbuf += n;
2078     buflen -= (size_t)n;
2079 
2080     if (us) {
2081         n = PyOS_snprintf(pbuf, buflen, ".%06d", us);
2082         if (n < 0 || (size_t)n >= buflen)
2083             goto Fail;
2084         pbuf += n;
2085     }
2086 
2087     return PyString_FromStringAndSize(buf, pbuf - buf);
2088 
2089  Fail:
2090     PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");
2091     return NULL;
2092 }
2093 
2094 /* Pickle support, a simple use of __reduce__. */
2095 
2096 /* __getstate__ isn't exposed */
2097 static PyObject *
delta_getstate(PyDateTime_Delta * self)2098 delta_getstate(PyDateTime_Delta *self)
2099 {
2100     return Py_BuildValue("iii", GET_TD_DAYS(self),
2101                                 GET_TD_SECONDS(self),
2102                                 GET_TD_MICROSECONDS(self));
2103 }
2104 
2105 static PyObject *
delta_total_seconds(PyObject * self)2106 delta_total_seconds(PyObject *self)
2107 {
2108     PyObject *total_seconds;
2109     PyObject *total_microseconds;
2110     PyObject *one_million;
2111 
2112     total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);
2113     if (total_microseconds == NULL)
2114         return NULL;
2115 
2116     one_million = PyLong_FromLong(1000000L);
2117     if (one_million == NULL) {
2118         Py_DECREF(total_microseconds);
2119         return NULL;
2120     }
2121 
2122     total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);
2123 
2124     Py_DECREF(total_microseconds);
2125     Py_DECREF(one_million);
2126     return total_seconds;
2127 }
2128 
2129 static PyObject *
delta_reduce(PyDateTime_Delta * self)2130 delta_reduce(PyDateTime_Delta* self)
2131 {
2132     return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));
2133 }
2134 
2135 #define OFFSET(field)  offsetof(PyDateTime_Delta, field)
2136 
2137 static PyMemberDef delta_members[] = {
2138 
2139     {"days",         T_INT, OFFSET(days),         READONLY,
2140      PyDoc_STR("Number of days.")},
2141 
2142     {"seconds",      T_INT, OFFSET(seconds),      READONLY,
2143      PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},
2144 
2145     {"microseconds", T_INT, OFFSET(microseconds), READONLY,
2146      PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},
2147     {NULL}
2148 };
2149 
2150 static PyMethodDef delta_methods[] = {
2151     {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,
2152      PyDoc_STR("Total seconds in the duration.")},
2153 
2154     {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,
2155      PyDoc_STR("__reduce__() -> (cls, state)")},
2156 
2157     {NULL,      NULL},
2158 };
2159 
2160 static char delta_doc[] =
2161 PyDoc_STR("Difference between two datetime values.");
2162 
2163 static PyNumberMethods delta_as_number = {
2164     delta_add,                                  /* nb_add */
2165     delta_subtract,                             /* nb_subtract */
2166     delta_multiply,                             /* nb_multiply */
2167     delta_divide,                               /* nb_divide */
2168     0,                                          /* nb_remainder */
2169     0,                                          /* nb_divmod */
2170     0,                                          /* nb_power */
2171     (unaryfunc)delta_negative,                  /* nb_negative */
2172     (unaryfunc)delta_positive,                  /* nb_positive */
2173     (unaryfunc)delta_abs,                       /* nb_absolute */
2174     (inquiry)delta_nonzero,                     /* nb_nonzero */
2175     0,                                          /*nb_invert*/
2176     0,                                          /*nb_lshift*/
2177     0,                                          /*nb_rshift*/
2178     0,                                          /*nb_and*/
2179     0,                                          /*nb_xor*/
2180     0,                                          /*nb_or*/
2181     0,                                          /*nb_coerce*/
2182     0,                                          /*nb_int*/
2183     0,                                          /*nb_long*/
2184     0,                                          /*nb_float*/
2185     0,                                          /*nb_oct*/
2186     0,                                          /*nb_hex*/
2187     0,                                          /*nb_inplace_add*/
2188     0,                                          /*nb_inplace_subtract*/
2189     0,                                          /*nb_inplace_multiply*/
2190     0,                                          /*nb_inplace_divide*/
2191     0,                                          /*nb_inplace_remainder*/
2192     0,                                          /*nb_inplace_power*/
2193     0,                                          /*nb_inplace_lshift*/
2194     0,                                          /*nb_inplace_rshift*/
2195     0,                                          /*nb_inplace_and*/
2196     0,                                          /*nb_inplace_xor*/
2197     0,                                          /*nb_inplace_or*/
2198     delta_divide,                               /* nb_floor_divide */
2199     0,                                          /* nb_true_divide */
2200     0,                                          /* nb_inplace_floor_divide */
2201     0,                                          /* nb_inplace_true_divide */
2202 };
2203 
2204 static PyTypeObject PyDateTime_DeltaType = {
2205     PyVarObject_HEAD_INIT(NULL, 0)
2206     "datetime.timedelta",                               /* tp_name */
2207     sizeof(PyDateTime_Delta),                           /* tp_basicsize */
2208     0,                                                  /* tp_itemsize */
2209     0,                                                  /* tp_dealloc */
2210     0,                                                  /* tp_print */
2211     0,                                                  /* tp_getattr */
2212     0,                                                  /* tp_setattr */
2213     0,                                                  /* tp_compare */
2214     (reprfunc)delta_repr,                               /* tp_repr */
2215     &delta_as_number,                                   /* tp_as_number */
2216     0,                                                  /* tp_as_sequence */
2217     0,                                                  /* tp_as_mapping */
2218     (hashfunc)delta_hash,                               /* tp_hash */
2219     0,                                                  /* tp_call */
2220     (reprfunc)delta_str,                                /* tp_str */
2221     PyObject_GenericGetAttr,                            /* tp_getattro */
2222     0,                                                  /* tp_setattro */
2223     0,                                                  /* tp_as_buffer */
2224     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2225         Py_TPFLAGS_BASETYPE,                            /* tp_flags */
2226     delta_doc,                                          /* tp_doc */
2227     0,                                                  /* tp_traverse */
2228     0,                                                  /* tp_clear */
2229     (richcmpfunc)delta_richcompare,                     /* tp_richcompare */
2230     0,                                                  /* tp_weaklistoffset */
2231     0,                                                  /* tp_iter */
2232     0,                                                  /* tp_iternext */
2233     delta_methods,                                      /* tp_methods */
2234     delta_members,                                      /* tp_members */
2235     0,                                                  /* tp_getset */
2236     0,                                                  /* tp_base */
2237     0,                                                  /* tp_dict */
2238     0,                                                  /* tp_descr_get */
2239     0,                                                  /* tp_descr_set */
2240     0,                                                  /* tp_dictoffset */
2241     0,                                                  /* tp_init */
2242     0,                                                  /* tp_alloc */
2243     delta_new,                                          /* tp_new */
2244     0,                                                  /* tp_free */
2245 };
2246 
2247 /*
2248  * PyDateTime_Date implementation.
2249  */
2250 
2251 /* Accessor properties. */
2252 
2253 static PyObject *
date_year(PyDateTime_Date * self,void * unused)2254 date_year(PyDateTime_Date *self, void *unused)
2255 {
2256     return PyInt_FromLong(GET_YEAR(self));
2257 }
2258 
2259 static PyObject *
date_month(PyDateTime_Date * self,void * unused)2260 date_month(PyDateTime_Date *self, void *unused)
2261 {
2262     return PyInt_FromLong(GET_MONTH(self));
2263 }
2264 
2265 static PyObject *
date_day(PyDateTime_Date * self,void * unused)2266 date_day(PyDateTime_Date *self, void *unused)
2267 {
2268     return PyInt_FromLong(GET_DAY(self));
2269 }
2270 
2271 static PyGetSetDef date_getset[] = {
2272     {"year",        (getter)date_year},
2273     {"month",       (getter)date_month},
2274     {"day",         (getter)date_day},
2275     {NULL}
2276 };
2277 
2278 /* Constructors. */
2279 
2280 static char *date_kws[] = {"year", "month", "day", NULL};
2281 
2282 static PyObject *
date_new(PyTypeObject * type,PyObject * args,PyObject * kw)2283 date_new(PyTypeObject *type, PyObject *args, PyObject *kw)
2284 {
2285     PyObject *self = NULL;
2286     PyObject *state;
2287     int year;
2288     int month;
2289     int day;
2290 
2291     /* Check for invocation from pickle with __getstate__ state */
2292     if (PyTuple_GET_SIZE(args) == 1 &&
2293         PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
2294         PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&
2295         MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
2296     {
2297         PyDateTime_Date *me;
2298 
2299         me = (PyDateTime_Date *) (type->tp_alloc(type, 0));
2300         if (me != NULL) {
2301             char *pdata = PyString_AS_STRING(state);
2302             memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);
2303             me->hashcode = -1;
2304         }
2305         return (PyObject *)me;
2306     }
2307 
2308     if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,
2309                                     &year, &month, &day)) {
2310         if (check_date_args(year, month, day) < 0)
2311             return NULL;
2312         self = new_date_ex(year, month, day, type);
2313     }
2314     return self;
2315 }
2316 
2317 /* Return new date from localtime(t). */
2318 static PyObject *
date_local_from_time_t(PyObject * cls,double ts)2319 date_local_from_time_t(PyObject *cls, double ts)
2320 {
2321     struct tm *tm;
2322     time_t t;
2323     PyObject *result = NULL;
2324 
2325     t = _PyTime_DoubleToTimet(ts);
2326     if (t == (time_t)-1 && PyErr_Occurred())
2327         return NULL;
2328     tm = localtime(&t);
2329     if (tm)
2330         result = PyObject_CallFunction(cls, "iii",
2331                                        tm->tm_year + 1900,
2332                                        tm->tm_mon + 1,
2333                                        tm->tm_mday);
2334     else
2335         PyErr_SetString(PyExc_ValueError,
2336                         "timestamp out of range for "
2337                         "platform localtime() function");
2338     return result;
2339 }
2340 
2341 /* Return new date from current time.
2342  * We say this is equivalent to fromtimestamp(time.time()), and the
2343  * only way to be sure of that is to *call* time.time().  That's not
2344  * generally the same as calling C's time.
2345  */
2346 static PyObject *
date_today(PyObject * cls,PyObject * dummy)2347 date_today(PyObject *cls, PyObject *dummy)
2348 {
2349     PyObject *time;
2350     PyObject *result;
2351 
2352     time = time_time();
2353     if (time == NULL)
2354         return NULL;
2355 
2356     /* Note well:  today() is a class method, so this may not call
2357      * date.fromtimestamp.  For example, it may call
2358      * datetime.fromtimestamp.  That's why we need all the accuracy
2359      * time.time() delivers; if someone were gonzo about optimization,
2360      * date.today() could get away with plain C time().
2361      */
2362     result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);
2363     Py_DECREF(time);
2364     return result;
2365 }
2366 
2367 /* Return new date from given timestamp (Python timestamp -- a double). */
2368 static PyObject *
date_fromtimestamp(PyObject * cls,PyObject * args)2369 date_fromtimestamp(PyObject *cls, PyObject *args)
2370 {
2371     double timestamp;
2372     PyObject *result = NULL;
2373 
2374     if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))
2375         result = date_local_from_time_t(cls, timestamp);
2376     return result;
2377 }
2378 
2379 /* Return new date from proleptic Gregorian ordinal.  Raises ValueError if
2380  * the ordinal is out of range.
2381  */
2382 static PyObject *
date_fromordinal(PyObject * cls,PyObject * args)2383 date_fromordinal(PyObject *cls, PyObject *args)
2384 {
2385     PyObject *result = NULL;
2386     int ordinal;
2387 
2388     if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {
2389         int year;
2390         int month;
2391         int day;
2392 
2393         if (ordinal < 1)
2394             PyErr_SetString(PyExc_ValueError, "ordinal must be "
2395                                               ">= 1");
2396         else {
2397             ord_to_ymd(ordinal, &year, &month, &day);
2398             result = PyObject_CallFunction(cls, "iii",
2399                                            year, month, day);
2400         }
2401     }
2402     return result;
2403 }
2404 
2405 /*
2406  * Date arithmetic.
2407  */
2408 
2409 /* date + timedelta -> date.  If arg negate is true, subtract the timedelta
2410  * instead.
2411  */
2412 static PyObject *
add_date_timedelta(PyDateTime_Date * date,PyDateTime_Delta * delta,int negate)2413 add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)
2414 {
2415     PyObject *result = NULL;
2416     int year = GET_YEAR(date);
2417     int month = GET_MONTH(date);
2418     int deltadays = GET_TD_DAYS(delta);
2419     /* C-level overflow is impossible because |deltadays| < 1e9. */
2420     int day = GET_DAY(date) + (negate ? -deltadays : deltadays);
2421 
2422     if (normalize_date(&year, &month, &day) >= 0)
2423         result = new_date(year, month, day);
2424     return result;
2425 }
2426 
2427 static PyObject *
date_add(PyObject * left,PyObject * right)2428 date_add(PyObject *left, PyObject *right)
2429 {
2430     if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2431         Py_INCREF(Py_NotImplemented);
2432         return Py_NotImplemented;
2433     }
2434     if (PyDate_Check(left)) {
2435         /* date + ??? */
2436         if (PyDelta_Check(right))
2437             /* date + delta */
2438             return add_date_timedelta((PyDateTime_Date *) left,
2439                                       (PyDateTime_Delta *) right,
2440                                       0);
2441     }
2442     else {
2443         /* ??? + date
2444          * 'right' must be one of us, or we wouldn't have been called
2445          */
2446         if (PyDelta_Check(left))
2447             /* delta + date */
2448             return add_date_timedelta((PyDateTime_Date *) right,
2449                                       (PyDateTime_Delta *) left,
2450                                       0);
2451     }
2452     Py_INCREF(Py_NotImplemented);
2453     return Py_NotImplemented;
2454 }
2455 
2456 static PyObject *
date_subtract(PyObject * left,PyObject * right)2457 date_subtract(PyObject *left, PyObject *right)
2458 {
2459     if (PyDateTime_Check(left) || PyDateTime_Check(right)) {
2460         Py_INCREF(Py_NotImplemented);
2461         return Py_NotImplemented;
2462     }
2463     if (PyDate_Check(left)) {
2464         if (PyDate_Check(right)) {
2465             /* date - date */
2466             int left_ord = ymd_to_ord(GET_YEAR(left),
2467                                       GET_MONTH(left),
2468                                       GET_DAY(left));
2469             int right_ord = ymd_to_ord(GET_YEAR(right),
2470                                        GET_MONTH(right),
2471                                        GET_DAY(right));
2472             return new_delta(left_ord - right_ord, 0, 0, 0);
2473         }
2474         if (PyDelta_Check(right)) {
2475             /* date - delta */
2476             return add_date_timedelta((PyDateTime_Date *) left,
2477                                       (PyDateTime_Delta *) right,
2478                                       1);
2479         }
2480     }
2481     Py_INCREF(Py_NotImplemented);
2482     return Py_NotImplemented;
2483 }
2484 
2485 
2486 /* Various ways to turn a date into a string. */
2487 
2488 static PyObject *
date_repr(PyDateTime_Date * self)2489 date_repr(PyDateTime_Date *self)
2490 {
2491     char buffer[1028];
2492     const char *type_name;
2493 
2494     type_name = Py_TYPE(self)->tp_name;
2495     PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",
2496                   type_name,
2497                   GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2498 
2499     return PyString_FromString(buffer);
2500 }
2501 
2502 static PyObject *
date_isoformat(PyDateTime_Date * self)2503 date_isoformat(PyDateTime_Date *self)
2504 {
2505     char buffer[128];
2506 
2507     isoformat_date(self, buffer, sizeof(buffer));
2508     return PyString_FromString(buffer);
2509 }
2510 
2511 /* str() calls the appropriate isoformat() method. */
2512 static PyObject *
date_str(PyDateTime_Date * self)2513 date_str(PyDateTime_Date *self)
2514 {
2515     return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
2516 }
2517 
2518 
2519 static PyObject *
date_ctime(PyDateTime_Date * self)2520 date_ctime(PyDateTime_Date *self)
2521 {
2522     return format_ctime(self, 0, 0, 0);
2523 }
2524 
2525 static PyObject *
date_strftime(PyDateTime_Date * self,PyObject * args,PyObject * kw)2526 date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2527 {
2528     /* This method can be inherited, and needs to call the
2529      * timetuple() method appropriate to self's class.
2530      */
2531     PyObject *result;
2532     PyObject *tuple;
2533     const char *format;
2534     Py_ssize_t format_len;
2535     static char *keywords[] = {"format", NULL};
2536 
2537     if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
2538                                       &format, &format_len))
2539         return NULL;
2540 
2541     tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");
2542     if (tuple == NULL)
2543         return NULL;
2544     result = wrap_strftime((PyObject *)self, format, format_len, tuple,
2545                            (PyObject *)self);
2546     Py_DECREF(tuple);
2547     return result;
2548 }
2549 
2550 static PyObject *
date_format(PyDateTime_Date * self,PyObject * args)2551 date_format(PyDateTime_Date *self, PyObject *args)
2552 {
2553     PyObject *format;
2554 
2555     if (!PyArg_ParseTuple(args, "O:__format__", &format))
2556         return NULL;
2557 
2558     /* Check for str or unicode */
2559     if (PyString_Check(format)) {
2560         /* If format is zero length, return str(self) */
2561         if (PyString_GET_SIZE(format) == 0)
2562             return PyObject_Str((PyObject *)self);
2563     } else if (PyUnicode_Check(format)) {
2564         /* If format is zero length, return str(self) */
2565         if (PyUnicode_GET_SIZE(format) == 0)
2566             return PyObject_Unicode((PyObject *)self);
2567     } else {
2568         PyErr_Format(PyExc_ValueError,
2569                      "__format__ expects str or unicode, not %.200s",
2570                      Py_TYPE(format)->tp_name);
2571         return NULL;
2572     }
2573     return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);
2574 }
2575 
2576 /* ISO methods. */
2577 
2578 static PyObject *
date_isoweekday(PyDateTime_Date * self)2579 date_isoweekday(PyDateTime_Date *self)
2580 {
2581     int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2582 
2583     return PyInt_FromLong(dow + 1);
2584 }
2585 
2586 static PyObject *
date_isocalendar(PyDateTime_Date * self)2587 date_isocalendar(PyDateTime_Date *self)
2588 {
2589     int  year         = GET_YEAR(self);
2590     int  week1_monday = iso_week1_monday(year);
2591     int today         = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));
2592     int  week;
2593     int  day;
2594 
2595     week = divmod(today - week1_monday, 7, &day);
2596     if (week < 0) {
2597         --year;
2598         week1_monday = iso_week1_monday(year);
2599         week = divmod(today - week1_monday, 7, &day);
2600     }
2601     else if (week >= 52 && today >= iso_week1_monday(year + 1)) {
2602         ++year;
2603         week = 0;
2604     }
2605     return Py_BuildValue("iii", year, week + 1, day + 1);
2606 }
2607 
2608 /* Miscellaneous methods. */
2609 
2610 /* This is more natural as a tp_compare, but doesn't work then:  for whatever
2611  * reason, Python's try_3way_compare ignores tp_compare unless
2612  * PyInstance_Check returns true, but these aren't old-style classes.
2613  */
2614 static PyObject *
date_richcompare(PyDateTime_Date * self,PyObject * other,int op)2615 date_richcompare(PyDateTime_Date *self, PyObject *other, int op)
2616 {
2617     int diff = 42;      /* nonsense */
2618 
2619     if (PyDate_Check(other))
2620         diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,
2621                       _PyDateTime_DATE_DATASIZE);
2622 
2623     else if (PyObject_HasAttrString(other, "timetuple")) {
2624         /* A hook for other kinds of date objects. */
2625         Py_INCREF(Py_NotImplemented);
2626         return Py_NotImplemented;
2627     }
2628     else if (op == Py_EQ || op == Py_NE)
2629         diff = 1;               /* any non-zero value will do */
2630 
2631     else /* stop this from falling back to address comparison */
2632         return cmperror((PyObject *)self, other);
2633 
2634     return diff_to_bool(diff, op);
2635 }
2636 
2637 static PyObject *
date_timetuple(PyDateTime_Date * self)2638 date_timetuple(PyDateTime_Date *self)
2639 {
2640     return build_struct_time(GET_YEAR(self),
2641                              GET_MONTH(self),
2642                              GET_DAY(self),
2643                              0, 0, 0, -1);
2644 }
2645 
2646 static PyObject *
date_replace(PyDateTime_Date * self,PyObject * args,PyObject * kw)2647 date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)
2648 {
2649     PyObject *clone;
2650     PyObject *tuple;
2651     int year = GET_YEAR(self);
2652     int month = GET_MONTH(self);
2653     int day = GET_DAY(self);
2654 
2655     if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,
2656                                       &year, &month, &day))
2657         return NULL;
2658     tuple = Py_BuildValue("iii", year, month, day);
2659     if (tuple == NULL)
2660         return NULL;
2661     clone = date_new(Py_TYPE(self), tuple, NULL);
2662     Py_DECREF(tuple);
2663     return clone;
2664 }
2665 
2666 static PyObject *date_getstate(PyDateTime_Date *self);
2667 
2668 static long
date_hash(PyDateTime_Date * self)2669 date_hash(PyDateTime_Date *self)
2670 {
2671     if (self->hashcode == -1) {
2672         PyObject *temp = date_getstate(self);
2673         if (temp != NULL) {
2674             self->hashcode = PyObject_Hash(temp);
2675             Py_DECREF(temp);
2676         }
2677     }
2678     return self->hashcode;
2679 }
2680 
2681 static PyObject *
date_toordinal(PyDateTime_Date * self)2682 date_toordinal(PyDateTime_Date *self)
2683 {
2684     return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),
2685                                      GET_DAY(self)));
2686 }
2687 
2688 static PyObject *
date_weekday(PyDateTime_Date * self)2689 date_weekday(PyDateTime_Date *self)
2690 {
2691     int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));
2692 
2693     return PyInt_FromLong(dow);
2694 }
2695 
2696 /* Pickle support, a simple use of __reduce__. */
2697 
2698 /* __getstate__ isn't exposed */
2699 static PyObject *
date_getstate(PyDateTime_Date * self)2700 date_getstate(PyDateTime_Date *self)
2701 {
2702     return Py_BuildValue(
2703         "(N)",
2704         PyString_FromStringAndSize((char *)self->data,
2705                                    _PyDateTime_DATE_DATASIZE));
2706 }
2707 
2708 static PyObject *
date_reduce(PyDateTime_Date * self,PyObject * arg)2709 date_reduce(PyDateTime_Date *self, PyObject *arg)
2710 {
2711     return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));
2712 }
2713 
2714 static PyMethodDef date_methods[] = {
2715 
2716     /* Class methods: */
2717 
2718     {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |
2719                                                        METH_CLASS,
2720      PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "
2721                "time.time()).")},
2722 
2723     {"fromordinal", (PyCFunction)date_fromordinal,      METH_VARARGS |
2724                                                     METH_CLASS,
2725      PyDoc_STR("int -> date corresponding to a proleptic Gregorian "
2726                "ordinal.")},
2727 
2728     {"today",         (PyCFunction)date_today,   METH_NOARGS | METH_CLASS,
2729      PyDoc_STR("Current date or datetime:  same as "
2730                "self.__class__.fromtimestamp(time.time()).")},
2731 
2732     /* Instance methods: */
2733 
2734     {"ctime",       (PyCFunction)date_ctime,        METH_NOARGS,
2735      PyDoc_STR("Return ctime() style string.")},
2736 
2737     {"strftime",        (PyCFunction)date_strftime,     METH_VARARGS | METH_KEYWORDS,
2738      PyDoc_STR("format -> strftime() style string.")},
2739 
2740     {"__format__",      (PyCFunction)date_format,       METH_VARARGS,
2741      PyDoc_STR("Formats self with strftime.")},
2742 
2743     {"timetuple",   (PyCFunction)date_timetuple,    METH_NOARGS,
2744      PyDoc_STR("Return time tuple, compatible with time.localtime().")},
2745 
2746     {"isocalendar", (PyCFunction)date_isocalendar,  METH_NOARGS,
2747      PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "
2748                "weekday.")},
2749 
2750     {"isoformat",   (PyCFunction)date_isoformat,        METH_NOARGS,
2751      PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},
2752 
2753     {"isoweekday",  (PyCFunction)date_isoweekday,   METH_NOARGS,
2754      PyDoc_STR("Return the day of the week represented by the date.\n"
2755                "Monday == 1 ... Sunday == 7")},
2756 
2757     {"toordinal",   (PyCFunction)date_toordinal,    METH_NOARGS,
2758      PyDoc_STR("Return proleptic Gregorian ordinal.  January 1 of year "
2759                "1 is day 1.")},
2760 
2761     {"weekday",     (PyCFunction)date_weekday,      METH_NOARGS,
2762      PyDoc_STR("Return the day of the week represented by the date.\n"
2763                "Monday == 0 ... Sunday == 6")},
2764 
2765     {"replace",     (PyCFunction)date_replace,      METH_VARARGS | METH_KEYWORDS,
2766      PyDoc_STR("Return date with new specified fields.")},
2767 
2768     {"__reduce__", (PyCFunction)date_reduce,        METH_NOARGS,
2769      PyDoc_STR("__reduce__() -> (cls, state)")},
2770 
2771     {NULL,      NULL}
2772 };
2773 
2774 static char date_doc[] =
2775 PyDoc_STR("date(year, month, day) --> date object");
2776 
2777 static PyNumberMethods date_as_number = {
2778     date_add,                                           /* nb_add */
2779     date_subtract,                                      /* nb_subtract */
2780     0,                                                  /* nb_multiply */
2781     0,                                                  /* nb_divide */
2782     0,                                                  /* nb_remainder */
2783     0,                                                  /* nb_divmod */
2784     0,                                                  /* nb_power */
2785     0,                                                  /* nb_negative */
2786     0,                                                  /* nb_positive */
2787     0,                                                  /* nb_absolute */
2788     0,                                                  /* nb_nonzero */
2789 };
2790 
2791 static PyTypeObject PyDateTime_DateType = {
2792     PyVarObject_HEAD_INIT(NULL, 0)
2793     "datetime.date",                                    /* tp_name */
2794     sizeof(PyDateTime_Date),                            /* tp_basicsize */
2795     0,                                                  /* tp_itemsize */
2796     0,                                                  /* tp_dealloc */
2797     0,                                                  /* tp_print */
2798     0,                                                  /* tp_getattr */
2799     0,                                                  /* tp_setattr */
2800     0,                                                  /* tp_compare */
2801     (reprfunc)date_repr,                                /* tp_repr */
2802     &date_as_number,                                    /* tp_as_number */
2803     0,                                                  /* tp_as_sequence */
2804     0,                                                  /* tp_as_mapping */
2805     (hashfunc)date_hash,                                /* tp_hash */
2806     0,                                                  /* tp_call */
2807     (reprfunc)date_str,                                 /* tp_str */
2808     PyObject_GenericGetAttr,                            /* tp_getattro */
2809     0,                                                  /* tp_setattro */
2810     0,                                                  /* tp_as_buffer */
2811     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
2812     Py_TPFLAGS_BASETYPE,                                /* tp_flags */
2813     date_doc,                                           /* tp_doc */
2814     0,                                                  /* tp_traverse */
2815     0,                                                  /* tp_clear */
2816     (richcmpfunc)date_richcompare,                      /* tp_richcompare */
2817     0,                                                  /* tp_weaklistoffset */
2818     0,                                                  /* tp_iter */
2819     0,                                                  /* tp_iternext */
2820     date_methods,                                       /* tp_methods */
2821     0,                                                  /* tp_members */
2822     date_getset,                                        /* tp_getset */
2823     0,                                                  /* tp_base */
2824     0,                                                  /* tp_dict */
2825     0,                                                  /* tp_descr_get */
2826     0,                                                  /* tp_descr_set */
2827     0,                                                  /* tp_dictoffset */
2828     0,                                                  /* tp_init */
2829     0,                                                  /* tp_alloc */
2830     date_new,                                           /* tp_new */
2831     0,                                                  /* tp_free */
2832 };
2833 
2834 /*
2835  * PyDateTime_TZInfo implementation.
2836  */
2837 
2838 /* This is a pure abstract base class, so doesn't do anything beyond
2839  * raising NotImplemented exceptions.  Real tzinfo classes need
2840  * to derive from this.  This is mostly for clarity, and for efficiency in
2841  * datetime and time constructors (their tzinfo arguments need to
2842  * be subclasses of this tzinfo class, which is easy and quick to check).
2843  *
2844  * Note:  For reasons having to do with pickling of subclasses, we have
2845  * to allow tzinfo objects to be instantiated.  This wasn't an issue
2846  * in the Python implementation (__init__() could raise NotImplementedError
2847  * there without ill effect), but doing so in the C implementation hit a
2848  * brick wall.
2849  */
2850 
2851 static PyObject *
tzinfo_nogo(const char * methodname)2852 tzinfo_nogo(const char* methodname)
2853 {
2854     PyErr_Format(PyExc_NotImplementedError,
2855                  "a tzinfo subclass must implement %s()",
2856                  methodname);
2857     return NULL;
2858 }
2859 
2860 /* Methods.  A subclass must implement these. */
2861 
2862 static PyObject *
tzinfo_tzname(PyDateTime_TZInfo * self,PyObject * dt)2863 tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)
2864 {
2865     return tzinfo_nogo("tzname");
2866 }
2867 
2868 static PyObject *
tzinfo_utcoffset(PyDateTime_TZInfo * self,PyObject * dt)2869 tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)
2870 {
2871     return tzinfo_nogo("utcoffset");
2872 }
2873 
2874 static PyObject *
tzinfo_dst(PyDateTime_TZInfo * self,PyObject * dt)2875 tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)
2876 {
2877     return tzinfo_nogo("dst");
2878 }
2879 
2880 static PyObject *
tzinfo_fromutc(PyDateTime_TZInfo * self,PyDateTime_DateTime * dt)2881 tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)
2882 {
2883     int y, m, d, hh, mm, ss, us;
2884 
2885     PyObject *result;
2886     int off, dst;
2887     int none;
2888     int delta;
2889 
2890     if (! PyDateTime_Check(dt)) {
2891         PyErr_SetString(PyExc_TypeError,
2892                         "fromutc: argument must be a datetime");
2893         return NULL;
2894     }
2895     if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {
2896         PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "
2897                         "is not self");
2898         return NULL;
2899     }
2900 
2901     off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);
2902     if (off == -1 && PyErr_Occurred())
2903         return NULL;
2904     if (none) {
2905         PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2906                         "utcoffset() result required");
2907         return NULL;
2908     }
2909 
2910     dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);
2911     if (dst == -1 && PyErr_Occurred())
2912         return NULL;
2913     if (none) {
2914         PyErr_SetString(PyExc_ValueError, "fromutc: non-None "
2915                         "dst() result required");
2916         return NULL;
2917     }
2918 
2919     y = GET_YEAR(dt);
2920     m = GET_MONTH(dt);
2921     d = GET_DAY(dt);
2922     hh = DATE_GET_HOUR(dt);
2923     mm = DATE_GET_MINUTE(dt);
2924     ss = DATE_GET_SECOND(dt);
2925     us = DATE_GET_MICROSECOND(dt);
2926 
2927     delta = off - dst;
2928     mm += delta;
2929     if ((mm < 0 || mm >= 60) &&
2930         normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2931         return NULL;
2932     result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2933     if (result == NULL)
2934         return result;
2935 
2936     dst = call_dst(dt->tzinfo, result, &none);
2937     if (dst == -1 && PyErr_Occurred())
2938         goto Fail;
2939     if (none)
2940         goto Inconsistent;
2941     if (dst == 0)
2942         return result;
2943 
2944     mm += dst;
2945     if ((mm < 0 || mm >= 60) &&
2946         normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
2947         goto Fail;
2948     Py_DECREF(result);
2949     result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);
2950     return result;
2951 
2952 Inconsistent:
2953     PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"
2954                     "inconsistent results; cannot convert");
2955 
2956     /* fall thru to failure */
2957 Fail:
2958     Py_DECREF(result);
2959     return NULL;
2960 }
2961 
2962 /*
2963  * Pickle support.  This is solely so that tzinfo subclasses can use
2964  * pickling -- tzinfo itself is supposed to be uninstantiable.
2965  */
2966 
2967 static PyObject *
tzinfo_reduce(PyObject * self)2968 tzinfo_reduce(PyObject *self)
2969 {
2970     PyObject *args, *state, *tmp;
2971     PyObject *getinitargs, *getstate;
2972 
2973     tmp = PyTuple_New(0);
2974     if (tmp == NULL)
2975         return NULL;
2976 
2977     getinitargs = PyObject_GetAttrString(self, "__getinitargs__");
2978     if (getinitargs != NULL) {
2979         args = PyObject_CallObject(getinitargs, tmp);
2980         Py_DECREF(getinitargs);
2981         if (args == NULL) {
2982             Py_DECREF(tmp);
2983             return NULL;
2984         }
2985     }
2986     else {
2987         PyErr_Clear();
2988         args = tmp;
2989         Py_INCREF(args);
2990     }
2991 
2992     getstate = PyObject_GetAttrString(self, "__getstate__");
2993     if (getstate != NULL) {
2994         state = PyObject_CallObject(getstate, tmp);
2995         Py_DECREF(getstate);
2996         if (state == NULL) {
2997             Py_DECREF(args);
2998             Py_DECREF(tmp);
2999             return NULL;
3000         }
3001     }
3002     else {
3003         PyObject **dictptr;
3004         PyErr_Clear();
3005         state = Py_None;
3006         dictptr = _PyObject_GetDictPtr(self);
3007         if (dictptr && *dictptr && PyDict_Size(*dictptr))
3008             state = *dictptr;
3009         Py_INCREF(state);
3010     }
3011 
3012     Py_DECREF(tmp);
3013 
3014     if (state == Py_None) {
3015         Py_DECREF(state);
3016         return Py_BuildValue("(ON)", Py_TYPE(self), args);
3017     }
3018     else
3019         return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);
3020 }
3021 
3022 static PyMethodDef tzinfo_methods[] = {
3023 
3024     {"tzname",          (PyCFunction)tzinfo_tzname,             METH_O,
3025      PyDoc_STR("datetime -> string name of time zone.")},
3026 
3027     {"utcoffset",       (PyCFunction)tzinfo_utcoffset,          METH_O,
3028      PyDoc_STR("datetime -> minutes east of UTC (negative for "
3029                "west of UTC).")},
3030 
3031     {"dst",             (PyCFunction)tzinfo_dst,                METH_O,
3032      PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},
3033 
3034     {"fromutc",         (PyCFunction)tzinfo_fromutc,            METH_O,
3035      PyDoc_STR("datetime in UTC -> datetime in local time.")},
3036 
3037     {"__reduce__",  (PyCFunction)tzinfo_reduce,             METH_NOARGS,
3038      PyDoc_STR("-> (cls, state)")},
3039 
3040     {NULL, NULL}
3041 };
3042 
3043 static char tzinfo_doc[] =
3044 PyDoc_STR("Abstract base class for time zone info objects.");
3045 
3046 statichere PyTypeObject PyDateTime_TZInfoType = {
3047     PyVarObject_HEAD_INIT(NULL, 0)
3048     "datetime.tzinfo",                          /* tp_name */
3049     sizeof(PyDateTime_TZInfo),                  /* tp_basicsize */
3050     0,                                          /* tp_itemsize */
3051     0,                                          /* tp_dealloc */
3052     0,                                          /* tp_print */
3053     0,                                          /* tp_getattr */
3054     0,                                          /* tp_setattr */
3055     0,                                          /* tp_compare */
3056     0,                                          /* tp_repr */
3057     0,                                          /* tp_as_number */
3058     0,                                          /* tp_as_sequence */
3059     0,                                          /* tp_as_mapping */
3060     0,                                          /* tp_hash */
3061     0,                                          /* tp_call */
3062     0,                                          /* tp_str */
3063     PyObject_GenericGetAttr,                    /* tp_getattro */
3064     0,                                          /* tp_setattro */
3065     0,                                          /* tp_as_buffer */
3066     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3067     Py_TPFLAGS_BASETYPE,                        /* tp_flags */
3068     tzinfo_doc,                                 /* tp_doc */
3069     0,                                          /* tp_traverse */
3070     0,                                          /* tp_clear */
3071     0,                                          /* tp_richcompare */
3072     0,                                          /* tp_weaklistoffset */
3073     0,                                          /* tp_iter */
3074     0,                                          /* tp_iternext */
3075     tzinfo_methods,                             /* tp_methods */
3076     0,                                          /* tp_members */
3077     0,                                          /* tp_getset */
3078     0,                                          /* tp_base */
3079     0,                                          /* tp_dict */
3080     0,                                          /* tp_descr_get */
3081     0,                                          /* tp_descr_set */
3082     0,                                          /* tp_dictoffset */
3083     0,                                          /* tp_init */
3084     0,                                          /* tp_alloc */
3085     PyType_GenericNew,                          /* tp_new */
3086     0,                                          /* tp_free */
3087 };
3088 
3089 /*
3090  * PyDateTime_Time implementation.
3091  */
3092 
3093 /* Accessor properties.
3094  */
3095 
3096 static PyObject *
time_hour(PyDateTime_Time * self,void * unused)3097 time_hour(PyDateTime_Time *self, void *unused)
3098 {
3099     return PyInt_FromLong(TIME_GET_HOUR(self));
3100 }
3101 
3102 static PyObject *
time_minute(PyDateTime_Time * self,void * unused)3103 time_minute(PyDateTime_Time *self, void *unused)
3104 {
3105     return PyInt_FromLong(TIME_GET_MINUTE(self));
3106 }
3107 
3108 /* The name time_second conflicted with some platform header file. */
3109 static PyObject *
py_time_second(PyDateTime_Time * self,void * unused)3110 py_time_second(PyDateTime_Time *self, void *unused)
3111 {
3112     return PyInt_FromLong(TIME_GET_SECOND(self));
3113 }
3114 
3115 static PyObject *
time_microsecond(PyDateTime_Time * self,void * unused)3116 time_microsecond(PyDateTime_Time *self, void *unused)
3117 {
3118     return PyInt_FromLong(TIME_GET_MICROSECOND(self));
3119 }
3120 
3121 static PyObject *
time_tzinfo(PyDateTime_Time * self,void * unused)3122 time_tzinfo(PyDateTime_Time *self, void *unused)
3123 {
3124     PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3125     Py_INCREF(result);
3126     return result;
3127 }
3128 
3129 static PyGetSetDef time_getset[] = {
3130     {"hour",        (getter)time_hour},
3131     {"minute",      (getter)time_minute},
3132     {"second",      (getter)py_time_second},
3133     {"microsecond", (getter)time_microsecond},
3134     {"tzinfo",          (getter)time_tzinfo},
3135     {NULL}
3136 };
3137 
3138 /*
3139  * Constructors.
3140  */
3141 
3142 static char *time_kws[] = {"hour", "minute", "second", "microsecond",
3143                            "tzinfo", NULL};
3144 
3145 static PyObject *
time_new(PyTypeObject * type,PyObject * args,PyObject * kw)3146 time_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3147 {
3148     PyObject *self = NULL;
3149     PyObject *state;
3150     int hour = 0;
3151     int minute = 0;
3152     int second = 0;
3153     int usecond = 0;
3154     PyObject *tzinfo = Py_None;
3155 
3156     /* Check for invocation from pickle with __getstate__ state */
3157     if (PyTuple_GET_SIZE(args) >= 1 &&
3158         PyTuple_GET_SIZE(args) <= 2 &&
3159         PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3160         PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&
3161         ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)
3162     {
3163         PyDateTime_Time *me;
3164         char aware;
3165 
3166         if (PyTuple_GET_SIZE(args) == 2) {
3167             tzinfo = PyTuple_GET_ITEM(args, 1);
3168             if (check_tzinfo_subclass(tzinfo) < 0) {
3169                 PyErr_SetString(PyExc_TypeError, "bad "
3170                     "tzinfo state arg");
3171                 return NULL;
3172             }
3173         }
3174         aware = (char)(tzinfo != Py_None);
3175         me = (PyDateTime_Time *) (type->tp_alloc(type, aware));
3176         if (me != NULL) {
3177             char *pdata = PyString_AS_STRING(state);
3178 
3179             memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);
3180             me->hashcode = -1;
3181             me->hastzinfo = aware;
3182             if (aware) {
3183                 Py_INCREF(tzinfo);
3184                 me->tzinfo = tzinfo;
3185             }
3186         }
3187         return (PyObject *)me;
3188     }
3189 
3190     if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,
3191                                     &hour, &minute, &second, &usecond,
3192                                     &tzinfo)) {
3193         if (check_time_args(hour, minute, second, usecond) < 0)
3194             return NULL;
3195         if (check_tzinfo_subclass(tzinfo) < 0)
3196             return NULL;
3197         self = new_time_ex(hour, minute, second, usecond, tzinfo,
3198                            type);
3199     }
3200     return self;
3201 }
3202 
3203 /*
3204  * Destructor.
3205  */
3206 
3207 static void
time_dealloc(PyDateTime_Time * self)3208 time_dealloc(PyDateTime_Time *self)
3209 {
3210     if (HASTZINFO(self)) {
3211         Py_XDECREF(self->tzinfo);
3212     }
3213     Py_TYPE(self)->tp_free((PyObject *)self);
3214 }
3215 
3216 /*
3217  * Indirect access to tzinfo methods.
3218  */
3219 
3220 /* These are all METH_NOARGS, so don't need to check the arglist. */
3221 static PyObject *
time_utcoffset(PyDateTime_Time * self,PyObject * unused)3222 time_utcoffset(PyDateTime_Time *self, PyObject *unused) {
3223     return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3224                                "utcoffset", Py_None);
3225 }
3226 
3227 static PyObject *
time_dst(PyDateTime_Time * self,PyObject * unused)3228 time_dst(PyDateTime_Time *self, PyObject *unused) {
3229     return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
3230                                "dst", Py_None);
3231 }
3232 
3233 static PyObject *
time_tzname(PyDateTime_Time * self,PyObject * unused)3234 time_tzname(PyDateTime_Time *self, PyObject *unused) {
3235     return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
3236                        Py_None);
3237 }
3238 
3239 /*
3240  * Various ways to turn a time into a string.
3241  */
3242 
3243 static PyObject *
time_repr(PyDateTime_Time * self)3244 time_repr(PyDateTime_Time *self)
3245 {
3246     char buffer[100];
3247     const char *type_name = Py_TYPE(self)->tp_name;
3248     int h = TIME_GET_HOUR(self);
3249     int m = TIME_GET_MINUTE(self);
3250     int s = TIME_GET_SECOND(self);
3251     int us = TIME_GET_MICROSECOND(self);
3252     PyObject *result = NULL;
3253 
3254     if (us)
3255         PyOS_snprintf(buffer, sizeof(buffer),
3256                       "%s(%d, %d, %d, %d)", type_name, h, m, s, us);
3257     else if (s)
3258         PyOS_snprintf(buffer, sizeof(buffer),
3259                       "%s(%d, %d, %d)", type_name, h, m, s);
3260     else
3261         PyOS_snprintf(buffer, sizeof(buffer),
3262                       "%s(%d, %d)", type_name, h, m);
3263     result = PyString_FromString(buffer);
3264     if (result != NULL && HASTZINFO(self))
3265         result = append_keyword_tzinfo(result, self->tzinfo);
3266     return result;
3267 }
3268 
3269 static PyObject *
time_str(PyDateTime_Time * self)3270 time_str(PyDateTime_Time *self)
3271 {
3272     return PyObject_CallMethod((PyObject *)self, "isoformat", "()");
3273 }
3274 
3275 static PyObject *
time_isoformat(PyDateTime_Time * self,PyObject * unused)3276 time_isoformat(PyDateTime_Time *self, PyObject *unused)
3277 {
3278     char buf[100];
3279     PyObject *result;
3280     /* Reuse the time format code from the datetime type. */
3281     PyDateTime_DateTime datetime;
3282     PyDateTime_DateTime *pdatetime = &datetime;
3283 
3284     /* Copy over just the time bytes. */
3285     memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,
3286            self->data,
3287            _PyDateTime_TIME_DATASIZE);
3288 
3289     isoformat_time(pdatetime, buf, sizeof(buf));
3290     result = PyString_FromString(buf);
3291     if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)
3292         return result;
3293 
3294     /* We need to append the UTC offset. */
3295     if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,
3296                          Py_None) < 0) {
3297         Py_DECREF(result);
3298         return NULL;
3299     }
3300     PyString_ConcatAndDel(&result, PyString_FromString(buf));
3301     return result;
3302 }
3303 
3304 static PyObject *
time_strftime(PyDateTime_Time * self,PyObject * args,PyObject * kw)3305 time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3306 {
3307     PyObject *result;
3308     PyObject *tuple;
3309     const char *format;
3310     Py_ssize_t format_len;
3311     static char *keywords[] = {"format", NULL};
3312 
3313     if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,
3314                                       &format, &format_len))
3315         return NULL;
3316 
3317     /* Python's strftime does insane things with the year part of the
3318      * timetuple.  The year is forced to (the otherwise nonsensical)
3319      * 1900 to worm around that.
3320      */
3321     tuple = Py_BuildValue("iiiiiiiii",
3322                           1900, 1, 1, /* year, month, day */
3323                   TIME_GET_HOUR(self),
3324                   TIME_GET_MINUTE(self),
3325                   TIME_GET_SECOND(self),
3326                   0, 1, -1); /* weekday, daynum, dst */
3327     if (tuple == NULL)
3328         return NULL;
3329     assert(PyTuple_Size(tuple) == 9);
3330     result = wrap_strftime((PyObject *)self, format, format_len, tuple,
3331                            Py_None);
3332     Py_DECREF(tuple);
3333     return result;
3334 }
3335 
3336 /*
3337  * Miscellaneous methods.
3338  */
3339 
3340 /* This is more natural as a tp_compare, but doesn't work then:  for whatever
3341  * reason, Python's try_3way_compare ignores tp_compare unless
3342  * PyInstance_Check returns true, but these aren't old-style classes.
3343  */
3344 static PyObject *
time_richcompare(PyDateTime_Time * self,PyObject * other,int op)3345 time_richcompare(PyDateTime_Time *self, PyObject *other, int op)
3346 {
3347     int diff;
3348     naivety n1, n2;
3349     int offset1, offset2;
3350 
3351     if (! PyTime_Check(other)) {
3352         if (op == Py_EQ || op == Py_NE) {
3353             PyObject *result = op == Py_EQ ? Py_False : Py_True;
3354             Py_INCREF(result);
3355             return result;
3356         }
3357         /* Stop this from falling back to address comparison. */
3358         return cmperror((PyObject *)self, other);
3359     }
3360     if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None,
3361                                  other, &offset2, &n2, Py_None) < 0)
3362         return NULL;
3363     assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
3364     /* If they're both naive, or both aware and have the same offsets,
3365      * we get off cheap.  Note that if they're both naive, offset1 ==
3366      * offset2 == 0 at this point.
3367      */
3368     if (n1 == n2 && offset1 == offset2) {
3369         diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,
3370                       _PyDateTime_TIME_DATASIZE);
3371         return diff_to_bool(diff, op);
3372     }
3373 
3374     if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
3375         assert(offset1 != offset2);             /* else last "if" handled it */
3376         /* Convert everything except microseconds to seconds.  These
3377          * can't overflow (no more than the # of seconds in 2 days).
3378          */
3379         offset1 = TIME_GET_HOUR(self) * 3600 +
3380                   (TIME_GET_MINUTE(self) - offset1) * 60 +
3381                   TIME_GET_SECOND(self);
3382         offset2 = TIME_GET_HOUR(other) * 3600 +
3383                   (TIME_GET_MINUTE(other) - offset2) * 60 +
3384                   TIME_GET_SECOND(other);
3385         diff = offset1 - offset2;
3386         if (diff == 0)
3387             diff = TIME_GET_MICROSECOND(self) -
3388                    TIME_GET_MICROSECOND(other);
3389         return diff_to_bool(diff, op);
3390     }
3391 
3392     assert(n1 != n2);
3393     PyErr_SetString(PyExc_TypeError,
3394                     "can't compare offset-naive and "
3395                     "offset-aware times");
3396     return NULL;
3397 }
3398 
3399 static long
time_hash(PyDateTime_Time * self)3400 time_hash(PyDateTime_Time *self)
3401 {
3402     if (self->hashcode == -1) {
3403         naivety n;
3404         int offset;
3405         PyObject *temp;
3406 
3407         n = classify_utcoffset((PyObject *)self, Py_None, &offset);
3408         assert(n != OFFSET_UNKNOWN);
3409         if (n == OFFSET_ERROR)
3410             return -1;
3411 
3412         /* Reduce this to a hash of another object. */
3413         if (offset == 0)
3414             temp = PyString_FromStringAndSize((char *)self->data,
3415                                     _PyDateTime_TIME_DATASIZE);
3416         else {
3417             int hour;
3418             int minute;
3419 
3420             assert(n == OFFSET_AWARE);
3421             assert(HASTZINFO(self));
3422             hour = divmod(TIME_GET_HOUR(self) * 60 +
3423                             TIME_GET_MINUTE(self) - offset,
3424                           60,
3425                           &minute);
3426             if (0 <= hour && hour < 24)
3427                 temp = new_time(hour, minute,
3428                                 TIME_GET_SECOND(self),
3429                                 TIME_GET_MICROSECOND(self),
3430                                 Py_None);
3431             else
3432                 temp = Py_BuildValue("iiii",
3433                            hour, minute,
3434                            TIME_GET_SECOND(self),
3435                            TIME_GET_MICROSECOND(self));
3436         }
3437         if (temp != NULL) {
3438             self->hashcode = PyObject_Hash(temp);
3439             Py_DECREF(temp);
3440         }
3441     }
3442     return self->hashcode;
3443 }
3444 
3445 static PyObject *
time_replace(PyDateTime_Time * self,PyObject * args,PyObject * kw)3446 time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)
3447 {
3448     PyObject *clone;
3449     PyObject *tuple;
3450     int hh = TIME_GET_HOUR(self);
3451     int mm = TIME_GET_MINUTE(self);
3452     int ss = TIME_GET_SECOND(self);
3453     int us = TIME_GET_MICROSECOND(self);
3454     PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
3455 
3456     if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",
3457                                       time_kws,
3458                                       &hh, &mm, &ss, &us, &tzinfo))
3459         return NULL;
3460     tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);
3461     if (tuple == NULL)
3462         return NULL;
3463     clone = time_new(Py_TYPE(self), tuple, NULL);
3464     Py_DECREF(tuple);
3465     return clone;
3466 }
3467 
3468 static int
time_nonzero(PyDateTime_Time * self)3469 time_nonzero(PyDateTime_Time *self)
3470 {
3471     int offset;
3472     int none;
3473 
3474     if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {
3475         /* Since utcoffset is in whole minutes, nothing can
3476          * alter the conclusion that this is nonzero.
3477          */
3478         return 1;
3479     }
3480     offset = 0;
3481     if (HASTZINFO(self) && self->tzinfo != Py_None) {
3482         offset = call_utcoffset(self->tzinfo, Py_None, &none);
3483         if (offset == -1 && PyErr_Occurred())
3484             return -1;
3485     }
3486     return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;
3487 }
3488 
3489 /* Pickle support, a simple use of __reduce__. */
3490 
3491 /* Let basestate be the non-tzinfo data string.
3492  * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
3493  * So it's a tuple in any (non-error) case.
3494  * __getstate__ isn't exposed.
3495  */
3496 static PyObject *
time_getstate(PyDateTime_Time * self)3497 time_getstate(PyDateTime_Time *self)
3498 {
3499     PyObject *basestate;
3500     PyObject *result = NULL;
3501 
3502     basestate =  PyString_FromStringAndSize((char *)self->data,
3503                                             _PyDateTime_TIME_DATASIZE);
3504     if (basestate != NULL) {
3505         if (! HASTZINFO(self) || self->tzinfo == Py_None)
3506             result = PyTuple_Pack(1, basestate);
3507         else
3508             result = PyTuple_Pack(2, basestate, self->tzinfo);
3509         Py_DECREF(basestate);
3510     }
3511     return result;
3512 }
3513 
3514 static PyObject *
time_reduce(PyDateTime_Time * self,PyObject * arg)3515 time_reduce(PyDateTime_Time *self, PyObject *arg)
3516 {
3517     return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));
3518 }
3519 
3520 static PyMethodDef time_methods[] = {
3521 
3522     {"isoformat",   (PyCFunction)time_isoformat,        METH_NOARGS,
3523      PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"
3524                "[+HH:MM].")},
3525 
3526     {"strftime",        (PyCFunction)time_strftime,     METH_VARARGS | METH_KEYWORDS,
3527      PyDoc_STR("format -> strftime() style string.")},
3528 
3529     {"__format__",      (PyCFunction)date_format,       METH_VARARGS,
3530      PyDoc_STR("Formats self with strftime.")},
3531 
3532     {"utcoffset",       (PyCFunction)time_utcoffset,    METH_NOARGS,
3533      PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
3534 
3535     {"tzname",          (PyCFunction)time_tzname,       METH_NOARGS,
3536      PyDoc_STR("Return self.tzinfo.tzname(self).")},
3537 
3538     {"dst",             (PyCFunction)time_dst,          METH_NOARGS,
3539      PyDoc_STR("Return self.tzinfo.dst(self).")},
3540 
3541     {"replace",     (PyCFunction)time_replace,          METH_VARARGS | METH_KEYWORDS,
3542      PyDoc_STR("Return time with new specified fields.")},
3543 
3544     {"__reduce__", (PyCFunction)time_reduce,        METH_NOARGS,
3545      PyDoc_STR("__reduce__() -> (cls, state)")},
3546 
3547     {NULL,      NULL}
3548 };
3549 
3550 static char time_doc[] =
3551 PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\
3552 \n\
3553 All arguments are optional. tzinfo may be None, or an instance of\n\
3554 a tzinfo subclass. The remaining arguments may be ints or longs.\n");
3555 
3556 static PyNumberMethods time_as_number = {
3557     0,                                          /* nb_add */
3558     0,                                          /* nb_subtract */
3559     0,                                          /* nb_multiply */
3560     0,                                          /* nb_divide */
3561     0,                                          /* nb_remainder */
3562     0,                                          /* nb_divmod */
3563     0,                                          /* nb_power */
3564     0,                                          /* nb_negative */
3565     0,                                          /* nb_positive */
3566     0,                                          /* nb_absolute */
3567     (inquiry)time_nonzero,                      /* nb_nonzero */
3568 };
3569 
3570 statichere PyTypeObject PyDateTime_TimeType = {
3571     PyVarObject_HEAD_INIT(NULL, 0)
3572     "datetime.time",                            /* tp_name */
3573     sizeof(PyDateTime_Time),                    /* tp_basicsize */
3574     0,                                          /* tp_itemsize */
3575     (destructor)time_dealloc,                   /* tp_dealloc */
3576     0,                                          /* tp_print */
3577     0,                                          /* tp_getattr */
3578     0,                                          /* tp_setattr */
3579     0,                                          /* tp_compare */
3580     (reprfunc)time_repr,                        /* tp_repr */
3581     &time_as_number,                            /* tp_as_number */
3582     0,                                          /* tp_as_sequence */
3583     0,                                          /* tp_as_mapping */
3584     (hashfunc)time_hash,                        /* tp_hash */
3585     0,                                          /* tp_call */
3586     (reprfunc)time_str,                         /* tp_str */
3587     PyObject_GenericGetAttr,                    /* tp_getattro */
3588     0,                                          /* tp_setattro */
3589     0,                                          /* tp_as_buffer */
3590     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
3591     Py_TPFLAGS_BASETYPE,                        /* tp_flags */
3592     time_doc,                                   /* tp_doc */
3593     0,                                          /* tp_traverse */
3594     0,                                          /* tp_clear */
3595     (richcmpfunc)time_richcompare,              /* tp_richcompare */
3596     0,                                          /* tp_weaklistoffset */
3597     0,                                          /* tp_iter */
3598     0,                                          /* tp_iternext */
3599     time_methods,                               /* tp_methods */
3600     0,                                          /* tp_members */
3601     time_getset,                                /* tp_getset */
3602     0,                                          /* tp_base */
3603     0,                                          /* tp_dict */
3604     0,                                          /* tp_descr_get */
3605     0,                                          /* tp_descr_set */
3606     0,                                          /* tp_dictoffset */
3607     0,                                          /* tp_init */
3608     time_alloc,                                 /* tp_alloc */
3609     time_new,                                   /* tp_new */
3610     0,                                          /* tp_free */
3611 };
3612 
3613 /*
3614  * PyDateTime_DateTime implementation.
3615  */
3616 
3617 /* Accessor properties.  Properties for day, month, and year are inherited
3618  * from date.
3619  */
3620 
3621 static PyObject *
datetime_hour(PyDateTime_DateTime * self,void * unused)3622 datetime_hour(PyDateTime_DateTime *self, void *unused)
3623 {
3624     return PyInt_FromLong(DATE_GET_HOUR(self));
3625 }
3626 
3627 static PyObject *
datetime_minute(PyDateTime_DateTime * self,void * unused)3628 datetime_minute(PyDateTime_DateTime *self, void *unused)
3629 {
3630     return PyInt_FromLong(DATE_GET_MINUTE(self));
3631 }
3632 
3633 static PyObject *
datetime_second(PyDateTime_DateTime * self,void * unused)3634 datetime_second(PyDateTime_DateTime *self, void *unused)
3635 {
3636     return PyInt_FromLong(DATE_GET_SECOND(self));
3637 }
3638 
3639 static PyObject *
datetime_microsecond(PyDateTime_DateTime * self,void * unused)3640 datetime_microsecond(PyDateTime_DateTime *self, void *unused)
3641 {
3642     return PyInt_FromLong(DATE_GET_MICROSECOND(self));
3643 }
3644 
3645 static PyObject *
datetime_tzinfo(PyDateTime_DateTime * self,void * unused)3646 datetime_tzinfo(PyDateTime_DateTime *self, void *unused)
3647 {
3648     PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;
3649     Py_INCREF(result);
3650     return result;
3651 }
3652 
3653 static PyGetSetDef datetime_getset[] = {
3654     {"hour",        (getter)datetime_hour},
3655     {"minute",      (getter)datetime_minute},
3656     {"second",      (getter)datetime_second},
3657     {"microsecond", (getter)datetime_microsecond},
3658     {"tzinfo",          (getter)datetime_tzinfo},
3659     {NULL}
3660 };
3661 
3662 /*
3663  * Constructors.
3664  */
3665 
3666 static char *datetime_kws[] = {
3667     "year", "month", "day", "hour", "minute", "second",
3668     "microsecond", "tzinfo", NULL
3669 };
3670 
3671 static PyObject *
datetime_new(PyTypeObject * type,PyObject * args,PyObject * kw)3672 datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)
3673 {
3674     PyObject *self = NULL;
3675     PyObject *state;
3676     int year;
3677     int month;
3678     int day;
3679     int hour = 0;
3680     int minute = 0;
3681     int second = 0;
3682     int usecond = 0;
3683     PyObject *tzinfo = Py_None;
3684 
3685     /* Check for invocation from pickle with __getstate__ state */
3686     if (PyTuple_GET_SIZE(args) >= 1 &&
3687         PyTuple_GET_SIZE(args) <= 2 &&
3688         PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&
3689         PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&
3690         MONTH_IS_SANE(PyString_AS_STRING(state)[2]))
3691     {
3692         PyDateTime_DateTime *me;
3693         char aware;
3694 
3695         if (PyTuple_GET_SIZE(args) == 2) {
3696             tzinfo = PyTuple_GET_ITEM(args, 1);
3697             if (check_tzinfo_subclass(tzinfo) < 0) {
3698                 PyErr_SetString(PyExc_TypeError, "bad "
3699                     "tzinfo state arg");
3700                 return NULL;
3701             }
3702         }
3703         aware = (char)(tzinfo != Py_None);
3704         me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));
3705         if (me != NULL) {
3706             char *pdata = PyString_AS_STRING(state);
3707 
3708             memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);
3709             me->hashcode = -1;
3710             me->hastzinfo = aware;
3711             if (aware) {
3712                 Py_INCREF(tzinfo);
3713                 me->tzinfo = tzinfo;
3714             }
3715         }
3716         return (PyObject *)me;
3717     }
3718 
3719     if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,
3720                                     &year, &month, &day, &hour, &minute,
3721                                     &second, &usecond, &tzinfo)) {
3722         if (check_date_args(year, month, day) < 0)
3723             return NULL;
3724         if (check_time_args(hour, minute, second, usecond) < 0)
3725             return NULL;
3726         if (check_tzinfo_subclass(tzinfo) < 0)
3727             return NULL;
3728         self = new_datetime_ex(year, month, day,
3729                                 hour, minute, second, usecond,
3730                                 tzinfo, type);
3731     }
3732     return self;
3733 }
3734 
3735 /* TM_FUNC is the shared type of localtime() and gmtime(). */
3736 typedef struct tm *(*TM_FUNC)(const time_t *timer);
3737 
3738 /* Internal helper.
3739  * Build datetime from a time_t and a distinct count of microseconds.
3740  * Pass localtime or gmtime for f, to control the interpretation of timet.
3741  */
3742 static PyObject *
datetime_from_timet_and_us(PyObject * cls,TM_FUNC f,time_t timet,int us,PyObject * tzinfo)3743 datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,
3744                            PyObject *tzinfo)
3745 {
3746     struct tm *tm;
3747     PyObject *result = NULL;
3748 
3749     tm = f(&timet);
3750     if (tm) {
3751         /* The platform localtime/gmtime may insert leap seconds,
3752          * indicated by tm->tm_sec > 59.  We don't care about them,
3753          * except to the extent that passing them on to the datetime
3754          * constructor would raise ValueError for a reason that
3755          * made no sense to the user.
3756          */
3757         if (tm->tm_sec > 59)
3758             tm->tm_sec = 59;
3759         result = PyObject_CallFunction(cls, "iiiiiiiO",
3760                                        tm->tm_year + 1900,
3761                                        tm->tm_mon + 1,
3762                                        tm->tm_mday,
3763                                        tm->tm_hour,
3764                                        tm->tm_min,
3765                                        tm->tm_sec,
3766                                        us,
3767                                        tzinfo);
3768     }
3769     else
3770         PyErr_SetString(PyExc_ValueError,
3771                         "timestamp out of range for "
3772                         "platform localtime()/gmtime() function");
3773     return result;
3774 }
3775 
3776 /* Internal helper.
3777  * Build datetime from a Python timestamp.  Pass localtime or gmtime for f,
3778  * to control the interpretation of the timestamp.  Since a double doesn't
3779  * have enough bits to cover a datetime's full range of precision, it's
3780  * better to call datetime_from_timet_and_us provided you have a way
3781  * to get that much precision (e.g., C time() isn't good enough).
3782  */
3783 static PyObject *
datetime_from_timestamp(PyObject * cls,TM_FUNC f,double timestamp,PyObject * tzinfo)3784 datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,
3785                         PyObject *tzinfo)
3786 {
3787     time_t timet;
3788     double fraction;
3789     int us;
3790 
3791     timet = _PyTime_DoubleToTimet(timestamp);
3792     if (timet == (time_t)-1 && PyErr_Occurred())
3793         return NULL;
3794     fraction = timestamp - (double)timet;
3795     us = (int)round_to_long(fraction * 1e6);
3796     if (us < 0) {
3797         /* Truncation towards zero is not what we wanted
3798            for negative numbers (Python's mod semantics) */
3799         timet -= 1;
3800         us += 1000000;
3801     }
3802     /* If timestamp is less than one microsecond smaller than a
3803      * full second, round up. Otherwise, ValueErrors are raised
3804      * for some floats. */
3805     if (us == 1000000) {
3806         timet += 1;
3807         us = 0;
3808     }
3809     return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);
3810 }
3811 
3812 /* Internal helper.
3813  * Build most accurate possible datetime for current time.  Pass localtime or
3814  * gmtime for f as appropriate.
3815  */
3816 static PyObject *
datetime_best_possible(PyObject * cls,TM_FUNC f,PyObject * tzinfo)3817 datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)
3818 {
3819 #ifdef HAVE_GETTIMEOFDAY
3820     struct timeval t;
3821 
3822 #ifdef GETTIMEOFDAY_NO_TZ
3823     gettimeofday(&t);
3824 #else
3825     gettimeofday(&t, (struct timezone *)NULL);
3826 #endif
3827     return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,
3828                                       tzinfo);
3829 
3830 #else   /* ! HAVE_GETTIMEOFDAY */
3831     /* No flavor of gettimeofday exists on this platform.  Python's
3832      * time.time() does a lot of other platform tricks to get the
3833      * best time it can on the platform, and we're not going to do
3834      * better than that (if we could, the better code would belong
3835      * in time.time()!)  We're limited by the precision of a double,
3836      * though.
3837      */
3838     PyObject *time;
3839     double dtime;
3840 
3841     time = time_time();
3842     if (time == NULL)
3843         return NULL;
3844     dtime = PyFloat_AsDouble(time);
3845     Py_DECREF(time);
3846     if (dtime == -1.0 && PyErr_Occurred())
3847         return NULL;
3848     return datetime_from_timestamp(cls, f, dtime, tzinfo);
3849 #endif  /* ! HAVE_GETTIMEOFDAY */
3850 }
3851 
3852 /* Return best possible local time -- this isn't constrained by the
3853  * precision of a timestamp.
3854  */
3855 static PyObject *
datetime_now(PyObject * cls,PyObject * args,PyObject * kw)3856 datetime_now(PyObject *cls, PyObject *args, PyObject *kw)
3857 {
3858     PyObject *self;
3859     PyObject *tzinfo = Py_None;
3860     static char *keywords[] = {"tz", NULL};
3861 
3862     if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,
3863                                       &tzinfo))
3864         return NULL;
3865     if (check_tzinfo_subclass(tzinfo) < 0)
3866         return NULL;
3867 
3868     self = datetime_best_possible(cls,
3869                                   tzinfo == Py_None ? localtime : gmtime,
3870                                   tzinfo);
3871     if (self != NULL && tzinfo != Py_None) {
3872         /* Convert UTC to tzinfo's zone. */
3873         PyObject *temp = self;
3874         self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3875         Py_DECREF(temp);
3876     }
3877     return self;
3878 }
3879 
3880 /* Return best possible UTC time -- this isn't constrained by the
3881  * precision of a timestamp.
3882  */
3883 static PyObject *
datetime_utcnow(PyObject * cls,PyObject * dummy)3884 datetime_utcnow(PyObject *cls, PyObject *dummy)
3885 {
3886     return datetime_best_possible(cls, gmtime, Py_None);
3887 }
3888 
3889 /* Return new local datetime from timestamp (Python timestamp -- a double). */
3890 static PyObject *
datetime_fromtimestamp(PyObject * cls,PyObject * args,PyObject * kw)3891 datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)
3892 {
3893     PyObject *self;
3894     double timestamp;
3895     PyObject *tzinfo = Py_None;
3896     static char *keywords[] = {"timestamp", "tz", NULL};
3897 
3898     if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",
3899                                       keywords, &timestamp, &tzinfo))
3900         return NULL;
3901     if (check_tzinfo_subclass(tzinfo) < 0)
3902         return NULL;
3903 
3904     self = datetime_from_timestamp(cls,
3905                                    tzinfo == Py_None ? localtime : gmtime,
3906                                    timestamp,
3907                                    tzinfo);
3908     if (self != NULL && tzinfo != Py_None) {
3909         /* Convert UTC to tzinfo's zone. */
3910         PyObject *temp = self;
3911         self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);
3912         Py_DECREF(temp);
3913     }
3914     return self;
3915 }
3916 
3917 /* Return new UTC datetime from timestamp (Python timestamp -- a double). */
3918 static PyObject *
datetime_utcfromtimestamp(PyObject * cls,PyObject * args)3919 datetime_utcfromtimestamp(PyObject *cls, PyObject *args)
3920 {
3921     double timestamp;
3922     PyObject *result = NULL;
3923 
3924     if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))
3925         result = datetime_from_timestamp(cls, gmtime, timestamp,
3926                                          Py_None);
3927     return result;
3928 }
3929 
3930 /* Return new datetime from time.strptime(). */
3931 static PyObject *
datetime_strptime(PyObject * cls,PyObject * args)3932 datetime_strptime(PyObject *cls, PyObject *args)
3933 {
3934     static PyObject *module = NULL;
3935     PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;
3936     const char *string, *format;
3937 
3938     if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))
3939         return NULL;
3940 
3941     if (module == NULL &&
3942         (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)
3943         return NULL;
3944 
3945     /* _strptime._strptime returns a two-element tuple.  The first
3946        element is a time.struct_time object.  The second is the
3947        microseconds (which are not defined for time.struct_time). */
3948     obj = PyObject_CallMethod(module, "_strptime", "ss", string, format);
3949     if (obj != NULL) {
3950         int i, good_timetuple = 1;
3951         long int ia[7];
3952         if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {
3953             st = PySequence_GetItem(obj, 0);
3954             frac = PySequence_GetItem(obj, 1);
3955             if (st == NULL || frac == NULL)
3956                 good_timetuple = 0;
3957             /* copy y/m/d/h/m/s values out of the
3958                time.struct_time */
3959             if (good_timetuple &&
3960                 PySequence_Check(st) &&
3961                 PySequence_Size(st) >= 6) {
3962                 for (i=0; i < 6; i++) {
3963                     PyObject *p = PySequence_GetItem(st, i);
3964                     if (p == NULL) {
3965                         good_timetuple = 0;
3966                         break;
3967                     }
3968                     if (PyInt_Check(p))
3969                         ia[i] = PyInt_AsLong(p);
3970                     else
3971                         good_timetuple = 0;
3972                     Py_DECREF(p);
3973                 }
3974             }
3975             else
3976                 good_timetuple = 0;
3977             /* follow that up with a little dose of microseconds */
3978             if (good_timetuple && PyInt_Check(frac))
3979                 ia[6] = PyInt_AsLong(frac);
3980             else
3981                 good_timetuple = 0;
3982         }
3983         else
3984             good_timetuple = 0;
3985         if (good_timetuple)
3986             result = PyObject_CallFunction(cls, "iiiiiii",
3987                                            ia[0], ia[1], ia[2],
3988                                            ia[3], ia[4], ia[5],
3989                                            ia[6]);
3990         else
3991             PyErr_SetString(PyExc_ValueError,
3992                 "unexpected value from _strptime._strptime");
3993     }
3994     Py_XDECREF(obj);
3995     Py_XDECREF(st);
3996     Py_XDECREF(frac);
3997     return result;
3998 }
3999 
4000 /* Return new datetime from date/datetime and time arguments. */
4001 static PyObject *
datetime_combine(PyObject * cls,PyObject * args,PyObject * kw)4002 datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)
4003 {
4004     static char *keywords[] = {"date", "time", NULL};
4005     PyObject *date;
4006     PyObject *time;
4007     PyObject *result = NULL;
4008 
4009     if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,
4010                                     &PyDateTime_DateType, &date,
4011                                     &PyDateTime_TimeType, &time)) {
4012         PyObject *tzinfo = Py_None;
4013 
4014         if (HASTZINFO(time))
4015             tzinfo = ((PyDateTime_Time *)time)->tzinfo;
4016         result = PyObject_CallFunction(cls, "iiiiiiiO",
4017                                         GET_YEAR(date),
4018                                         GET_MONTH(date),
4019                                         GET_DAY(date),
4020                                         TIME_GET_HOUR(time),
4021                                         TIME_GET_MINUTE(time),
4022                                         TIME_GET_SECOND(time),
4023                                         TIME_GET_MICROSECOND(time),
4024                                         tzinfo);
4025     }
4026     return result;
4027 }
4028 
4029 /*
4030  * Destructor.
4031  */
4032 
4033 static void
datetime_dealloc(PyDateTime_DateTime * self)4034 datetime_dealloc(PyDateTime_DateTime *self)
4035 {
4036     if (HASTZINFO(self)) {
4037         Py_XDECREF(self->tzinfo);
4038     }
4039     Py_TYPE(self)->tp_free((PyObject *)self);
4040 }
4041 
4042 /*
4043  * Indirect access to tzinfo methods.
4044  */
4045 
4046 /* These are all METH_NOARGS, so don't need to check the arglist. */
4047 static PyObject *
datetime_utcoffset(PyDateTime_DateTime * self,PyObject * unused)4048 datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {
4049     return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4050                                "utcoffset", (PyObject *)self);
4051 }
4052 
4053 static PyObject *
datetime_dst(PyDateTime_DateTime * self,PyObject * unused)4054 datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {
4055     return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,
4056                                "dst", (PyObject *)self);
4057 }
4058 
4059 static PyObject *
datetime_tzname(PyDateTime_DateTime * self,PyObject * unused)4060 datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {
4061     return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,
4062                        (PyObject *)self);
4063 }
4064 
4065 /*
4066  * datetime arithmetic.
4067  */
4068 
4069 /* factor must be 1 (to add) or -1 (to subtract).  The result inherits
4070  * the tzinfo state of date.
4071  */
4072 static PyObject *
add_datetime_timedelta(PyDateTime_DateTime * date,PyDateTime_Delta * delta,int factor)4073 add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,
4074                        int factor)
4075 {
4076     /* Note that the C-level additions can't overflow, because of
4077      * invariant bounds on the member values.
4078      */
4079     int year = GET_YEAR(date);
4080     int month = GET_MONTH(date);
4081     int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;
4082     int hour = DATE_GET_HOUR(date);
4083     int minute = DATE_GET_MINUTE(date);
4084     int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;
4085     int microsecond = DATE_GET_MICROSECOND(date) +
4086                       GET_TD_MICROSECONDS(delta) * factor;
4087 
4088     assert(factor == 1 || factor == -1);
4089     if (normalize_datetime(&year, &month, &day,
4090                            &hour, &minute, &second, &microsecond) < 0)
4091         return NULL;
4092     else
4093         return new_datetime(year, month, day,
4094                             hour, minute, second, microsecond,
4095                             HASTZINFO(date) ? date->tzinfo : Py_None);
4096 }
4097 
4098 static PyObject *
datetime_add(PyObject * left,PyObject * right)4099 datetime_add(PyObject *left, PyObject *right)
4100 {
4101     if (PyDateTime_Check(left)) {
4102         /* datetime + ??? */
4103         if (PyDelta_Check(right))
4104             /* datetime + delta */
4105             return add_datetime_timedelta(
4106                             (PyDateTime_DateTime *)left,
4107                             (PyDateTime_Delta *)right,
4108                             1);
4109     }
4110     else if (PyDelta_Check(left)) {
4111         /* delta + datetime */
4112         return add_datetime_timedelta((PyDateTime_DateTime *) right,
4113                                       (PyDateTime_Delta *) left,
4114                                       1);
4115     }
4116     Py_INCREF(Py_NotImplemented);
4117     return Py_NotImplemented;
4118 }
4119 
4120 static PyObject *
datetime_subtract(PyObject * left,PyObject * right)4121 datetime_subtract(PyObject *left, PyObject *right)
4122 {
4123     PyObject *result = Py_NotImplemented;
4124 
4125     if (PyDateTime_Check(left)) {
4126         /* datetime - ??? */
4127         if (PyDateTime_Check(right)) {
4128             /* datetime - datetime */
4129             naivety n1, n2;
4130             int offset1, offset2;
4131             int delta_d, delta_s, delta_us;
4132 
4133             if (classify_two_utcoffsets(left, &offset1, &n1, left,
4134                                         right, &offset2, &n2,
4135                                         right) < 0)
4136                 return NULL;
4137             assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4138             if (n1 != n2) {
4139                 PyErr_SetString(PyExc_TypeError,
4140                     "can't subtract offset-naive and "
4141                     "offset-aware datetimes");
4142                 return NULL;
4143             }
4144             delta_d = ymd_to_ord(GET_YEAR(left),
4145                                  GET_MONTH(left),
4146                                  GET_DAY(left)) -
4147                       ymd_to_ord(GET_YEAR(right),
4148                                  GET_MONTH(right),
4149                                  GET_DAY(right));
4150             /* These can't overflow, since the values are
4151              * normalized.  At most this gives the number of
4152              * seconds in one day.
4153              */
4154             delta_s = (DATE_GET_HOUR(left) -
4155                        DATE_GET_HOUR(right)) * 3600 +
4156                       (DATE_GET_MINUTE(left) -
4157                        DATE_GET_MINUTE(right)) * 60 +
4158                       (DATE_GET_SECOND(left) -
4159                        DATE_GET_SECOND(right));
4160             delta_us = DATE_GET_MICROSECOND(left) -
4161                        DATE_GET_MICROSECOND(right);
4162             /* (left - offset1) - (right - offset2) =
4163              * (left - right) + (offset2 - offset1)
4164              */
4165             delta_s += (offset2 - offset1) * 60;
4166             result = new_delta(delta_d, delta_s, delta_us, 1);
4167         }
4168         else if (PyDelta_Check(right)) {
4169             /* datetime - delta */
4170             result = add_datetime_timedelta(
4171                             (PyDateTime_DateTime *)left,
4172                             (PyDateTime_Delta *)right,
4173                             -1);
4174         }
4175     }
4176 
4177     if (result == Py_NotImplemented)
4178         Py_INCREF(result);
4179     return result;
4180 }
4181 
4182 /* Various ways to turn a datetime into a string. */
4183 
4184 static PyObject *
datetime_repr(PyDateTime_DateTime * self)4185 datetime_repr(PyDateTime_DateTime *self)
4186 {
4187     char buffer[1000];
4188     const char *type_name = Py_TYPE(self)->tp_name;
4189     PyObject *baserepr;
4190 
4191     if (DATE_GET_MICROSECOND(self)) {
4192         PyOS_snprintf(buffer, sizeof(buffer),
4193                       "%s(%d, %d, %d, %d, %d, %d, %d)",
4194                       type_name,
4195                       GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4196                       DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4197                       DATE_GET_SECOND(self),
4198                       DATE_GET_MICROSECOND(self));
4199     }
4200     else if (DATE_GET_SECOND(self)) {
4201         PyOS_snprintf(buffer, sizeof(buffer),
4202                       "%s(%d, %d, %d, %d, %d, %d)",
4203                       type_name,
4204                       GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4205                       DATE_GET_HOUR(self), DATE_GET_MINUTE(self),
4206                       DATE_GET_SECOND(self));
4207     }
4208     else {
4209         PyOS_snprintf(buffer, sizeof(buffer),
4210                       "%s(%d, %d, %d, %d, %d)",
4211                       type_name,
4212                       GET_YEAR(self), GET_MONTH(self), GET_DAY(self),
4213                       DATE_GET_HOUR(self), DATE_GET_MINUTE(self));
4214     }
4215     baserepr = PyString_FromString(buffer);
4216     if (baserepr == NULL || ! HASTZINFO(self))
4217         return baserepr;
4218     return append_keyword_tzinfo(baserepr, self->tzinfo);
4219 }
4220 
4221 static PyObject *
datetime_str(PyDateTime_DateTime * self)4222 datetime_str(PyDateTime_DateTime *self)
4223 {
4224     return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");
4225 }
4226 
4227 static PyObject *
datetime_isoformat(PyDateTime_DateTime * self,PyObject * args,PyObject * kw)4228 datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
4229 {
4230     char sep = 'T';
4231     static char *keywords[] = {"sep", NULL};
4232     char buffer[100];
4233     char *cp;
4234     PyObject *result;
4235 
4236     if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,
4237                                      &sep))
4238         return NULL;
4239     cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));
4240     assert(cp != NULL);
4241     *cp++ = sep;
4242     cp = isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));
4243     result = PyString_FromStringAndSize(buffer, cp - buffer);
4244     if (result == NULL || ! HASTZINFO(self))
4245         return result;
4246 
4247     /* We need to append the UTC offset. */
4248     if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,
4249                          (PyObject *)self) < 0) {
4250         Py_DECREF(result);
4251         return NULL;
4252     }
4253     PyString_ConcatAndDel(&result, PyString_FromString(buffer));
4254     return result;
4255 }
4256 
4257 static PyObject *
datetime_ctime(PyDateTime_DateTime * self)4258 datetime_ctime(PyDateTime_DateTime *self)
4259 {
4260     return format_ctime((PyDateTime_Date *)self,
4261                         DATE_GET_HOUR(self),
4262                         DATE_GET_MINUTE(self),
4263                         DATE_GET_SECOND(self));
4264 }
4265 
4266 /* Miscellaneous methods. */
4267 
4268 /* This is more natural as a tp_compare, but doesn't work then:  for whatever
4269  * reason, Python's try_3way_compare ignores tp_compare unless
4270  * PyInstance_Check returns true, but these aren't old-style classes.
4271  */
4272 static PyObject *
datetime_richcompare(PyDateTime_DateTime * self,PyObject * other,int op)4273 datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)
4274 {
4275     int diff;
4276     naivety n1, n2;
4277     int offset1, offset2;
4278 
4279     if (! PyDateTime_Check(other)) {
4280         /* If other has a "timetuple" attr, that's an advertised
4281          * hook for other classes to ask to get comparison control.
4282          * However, date instances have a timetuple attr, and we
4283          * don't want to allow that comparison.  Because datetime
4284          * is a subclass of date, when mixing date and datetime
4285          * in a comparison, Python gives datetime the first shot
4286          * (it's the more specific subtype).  So we can stop that
4287          * combination here reliably.
4288          */
4289         if (PyObject_HasAttrString(other, "timetuple") &&
4290             ! PyDate_Check(other)) {
4291             /* A hook for other kinds of datetime objects. */
4292             Py_INCREF(Py_NotImplemented);
4293             return Py_NotImplemented;
4294         }
4295         if (op == Py_EQ || op == Py_NE) {
4296             PyObject *result = op == Py_EQ ? Py_False : Py_True;
4297             Py_INCREF(result);
4298             return result;
4299         }
4300         /* Stop this from falling back to address comparison. */
4301         return cmperror((PyObject *)self, other);
4302     }
4303 
4304     if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1,
4305                                 (PyObject *)self,
4306                                  other, &offset2, &n2,
4307                                  other) < 0)
4308         return NULL;
4309     assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);
4310     /* If they're both naive, or both aware and have the same offsets,
4311      * we get off cheap.  Note that if they're both naive, offset1 ==
4312      * offset2 == 0 at this point.
4313      */
4314     if (n1 == n2 && offset1 == offset2) {
4315         diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,
4316                       _PyDateTime_DATETIME_DATASIZE);
4317         return diff_to_bool(diff, op);
4318     }
4319 
4320     if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {
4321         PyDateTime_Delta *delta;
4322 
4323         assert(offset1 != offset2);             /* else last "if" handled it */
4324         delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,
4325                                                        other);
4326         if (delta == NULL)
4327             return NULL;
4328         diff = GET_TD_DAYS(delta);
4329         if (diff == 0)
4330             diff = GET_TD_SECONDS(delta) |
4331                    GET_TD_MICROSECONDS(delta);
4332         Py_DECREF(delta);
4333         return diff_to_bool(diff, op);
4334     }
4335 
4336     assert(n1 != n2);
4337     PyErr_SetString(PyExc_TypeError,
4338                     "can't compare offset-naive and "
4339                     "offset-aware datetimes");
4340     return NULL;
4341 }
4342 
4343 static long
datetime_hash(PyDateTime_DateTime * self)4344 datetime_hash(PyDateTime_DateTime *self)
4345 {
4346     if (self->hashcode == -1) {
4347         naivety n;
4348         int offset;
4349         PyObject *temp;
4350 
4351         n = classify_utcoffset((PyObject *)self, (PyObject *)self,
4352                                &offset);
4353         assert(n != OFFSET_UNKNOWN);
4354         if (n == OFFSET_ERROR)
4355             return -1;
4356 
4357         /* Reduce this to a hash of another object. */
4358         if (n == OFFSET_NAIVE)
4359             temp = PyString_FromStringAndSize(
4360                             (char *)self->data,
4361                             _PyDateTime_DATETIME_DATASIZE);
4362         else {
4363             int days;
4364             int seconds;
4365 
4366             assert(n == OFFSET_AWARE);
4367             assert(HASTZINFO(self));
4368             days = ymd_to_ord(GET_YEAR(self),
4369                               GET_MONTH(self),
4370                               GET_DAY(self));
4371             seconds = DATE_GET_HOUR(self) * 3600 +
4372                       (DATE_GET_MINUTE(self) - offset) * 60 +
4373                       DATE_GET_SECOND(self);
4374             temp = new_delta(days,
4375                              seconds,
4376                              DATE_GET_MICROSECOND(self),
4377                              1);
4378         }
4379         if (temp != NULL) {
4380             self->hashcode = PyObject_Hash(temp);
4381             Py_DECREF(temp);
4382         }
4383     }
4384     return self->hashcode;
4385 }
4386 
4387 static PyObject *
datetime_replace(PyDateTime_DateTime * self,PyObject * args,PyObject * kw)4388 datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
4389 {
4390     PyObject *clone;
4391     PyObject *tuple;
4392     int y = GET_YEAR(self);
4393     int m = GET_MONTH(self);
4394     int d = GET_DAY(self);
4395     int hh = DATE_GET_HOUR(self);
4396     int mm = DATE_GET_MINUTE(self);
4397     int ss = DATE_GET_SECOND(self);
4398     int us = DATE_GET_MICROSECOND(self);
4399     PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;
4400 
4401     if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",
4402                                       datetime_kws,
4403                                       &y, &m, &d, &hh, &mm, &ss, &us,
4404                                       &tzinfo))
4405         return NULL;
4406     tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);
4407     if (tuple == NULL)
4408         return NULL;
4409     clone = datetime_new(Py_TYPE(self), tuple, NULL);
4410     Py_DECREF(tuple);
4411     return clone;
4412 }
4413 
4414 static PyObject *
datetime_astimezone(PyDateTime_DateTime * self,PyObject * args,PyObject * kw)4415 datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)
4416 {
4417     int y, m, d, hh, mm, ss, us;
4418     PyObject *result;
4419     int offset, none;
4420 
4421     PyObject *tzinfo;
4422     static char *keywords[] = {"tz", NULL};
4423 
4424     if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,
4425                                       &PyDateTime_TZInfoType, &tzinfo))
4426         return NULL;
4427 
4428     if (!HASTZINFO(self) || self->tzinfo == Py_None)
4429         goto NeedAware;
4430 
4431     /* Conversion to self's own time zone is a NOP. */
4432     if (self->tzinfo == tzinfo) {
4433         Py_INCREF(self);
4434         return (PyObject *)self;
4435     }
4436 
4437     /* Convert self to UTC. */
4438     offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4439     if (offset == -1 && PyErr_Occurred())
4440         return NULL;
4441     if (none)
4442         goto NeedAware;
4443 
4444     y = GET_YEAR(self);
4445     m = GET_MONTH(self);
4446     d = GET_DAY(self);
4447     hh = DATE_GET_HOUR(self);
4448     mm = DATE_GET_MINUTE(self);
4449     ss = DATE_GET_SECOND(self);
4450     us = DATE_GET_MICROSECOND(self);
4451 
4452     mm -= offset;
4453     if ((mm < 0 || mm >= 60) &&
4454         normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)
4455         return NULL;
4456 
4457     /* Attach new tzinfo and let fromutc() do the rest. */
4458     result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);
4459     if (result != NULL) {
4460         PyObject *temp = result;
4461 
4462         result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);
4463         Py_DECREF(temp);
4464     }
4465     return result;
4466 
4467 NeedAware:
4468     PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "
4469                                       "a naive datetime");
4470     return NULL;
4471 }
4472 
4473 static PyObject *
datetime_timetuple(PyDateTime_DateTime * self)4474 datetime_timetuple(PyDateTime_DateTime *self)
4475 {
4476     int dstflag = -1;
4477 
4478     if (HASTZINFO(self) && self->tzinfo != Py_None) {
4479         int none;
4480 
4481         dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);
4482         if (dstflag == -1 && PyErr_Occurred())
4483             return NULL;
4484 
4485         if (none)
4486             dstflag = -1;
4487         else if (dstflag != 0)
4488             dstflag = 1;
4489 
4490     }
4491     return build_struct_time(GET_YEAR(self),
4492                              GET_MONTH(self),
4493                              GET_DAY(self),
4494                              DATE_GET_HOUR(self),
4495                              DATE_GET_MINUTE(self),
4496                              DATE_GET_SECOND(self),
4497                              dstflag);
4498 }
4499 
4500 static PyObject *
datetime_getdate(PyDateTime_DateTime * self)4501 datetime_getdate(PyDateTime_DateTime *self)
4502 {
4503     return new_date(GET_YEAR(self),
4504                     GET_MONTH(self),
4505                     GET_DAY(self));
4506 }
4507 
4508 static PyObject *
datetime_gettime(PyDateTime_DateTime * self)4509 datetime_gettime(PyDateTime_DateTime *self)
4510 {
4511     return new_time(DATE_GET_HOUR(self),
4512                     DATE_GET_MINUTE(self),
4513                     DATE_GET_SECOND(self),
4514                     DATE_GET_MICROSECOND(self),
4515                     Py_None);
4516 }
4517 
4518 static PyObject *
datetime_gettimetz(PyDateTime_DateTime * self)4519 datetime_gettimetz(PyDateTime_DateTime *self)
4520 {
4521     return new_time(DATE_GET_HOUR(self),
4522                     DATE_GET_MINUTE(self),
4523                     DATE_GET_SECOND(self),
4524                     DATE_GET_MICROSECOND(self),
4525                     HASTZINFO(self) ? self->tzinfo : Py_None);
4526 }
4527 
4528 static PyObject *
datetime_utctimetuple(PyDateTime_DateTime * self)4529 datetime_utctimetuple(PyDateTime_DateTime *self)
4530 {
4531     int y = GET_YEAR(self);
4532     int m = GET_MONTH(self);
4533     int d = GET_DAY(self);
4534     int hh = DATE_GET_HOUR(self);
4535     int mm = DATE_GET_MINUTE(self);
4536     int ss = DATE_GET_SECOND(self);
4537     int us = 0;         /* microseconds are ignored in a timetuple */
4538     int offset = 0;
4539 
4540     if (HASTZINFO(self) && self->tzinfo != Py_None) {
4541         int none;
4542 
4543         offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);
4544         if (offset == -1 && PyErr_Occurred())
4545             return NULL;
4546     }
4547     /* Even if offset is 0, don't call timetuple() -- tm_isdst should be
4548      * 0 in a UTC timetuple regardless of what dst() says.
4549      */
4550     if (offset) {
4551         /* Subtract offset minutes & normalize. */
4552         int stat;
4553 
4554         mm -= offset;
4555         stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);
4556         if (stat < 0) {
4557             /* At the edges, it's possible we overflowed
4558              * beyond MINYEAR or MAXYEAR.
4559              */
4560             if (PyErr_ExceptionMatches(PyExc_OverflowError))
4561                 PyErr_Clear();
4562             else
4563                 return NULL;
4564         }
4565     }
4566     return build_struct_time(y, m, d, hh, mm, ss, 0);
4567 }
4568 
4569 /* Pickle support, a simple use of __reduce__. */
4570 
4571 /* Let basestate be the non-tzinfo data string.
4572  * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).
4573  * So it's a tuple in any (non-error) case.
4574  * __getstate__ isn't exposed.
4575  */
4576 static PyObject *
datetime_getstate(PyDateTime_DateTime * self)4577 datetime_getstate(PyDateTime_DateTime *self)
4578 {
4579     PyObject *basestate;
4580     PyObject *result = NULL;
4581 
4582     basestate = PyString_FromStringAndSize((char *)self->data,
4583                                       _PyDateTime_DATETIME_DATASIZE);
4584     if (basestate != NULL) {
4585         if (! HASTZINFO(self) || self->tzinfo == Py_None)
4586             result = PyTuple_Pack(1, basestate);
4587         else
4588             result = PyTuple_Pack(2, basestate, self->tzinfo);
4589         Py_DECREF(basestate);
4590     }
4591     return result;
4592 }
4593 
4594 static PyObject *
datetime_reduce(PyDateTime_DateTime * self,PyObject * arg)4595 datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)
4596 {
4597     return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));
4598 }
4599 
4600 static PyMethodDef datetime_methods[] = {
4601 
4602     /* Class methods: */
4603 
4604     {"now",         (PyCFunction)datetime_now,
4605      METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4606      PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},
4607 
4608     {"utcnow",         (PyCFunction)datetime_utcnow,
4609      METH_NOARGS | METH_CLASS,
4610      PyDoc_STR("Return a new datetime representing UTC day and time.")},
4611 
4612     {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,
4613      METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4614      PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},
4615 
4616     {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,
4617      METH_VARARGS | METH_CLASS,
4618      PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "
4619                "(like time.time()).")},
4620 
4621     {"strptime", (PyCFunction)datetime_strptime,
4622      METH_VARARGS | METH_CLASS,
4623      PyDoc_STR("string, format -> new datetime parsed from a string "
4624                "(like time.strptime()).")},
4625 
4626     {"combine", (PyCFunction)datetime_combine,
4627      METH_VARARGS | METH_KEYWORDS | METH_CLASS,
4628      PyDoc_STR("date, time -> datetime with same date and time fields")},
4629 
4630     /* Instance methods: */
4631 
4632     {"date",   (PyCFunction)datetime_getdate, METH_NOARGS,
4633      PyDoc_STR("Return date object with same year, month and day.")},
4634 
4635     {"time",   (PyCFunction)datetime_gettime, METH_NOARGS,
4636      PyDoc_STR("Return time object with same time but with tzinfo=None.")},
4637 
4638     {"timetz",   (PyCFunction)datetime_gettimetz, METH_NOARGS,
4639      PyDoc_STR("Return time object with same time and tzinfo.")},
4640 
4641     {"ctime",       (PyCFunction)datetime_ctime,        METH_NOARGS,
4642      PyDoc_STR("Return ctime() style string.")},
4643 
4644     {"timetuple",   (PyCFunction)datetime_timetuple, METH_NOARGS,
4645      PyDoc_STR("Return time tuple, compatible with time.localtime().")},
4646 
4647     {"utctimetuple",   (PyCFunction)datetime_utctimetuple, METH_NOARGS,
4648      PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},
4649 
4650     {"isoformat",   (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,
4651      PyDoc_STR("[sep] -> string in ISO 8601 format, "
4652                "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"
4653                "sep is used to separate the year from the time, and "
4654                "defaults to 'T'.")},
4655 
4656     {"utcoffset",       (PyCFunction)datetime_utcoffset, METH_NOARGS,
4657      PyDoc_STR("Return self.tzinfo.utcoffset(self).")},
4658 
4659     {"tzname",          (PyCFunction)datetime_tzname,   METH_NOARGS,
4660      PyDoc_STR("Return self.tzinfo.tzname(self).")},
4661 
4662     {"dst",             (PyCFunction)datetime_dst, METH_NOARGS,
4663      PyDoc_STR("Return self.tzinfo.dst(self).")},
4664 
4665     {"replace",     (PyCFunction)datetime_replace,      METH_VARARGS | METH_KEYWORDS,
4666      PyDoc_STR("Return datetime with new specified fields.")},
4667 
4668     {"astimezone",  (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,
4669      PyDoc_STR("tz -> convert to local time in new timezone tz\n")},
4670 
4671     {"__reduce__", (PyCFunction)datetime_reduce,     METH_NOARGS,
4672      PyDoc_STR("__reduce__() -> (cls, state)")},
4673 
4674     {NULL,      NULL}
4675 };
4676 
4677 static char datetime_doc[] =
4678 PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\
4679 \n\
4680 The year, month and day arguments are required. tzinfo may be None, or an\n\
4681 instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");
4682 
4683 static PyNumberMethods datetime_as_number = {
4684     datetime_add,                               /* nb_add */
4685     datetime_subtract,                          /* nb_subtract */
4686     0,                                          /* nb_multiply */
4687     0,                                          /* nb_divide */
4688     0,                                          /* nb_remainder */
4689     0,                                          /* nb_divmod */
4690     0,                                          /* nb_power */
4691     0,                                          /* nb_negative */
4692     0,                                          /* nb_positive */
4693     0,                                          /* nb_absolute */
4694     0,                                          /* nb_nonzero */
4695 };
4696 
4697 statichere PyTypeObject PyDateTime_DateTimeType = {
4698     PyVarObject_HEAD_INIT(NULL, 0)
4699     "datetime.datetime",                        /* tp_name */
4700     sizeof(PyDateTime_DateTime),                /* tp_basicsize */
4701     0,                                          /* tp_itemsize */
4702     (destructor)datetime_dealloc,               /* tp_dealloc */
4703     0,                                          /* tp_print */
4704     0,                                          /* tp_getattr */
4705     0,                                          /* tp_setattr */
4706     0,                                          /* tp_compare */
4707     (reprfunc)datetime_repr,                    /* tp_repr */
4708     &datetime_as_number,                        /* tp_as_number */
4709     0,                                          /* tp_as_sequence */
4710     0,                                          /* tp_as_mapping */
4711     (hashfunc)datetime_hash,                    /* tp_hash */
4712     0,                                          /* tp_call */
4713     (reprfunc)datetime_str,                     /* tp_str */
4714     PyObject_GenericGetAttr,                    /* tp_getattro */
4715     0,                                          /* tp_setattro */
4716     0,                                          /* tp_as_buffer */
4717     Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |
4718     Py_TPFLAGS_BASETYPE,                        /* tp_flags */
4719     datetime_doc,                               /* tp_doc */
4720     0,                                          /* tp_traverse */
4721     0,                                          /* tp_clear */
4722     (richcmpfunc)datetime_richcompare,          /* tp_richcompare */
4723     0,                                          /* tp_weaklistoffset */
4724     0,                                          /* tp_iter */
4725     0,                                          /* tp_iternext */
4726     datetime_methods,                           /* tp_methods */
4727     0,                                          /* tp_members */
4728     datetime_getset,                            /* tp_getset */
4729     &PyDateTime_DateType,                       /* tp_base */
4730     0,                                          /* tp_dict */
4731     0,                                          /* tp_descr_get */
4732     0,                                          /* tp_descr_set */
4733     0,                                          /* tp_dictoffset */
4734     0,                                          /* tp_init */
4735     datetime_alloc,                             /* tp_alloc */
4736     datetime_new,                               /* tp_new */
4737     0,                                          /* tp_free */
4738 };
4739 
4740 /* ---------------------------------------------------------------------------
4741  * Module methods and initialization.
4742  */
4743 
4744 static PyMethodDef module_methods[] = {
4745     {NULL, NULL}
4746 };
4747 
4748 /* C API.  Clients get at this via PyDateTime_IMPORT, defined in
4749  * datetime.h.
4750  */
4751 static PyDateTime_CAPI CAPI = {
4752     &PyDateTime_DateType,
4753     &PyDateTime_DateTimeType,
4754     &PyDateTime_TimeType,
4755     &PyDateTime_DeltaType,
4756     &PyDateTime_TZInfoType,
4757     new_date_ex,
4758     new_datetime_ex,
4759     new_time_ex,
4760     new_delta_ex,
4761     datetime_fromtimestamp,
4762     date_fromtimestamp
4763 };
4764 
4765 
4766 PyMODINIT_FUNC
initdatetime(void)4767 initdatetime(void)
4768 {
4769     PyObject *m;        /* a module object */
4770     PyObject *d;        /* its dict */
4771     PyObject *x;
4772 
4773     m = Py_InitModule3("datetime", module_methods,
4774                        "Fast implementation of the datetime type.");
4775     if (m == NULL)
4776         return;
4777 
4778     if (PyType_Ready(&PyDateTime_DateType) < 0)
4779         return;
4780     if (PyType_Ready(&PyDateTime_DateTimeType) < 0)
4781         return;
4782     if (PyType_Ready(&PyDateTime_DeltaType) < 0)
4783         return;
4784     if (PyType_Ready(&PyDateTime_TimeType) < 0)
4785         return;
4786     if (PyType_Ready(&PyDateTime_TZInfoType) < 0)
4787         return;
4788 
4789     /* timedelta values */
4790     d = PyDateTime_DeltaType.tp_dict;
4791 
4792     x = new_delta(0, 0, 1, 0);
4793     if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4794         return;
4795     Py_DECREF(x);
4796 
4797     x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);
4798     if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4799         return;
4800     Py_DECREF(x);
4801 
4802     x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);
4803     if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4804         return;
4805     Py_DECREF(x);
4806 
4807     /* date values */
4808     d = PyDateTime_DateType.tp_dict;
4809 
4810     x = new_date(1, 1, 1);
4811     if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4812         return;
4813     Py_DECREF(x);
4814 
4815     x = new_date(MAXYEAR, 12, 31);
4816     if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4817         return;
4818     Py_DECREF(x);
4819 
4820     x = new_delta(1, 0, 0, 0);
4821     if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4822         return;
4823     Py_DECREF(x);
4824 
4825     /* time values */
4826     d = PyDateTime_TimeType.tp_dict;
4827 
4828     x = new_time(0, 0, 0, 0, Py_None);
4829     if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4830         return;
4831     Py_DECREF(x);
4832 
4833     x = new_time(23, 59, 59, 999999, Py_None);
4834     if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4835         return;
4836     Py_DECREF(x);
4837 
4838     x = new_delta(0, 0, 1, 0);
4839     if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4840         return;
4841     Py_DECREF(x);
4842 
4843     /* datetime values */
4844     d = PyDateTime_DateTimeType.tp_dict;
4845 
4846     x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);
4847     if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)
4848         return;
4849     Py_DECREF(x);
4850 
4851     x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);
4852     if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)
4853         return;
4854     Py_DECREF(x);
4855 
4856     x = new_delta(0, 0, 1, 0);
4857     if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)
4858         return;
4859     Py_DECREF(x);
4860 
4861     /* module initialization */
4862     PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);
4863     PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);
4864 
4865     Py_INCREF(&PyDateTime_DateType);
4866     PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);
4867 
4868     Py_INCREF(&PyDateTime_DateTimeType);
4869     PyModule_AddObject(m, "datetime",
4870                        (PyObject *)&PyDateTime_DateTimeType);
4871 
4872     Py_INCREF(&PyDateTime_TimeType);
4873     PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);
4874 
4875     Py_INCREF(&PyDateTime_DeltaType);
4876     PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);
4877 
4878     Py_INCREF(&PyDateTime_TZInfoType);
4879     PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);
4880 
4881     x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);
4882     if (x == NULL)
4883         return;
4884     PyModule_AddObject(m, "datetime_CAPI", x);
4885 
4886     /* A 4-year cycle has an extra leap day over what we'd get from
4887      * pasting together 4 single years.
4888      */
4889     assert(DI4Y == 4 * 365 + 1);
4890     assert(DI4Y == days_before_year(4+1));
4891 
4892     /* Similarly, a 400-year cycle has an extra leap day over what we'd
4893      * get from pasting together 4 100-year cycles.
4894      */
4895     assert(DI400Y == 4 * DI100Y + 1);
4896     assert(DI400Y == days_before_year(400+1));
4897 
4898     /* OTOH, a 100-year cycle has one fewer leap day than we'd get from
4899      * pasting together 25 4-year cycles.
4900      */
4901     assert(DI100Y == 25 * DI4Y - 1);
4902     assert(DI100Y == days_before_year(100+1));
4903 
4904     us_per_us = PyInt_FromLong(1);
4905     us_per_ms = PyInt_FromLong(1000);
4906     us_per_second = PyInt_FromLong(1000000);
4907     us_per_minute = PyInt_FromLong(60000000);
4908     seconds_per_day = PyInt_FromLong(24 * 3600);
4909     if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||
4910         us_per_minute == NULL || seconds_per_day == NULL)
4911         return;
4912 
4913     /* The rest are too big for 32-bit ints, but even
4914      * us_per_week fits in 40 bits, so doubles should be exact.
4915      */
4916     us_per_hour = PyLong_FromDouble(3600000000.0);
4917     us_per_day = PyLong_FromDouble(86400000000.0);
4918     us_per_week = PyLong_FromDouble(604800000000.0);
4919     if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)
4920         return;
4921 }
4922 
4923 /* ---------------------------------------------------------------------------
4924 Some time zone algebra.  For a datetime x, let
4925     x.n = x stripped of its timezone -- its naive time.
4926     x.o = x.utcoffset(), and assuming that doesn't raise an exception or
4927       return None
4928     x.d = x.dst(), and assuming that doesn't raise an exception or
4929       return None
4930     x.s = x's standard offset, x.o - x.d
4931 
4932 Now some derived rules, where k is a duration (timedelta).
4933 
4934 1. x.o = x.s + x.d
4935    This follows from the definition of x.s.
4936 
4937 2. If x and y have the same tzinfo member, x.s = y.s.
4938    This is actually a requirement, an assumption we need to make about
4939    sane tzinfo classes.
4940 
4941 3. The naive UTC time corresponding to x is x.n - x.o.
4942    This is again a requirement for a sane tzinfo class.
4943 
4944 4. (x+k).s = x.s
4945    This follows from #2, and that datimetimetz+timedelta preserves tzinfo.
4946 
4947 5. (x+k).n = x.n + k
4948    Again follows from how arithmetic is defined.
4949 
4950 Now we can explain tz.fromutc(x).  Let's assume it's an interesting case
4951 (meaning that the various tzinfo methods exist, and don't blow up or return
4952 None when called).
4953 
4954 The function wants to return a datetime y with timezone tz, equivalent to x.
4955 x is already in UTC.
4956 
4957 By #3, we want
4958 
4959     y.n - y.o = x.n                             [1]
4960 
4961 The algorithm starts by attaching tz to x.n, and calling that y.  So
4962 x.n = y.n at the start.  Then it wants to add a duration k to y, so that [1]
4963 becomes true; in effect, we want to solve [2] for k:
4964 
4965    (y+k).n - (y+k).o = x.n                      [2]
4966 
4967 By #1, this is the same as
4968 
4969    (y+k).n - ((y+k).s + (y+k).d) = x.n          [3]
4970 
4971 By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.
4972 Substituting that into [3],
4973 
4974    x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving
4975    k - (y+k).s - (y+k).d = 0; rearranging,
4976    k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so
4977    k = y.s - (y+k).d
4978 
4979 On the RHS, (y+k).d can't be computed directly, but y.s can be, and we
4980 approximate k by ignoring the (y+k).d term at first.  Note that k can't be
4981 very large, since all offset-returning methods return a duration of magnitude
4982 less than 24 hours.  For that reason, if y is firmly in std time, (y+k).d must
4983 be 0, so ignoring it has no consequence then.
4984 
4985 In any case, the new value is
4986 
4987     z = y + y.s                                 [4]
4988 
4989 It's helpful to step back at look at [4] from a higher level:  it's simply
4990 mapping from UTC to tz's standard time.
4991 
4992 At this point, if
4993 
4994     z.n - z.o = x.n                             [5]
4995 
4996 we have an equivalent time, and are almost done.  The insecurity here is
4997 at the start of daylight time.  Picture US Eastern for concreteness.  The wall
4998 time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good
4999 sense then.  The docs ask that an Eastern tzinfo class consider such a time to
5000 be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST
5001 on the day DST starts.  We want to return the 1:MM EST spelling because that's
5002 the only spelling that makes sense on the local wall clock.
5003 
5004 In fact, if [5] holds at this point, we do have the standard-time spelling,
5005 but that takes a bit of proof.  We first prove a stronger result.  What's the
5006 difference between the LHS and RHS of [5]?  Let
5007 
5008     diff = x.n - (z.n - z.o)                    [6]
5009 
5010 Now
5011     z.n =                       by [4]
5012     (y + y.s).n =               by #5
5013     y.n + y.s =                 since y.n = x.n
5014     x.n + y.s =                 since z and y are have the same tzinfo member,
5015                                     y.s = z.s by #2
5016     x.n + z.s
5017 
5018 Plugging that back into [6] gives
5019 
5020     diff =
5021     x.n - ((x.n + z.s) - z.o) =     expanding
5022     x.n - x.n - z.s + z.o =         cancelling
5023     - z.s + z.o =                   by #2
5024     z.d
5025 
5026 So diff = z.d.
5027 
5028 If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time
5029 spelling we wanted in the endcase described above.  We're done.  Contrarily,
5030 if z.d = 0, then we have a UTC equivalent, and are also done.
5031 
5032 If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to
5033 add to z (in effect, z is in tz's standard time, and we need to shift the
5034 local clock into tz's daylight time).
5035 
5036 Let
5037 
5038     z' = z + z.d = z + diff                     [7]
5039 
5040 and we can again ask whether
5041 
5042     z'.n - z'.o = x.n                           [8]
5043 
5044 If so, we're done.  If not, the tzinfo class is insane, according to the
5045 assumptions we've made.  This also requires a bit of proof.  As before, let's
5046 compute the difference between the LHS and RHS of [8] (and skipping some of
5047 the justifications for the kinds of substitutions we've done several times
5048 already):
5049 
5050     diff' = x.n - (z'.n - z'.o) =           replacing z'.n via [7]
5051         x.n  - (z.n + diff - z'.o) =    replacing diff via [6]
5052         x.n - (z.n + x.n - (z.n - z.o) - z'.o) =
5053         x.n - z.n - x.n + z.n - z.o + z'.o =    cancel x.n
5054         - z.n + z.n - z.o + z'.o =              cancel z.n
5055         - z.o + z'.o =                      #1 twice
5056         -z.s - z.d + z'.s + z'.d =          z and z' have same tzinfo
5057         z'.d - z.d
5058 
5059 So z' is UTC-equivalent to x iff z'.d = z.d at this point.  If they are equal,
5060 we've found the UTC-equivalent so are done.  In fact, we stop with [7] and
5061 return z', not bothering to compute z'.d.
5062 
5063 How could z.d and z'd differ?  z' = z + z.d [7], so merely moving z' by
5064 a dst() offset, and starting *from* a time already in DST (we know z.d != 0),
5065 would have to change the result dst() returns:  we start in DST, and moving
5066 a little further into it takes us out of DST.
5067 
5068 There isn't a sane case where this can happen.  The closest it gets is at
5069 the end of DST, where there's an hour in UTC with no spelling in a hybrid
5070 tzinfo class.  In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT.  During
5071 that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM
5072 UTC) because the docs insist on that, but 0:MM is taken as being in daylight
5073 time (4:MM UTC).  There is no local time mapping to 5:MM UTC.  The local
5074 clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in
5075 standard time.  Since that's what the local clock *does*, we want to map both
5076 UTC hours 5:MM and 6:MM to 1:MM Eastern.  The result is ambiguous
5077 in local time, but so it goes -- it's the way the local clock works.
5078 
5079 When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,
5080 so z=0:MM.  z.d=60 (minutes) then, so [5] doesn't hold and we keep going.
5081 z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]
5082 (correctly) concludes that z' is not UTC-equivalent to x.
5083 
5084 Because we know z.d said z was in daylight time (else [5] would have held and
5085 we would have stopped then), and we know z.d != z'.d (else [8] would have held
5086 and we would have stopped then), and there are only 2 possible values dst() can
5087 return in Eastern, it follows that z'.d must be 0 (which it is in the example,
5088 but the reasoning doesn't depend on the example -- it depends on there being
5089 two possible dst() outcomes, one zero and the other non-zero).  Therefore
5090 z' must be in standard time, and is the spelling we want in this case.
5091 
5092 Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is
5093 concerned (because it takes z' as being in standard time rather than the
5094 daylight time we intend here), but returning it gives the real-life "local
5095 clock repeats an hour" behavior when mapping the "unspellable" UTC hour into
5096 tz.
5097 
5098 When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with
5099 the 1:MM standard time spelling we want.
5100 
5101 So how can this break?  One of the assumptions must be violated.  Two
5102 possibilities:
5103 
5104 1) [2] effectively says that y.s is invariant across all y belong to a given
5105    time zone.  This isn't true if, for political reasons or continental drift,
5106    a region decides to change its base offset from UTC.
5107 
5108 2) There may be versions of "double daylight" time where the tail end of
5109    the analysis gives up a step too early.  I haven't thought about that
5110    enough to say.
5111 
5112 In any case, it's clear that the default fromutc() is strong enough to handle
5113 "almost all" time zones:  so long as the standard offset is invariant, it
5114 doesn't matter if daylight time transition points change from year to year, or
5115 if daylight time is skipped in some years; it doesn't matter how large or
5116 small dst() may get within its bounds; and it doesn't even matter if some
5117 perverse time zone returns a negative dst()).  So a breaking case must be
5118 pretty bizarre, and a tzinfo subclass can override fromutc() if it is.
5119 --------------------------------------------------------------------------- */
5120