]> git.proxmox.com Git - mirror_edk2.git/blobdiff - AppPkg/Applications/Python/Python-2.7.10/Modules/datetimemodule.c
edk2: Remove AppPkg, StdLib, StdLibPrivateInternalFiles
[mirror_edk2.git] / AppPkg / Applications / Python / Python-2.7.10 / Modules / datetimemodule.c
diff --git a/AppPkg/Applications/Python/Python-2.7.10/Modules/datetimemodule.c b/AppPkg/Applications/Python/Python-2.7.10/Modules/datetimemodule.c
deleted file mode 100644 (file)
index 655f70d..0000000
+++ /dev/null
@@ -1,5117 +0,0 @@
-/*  C implementation for the date/time type documented at\r
- *  http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage\r
- */\r
-\r
-#define PY_SSIZE_T_CLEAN\r
-\r
-#include "Python.h"\r
-#include "modsupport.h"\r
-#include "structmember.h"\r
-\r
-#include <time.h>\r
-\r
-#include "timefuncs.h"\r
-\r
-/* Differentiate between building the core module and building extension\r
- * modules.\r
- */\r
-#ifndef Py_BUILD_CORE\r
-#define Py_BUILD_CORE\r
-#endif\r
-#include "datetime.h"\r
-#undef Py_BUILD_CORE\r
-\r
-/* We require that C int be at least 32 bits, and use int virtually\r
- * everywhere.  In just a few cases we use a temp long, where a Python\r
- * API returns a C long.  In such cases, we have to ensure that the\r
- * final result fits in a C int (this can be an issue on 64-bit boxes).\r
- */\r
-#if SIZEOF_INT < 4\r
-#       error "datetime.c requires that C int have at least 32 bits"\r
-#endif\r
-\r
-#define MINYEAR 1\r
-#define MAXYEAR 9999\r
-#define MAXORDINAL 3652059 /* date(9999,12,31).toordinal() */\r
-\r
-/* Nine decimal digits is easy to communicate, and leaves enough room\r
- * so that two delta days can be added w/o fear of overflowing a signed\r
- * 32-bit int, and with plenty of room left over to absorb any possible\r
- * carries from adding seconds.\r
- */\r
-#define MAX_DELTA_DAYS 999999999\r
-\r
-/* Rename the long macros in datetime.h to more reasonable short names. */\r
-#define GET_YEAR                PyDateTime_GET_YEAR\r
-#define GET_MONTH               PyDateTime_GET_MONTH\r
-#define GET_DAY                 PyDateTime_GET_DAY\r
-#define DATE_GET_HOUR           PyDateTime_DATE_GET_HOUR\r
-#define DATE_GET_MINUTE         PyDateTime_DATE_GET_MINUTE\r
-#define DATE_GET_SECOND         PyDateTime_DATE_GET_SECOND\r
-#define DATE_GET_MICROSECOND    PyDateTime_DATE_GET_MICROSECOND\r
-\r
-/* Date accessors for date and datetime. */\r
-#define SET_YEAR(o, v)          (((o)->data[0] = ((v) & 0xff00) >> 8), \\r
-                 ((o)->data[1] = ((v) & 0x00ff)))\r
-#define SET_MONTH(o, v)         (PyDateTime_GET_MONTH(o) = (v))\r
-#define SET_DAY(o, v)           (PyDateTime_GET_DAY(o) = (v))\r
-\r
-/* Date/Time accessors for datetime. */\r
-#define DATE_SET_HOUR(o, v)     (PyDateTime_DATE_GET_HOUR(o) = (v))\r
-#define DATE_SET_MINUTE(o, v)   (PyDateTime_DATE_GET_MINUTE(o) = (v))\r
-#define DATE_SET_SECOND(o, v)   (PyDateTime_DATE_GET_SECOND(o) = (v))\r
-#define DATE_SET_MICROSECOND(o, v)      \\r
-    (((o)->data[7] = ((v) & 0xff0000) >> 16), \\r
-     ((o)->data[8] = ((v) & 0x00ff00) >> 8), \\r
-     ((o)->data[9] = ((v) & 0x0000ff)))\r
-\r
-/* Time accessors for time. */\r
-#define TIME_GET_HOUR           PyDateTime_TIME_GET_HOUR\r
-#define TIME_GET_MINUTE         PyDateTime_TIME_GET_MINUTE\r
-#define TIME_GET_SECOND         PyDateTime_TIME_GET_SECOND\r
-#define TIME_GET_MICROSECOND    PyDateTime_TIME_GET_MICROSECOND\r
-#define TIME_SET_HOUR(o, v)     (PyDateTime_TIME_GET_HOUR(o) = (v))\r
-#define TIME_SET_MINUTE(o, v)   (PyDateTime_TIME_GET_MINUTE(o) = (v))\r
-#define TIME_SET_SECOND(o, v)   (PyDateTime_TIME_GET_SECOND(o) = (v))\r
-#define TIME_SET_MICROSECOND(o, v)      \\r
-    (((o)->data[3] = ((v) & 0xff0000) >> 16), \\r
-     ((o)->data[4] = ((v) & 0x00ff00) >> 8), \\r
-     ((o)->data[5] = ((v) & 0x0000ff)))\r
-\r
-/* Delta accessors for timedelta. */\r
-#define GET_TD_DAYS(o)          (((PyDateTime_Delta *)(o))->days)\r
-#define GET_TD_SECONDS(o)       (((PyDateTime_Delta *)(o))->seconds)\r
-#define GET_TD_MICROSECONDS(o)  (((PyDateTime_Delta *)(o))->microseconds)\r
-\r
-#define SET_TD_DAYS(o, v)       ((o)->days = (v))\r
-#define SET_TD_SECONDS(o, v)    ((o)->seconds = (v))\r
-#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))\r
-\r
-/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns\r
- * p->hastzinfo.\r
- */\r
-#define HASTZINFO(p)            (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)\r
-\r
-/* M is a char or int claiming to be a valid month.  The macro is equivalent\r
- * to the two-sided Python test\r
- *      1 <= M <= 12\r
- */\r
-#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)\r
-\r
-/* Forward declarations. */\r
-static PyTypeObject PyDateTime_DateType;\r
-static PyTypeObject PyDateTime_DateTimeType;\r
-static PyTypeObject PyDateTime_DeltaType;\r
-static PyTypeObject PyDateTime_TimeType;\r
-static PyTypeObject PyDateTime_TZInfoType;\r
-\r
-/* ---------------------------------------------------------------------------\r
- * Math utilities.\r
- */\r
-\r
-/* k = i+j overflows iff k differs in sign from both inputs,\r
- * iff k^i has sign bit set and k^j has sign bit set,\r
- * iff (k^i)&(k^j) has sign bit set.\r
- */\r
-#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \\r
-    ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)\r
-\r
-/* Compute Python divmod(x, y), returning the quotient and storing the\r
- * remainder into *r.  The quotient is the floor of x/y, and that's\r
- * the real point of this.  C will probably truncate instead (C99\r
- * requires truncation; C89 left it implementation-defined).\r
- * Simplification:  we *require* that y > 0 here.  That's appropriate\r
- * for all the uses made of it.  This simplifies the code and makes\r
- * the overflow case impossible (divmod(LONG_MIN, -1) is the only\r
- * overflow case).\r
- */\r
-static int\r
-divmod(int x, int y, int *r)\r
-{\r
-    int quo;\r
-\r
-    assert(y > 0);\r
-    quo = x / y;\r
-    *r = x - quo * y;\r
-    if (*r < 0) {\r
-        --quo;\r
-        *r += y;\r
-    }\r
-    assert(0 <= *r && *r < y);\r
-    return quo;\r
-}\r
-\r
-/* Round a double to the nearest long.  |x| must be small enough to fit\r
- * in a C long; this is not checked.\r
- */\r
-static long\r
-round_to_long(double x)\r
-{\r
-    if (x >= 0.0)\r
-        x = floor(x + 0.5);\r
-    else\r
-        x = ceil(x - 0.5);\r
-    return (long)x;\r
-}\r
-\r
-/* ---------------------------------------------------------------------------\r
- * General calendrical helper functions\r
- */\r
-\r
-/* For each month ordinal in 1..12, the number of days in that month,\r
- * and the number of days before that month in the same year.  These\r
- * are correct for non-leap years only.\r
- */\r
-static int _days_in_month[] = {\r
-    0, /* unused; this vector uses 1-based indexing */\r
-    31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31\r
-};\r
-\r
-static int _days_before_month[] = {\r
-    0, /* unused; this vector uses 1-based indexing */\r
-    0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334\r
-};\r
-\r
-/* year -> 1 if leap year, else 0. */\r
-static int\r
-is_leap(int year)\r
-{\r
-    /* Cast year to unsigned.  The result is the same either way, but\r
-     * C can generate faster code for unsigned mod than for signed\r
-     * mod (especially for % 4 -- a good compiler should just grab\r
-     * the last 2 bits when the LHS is unsigned).\r
-     */\r
-    const unsigned int ayear = (unsigned int)year;\r
-    return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);\r
-}\r
-\r
-/* year, month -> number of days in that month in that year */\r
-static int\r
-days_in_month(int year, int month)\r
-{\r
-    assert(month >= 1);\r
-    assert(month <= 12);\r
-    if (month == 2 && is_leap(year))\r
-        return 29;\r
-    else\r
-        return _days_in_month[month];\r
-}\r
-\r
-/* year, month -> number of days in year preceeding first day of month */\r
-static int\r
-days_before_month(int year, int month)\r
-{\r
-    int days;\r
-\r
-    assert(month >= 1);\r
-    assert(month <= 12);\r
-    days = _days_before_month[month];\r
-    if (month > 2 && is_leap(year))\r
-        ++days;\r
-    return days;\r
-}\r
-\r
-/* year -> number of days before January 1st of year.  Remember that we\r
- * start with year 1, so days_before_year(1) == 0.\r
- */\r
-static int\r
-days_before_year(int year)\r
-{\r
-    int y = year - 1;\r
-    /* This is incorrect if year <= 0; we really want the floor\r
-     * here.  But so long as MINYEAR is 1, the smallest year this\r
-     * can see is 0 (this can happen in some normalization endcases),\r
-     * so we'll just special-case that.\r
-     */\r
-    assert (year >= 0);\r
-    if (y >= 0)\r
-        return y*365 + y/4 - y/100 + y/400;\r
-    else {\r
-        assert(y == -1);\r
-        return -366;\r
-    }\r
-}\r
-\r
-/* Number of days in 4, 100, and 400 year cycles.  That these have\r
- * the correct values is asserted in the module init function.\r
- */\r
-#define DI4Y    1461    /* days_before_year(5); days in 4 years */\r
-#define DI100Y  36524   /* days_before_year(101); days in 100 years */\r
-#define DI400Y  146097  /* days_before_year(401); days in 400 years  */\r
-\r
-/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */\r
-static void\r
-ord_to_ymd(int ordinal, int *year, int *month, int *day)\r
-{\r
-    int n, n1, n4, n100, n400, leapyear, preceding;\r
-\r
-    /* ordinal is a 1-based index, starting at 1-Jan-1.  The pattern of\r
-     * leap years repeats exactly every 400 years.  The basic strategy is\r
-     * to find the closest 400-year boundary at or before ordinal, then\r
-     * work with the offset from that boundary to ordinal.  Life is much\r
-     * clearer if we subtract 1 from ordinal first -- then the values\r
-     * of ordinal at 400-year boundaries are exactly those divisible\r
-     * by DI400Y:\r
-     *\r
-     *    D  M   Y            n              n-1\r
-     *    -- --- ----        ----------     ----------------\r
-     *    31 Dec -400        -DI400Y       -DI400Y -1\r
-     *     1 Jan -399         -DI400Y +1   -DI400Y      400-year boundary\r
-     *    ...\r
-     *    30 Dec  000        -1             -2\r
-     *    31 Dec  000         0             -1\r
-     *     1 Jan  001         1              0          400-year boundary\r
-     *     2 Jan  001         2              1\r
-     *     3 Jan  001         3              2\r
-     *    ...\r
-     *    31 Dec  400         DI400Y        DI400Y -1\r
-     *     1 Jan  401         DI400Y +1     DI400Y      400-year boundary\r
-     */\r
-    assert(ordinal >= 1);\r
-    --ordinal;\r
-    n400 = ordinal / DI400Y;\r
-    n = ordinal % DI400Y;\r
-    *year = n400 * 400 + 1;\r
-\r
-    /* Now n is the (non-negative) offset, in days, from January 1 of\r
-     * year, to the desired date.  Now compute how many 100-year cycles\r
-     * precede n.\r
-     * Note that it's possible for n100 to equal 4!  In that case 4 full\r
-     * 100-year cycles precede the desired day, which implies the\r
-     * desired day is December 31 at the end of a 400-year cycle.\r
-     */\r
-    n100 = n / DI100Y;\r
-    n = n % DI100Y;\r
-\r
-    /* Now compute how many 4-year cycles precede it. */\r
-    n4 = n / DI4Y;\r
-    n = n % DI4Y;\r
-\r
-    /* And now how many single years.  Again n1 can be 4, and again\r
-     * meaning that the desired day is December 31 at the end of the\r
-     * 4-year cycle.\r
-     */\r
-    n1 = n / 365;\r
-    n = n % 365;\r
-\r
-    *year += n100 * 100 + n4 * 4 + n1;\r
-    if (n1 == 4 || n100 == 4) {\r
-        assert(n == 0);\r
-        *year -= 1;\r
-        *month = 12;\r
-        *day = 31;\r
-        return;\r
-    }\r
-\r
-    /* Now the year is correct, and n is the offset from January 1.  We\r
-     * find the month via an estimate that's either exact or one too\r
-     * large.\r
-     */\r
-    leapyear = n1 == 3 && (n4 != 24 || n100 == 3);\r
-    assert(leapyear == is_leap(*year));\r
-    *month = (n + 50) >> 5;\r
-    preceding = (_days_before_month[*month] + (*month > 2 && leapyear));\r
-    if (preceding > n) {\r
-        /* estimate is too large */\r
-        *month -= 1;\r
-        preceding -= days_in_month(*year, *month);\r
-    }\r
-    n -= preceding;\r
-    assert(0 <= n);\r
-    assert(n < days_in_month(*year, *month));\r
-\r
-    *day = n + 1;\r
-}\r
-\r
-/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */\r
-static int\r
-ymd_to_ord(int year, int month, int day)\r
-{\r
-    return days_before_year(year) + days_before_month(year, month) + day;\r
-}\r
-\r
-/* Day of week, where Monday==0, ..., Sunday==6.  1/1/1 was a Monday. */\r
-static int\r
-weekday(int year, int month, int day)\r
-{\r
-    return (ymd_to_ord(year, month, day) + 6) % 7;\r
-}\r
-\r
-/* Ordinal of the Monday starting week 1 of the ISO year.  Week 1 is the\r
- * first calendar week containing a Thursday.\r
- */\r
-static int\r
-iso_week1_monday(int year)\r
-{\r
-    int first_day = ymd_to_ord(year, 1, 1);     /* ord of 1/1 */\r
-    /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */\r
-    int first_weekday = (first_day + 6) % 7;\r
-    /* ordinal of closest Monday at or before 1/1 */\r
-    int week1_monday  = first_day - first_weekday;\r
-\r
-    if (first_weekday > 3)      /* if 1/1 was Fri, Sat, Sun */\r
-        week1_monday += 7;\r
-    return week1_monday;\r
-}\r
-\r
-/* ---------------------------------------------------------------------------\r
- * Range checkers.\r
- */\r
-\r
-/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS.  If so, return 0.\r
- * If not, raise OverflowError and return -1.\r
- */\r
-static int\r
-check_delta_day_range(int days)\r
-{\r
-    if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)\r
-        return 0;\r
-    PyErr_Format(PyExc_OverflowError,\r
-                 "days=%d; must have magnitude <= %d",\r
-                 days, MAX_DELTA_DAYS);\r
-    return -1;\r
-}\r
-\r
-/* Check that date arguments are in range.  Return 0 if they are.  If they\r
- * aren't, raise ValueError and return -1.\r
- */\r
-static int\r
-check_date_args(int year, int month, int day)\r
-{\r
-\r
-    if (year < MINYEAR || year > MAXYEAR) {\r
-        PyErr_SetString(PyExc_ValueError,\r
-                        "year is out of range");\r
-        return -1;\r
-    }\r
-    if (month < 1 || month > 12) {\r
-        PyErr_SetString(PyExc_ValueError,\r
-                        "month must be in 1..12");\r
-        return -1;\r
-    }\r
-    if (day < 1 || day > days_in_month(year, month)) {\r
-        PyErr_SetString(PyExc_ValueError,\r
-                        "day is out of range for month");\r
-        return -1;\r
-    }\r
-    return 0;\r
-}\r
-\r
-/* Check that time arguments are in range.  Return 0 if they are.  If they\r
- * aren't, raise ValueError and return -1.\r
- */\r
-static int\r
-check_time_args(int h, int m, int s, int us)\r
-{\r
-    if (h < 0 || h > 23) {\r
-        PyErr_SetString(PyExc_ValueError,\r
-                        "hour must be in 0..23");\r
-        return -1;\r
-    }\r
-    if (m < 0 || m > 59) {\r
-        PyErr_SetString(PyExc_ValueError,\r
-                        "minute must be in 0..59");\r
-        return -1;\r
-    }\r
-    if (s < 0 || s > 59) {\r
-        PyErr_SetString(PyExc_ValueError,\r
-                        "second must be in 0..59");\r
-        return -1;\r
-    }\r
-    if (us < 0 || us > 999999) {\r
-        PyErr_SetString(PyExc_ValueError,\r
-                        "microsecond must be in 0..999999");\r
-        return -1;\r
-    }\r
-    return 0;\r
-}\r
-\r
-/* ---------------------------------------------------------------------------\r
- * Normalization utilities.\r
- */\r
-\r
-/* One step of a mixed-radix conversion.  A "hi" unit is equivalent to\r
- * factor "lo" units.  factor must be > 0.  If *lo is less than 0, or\r
- * at least factor, enough of *lo is converted into "hi" units so that\r
- * 0 <= *lo < factor.  The input values must be such that int overflow\r
- * is impossible.\r
- */\r
-static void\r
-normalize_pair(int *hi, int *lo, int factor)\r
-{\r
-    assert(factor > 0);\r
-    assert(lo != hi);\r
-    if (*lo < 0 || *lo >= factor) {\r
-        const int num_hi = divmod(*lo, factor, lo);\r
-        const int new_hi = *hi + num_hi;\r
-        assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));\r
-        *hi = new_hi;\r
-    }\r
-    assert(0 <= *lo && *lo < factor);\r
-}\r
-\r
-/* Fiddle days (d), seconds (s), and microseconds (us) so that\r
- *      0 <= *s < 24*3600\r
- *      0 <= *us < 1000000\r
- * The input values must be such that the internals don't overflow.\r
- * The way this routine is used, we don't get close.\r
- */\r
-static void\r
-normalize_d_s_us(int *d, int *s, int *us)\r
-{\r
-    if (*us < 0 || *us >= 1000000) {\r
-        normalize_pair(s, us, 1000000);\r
-        /* |s| can't be bigger than about\r
-         * |original s| + |original us|/1000000 now.\r
-         */\r
-\r
-    }\r
-    if (*s < 0 || *s >= 24*3600) {\r
-        normalize_pair(d, s, 24*3600);\r
-        /* |d| can't be bigger than about\r
-         * |original d| +\r
-         * (|original s| + |original us|/1000000) / (24*3600) now.\r
-         */\r
-    }\r
-    assert(0 <= *s && *s < 24*3600);\r
-    assert(0 <= *us && *us < 1000000);\r
-}\r
-\r
-/* Fiddle years (y), months (m), and days (d) so that\r
- *      1 <= *m <= 12\r
- *      1 <= *d <= days_in_month(*y, *m)\r
- * The input values must be such that the internals don't overflow.\r
- * The way this routine is used, we don't get close.\r
- */\r
-static int\r
-normalize_y_m_d(int *y, int *m, int *d)\r
-{\r
-    int dim;            /* # of days in month */\r
-\r
-    /* This gets muddy:  the proper range for day can't be determined\r
-     * without knowing the correct month and year, but if day is, e.g.,\r
-     * plus or minus a million, the current month and year values make\r
-     * no sense (and may also be out of bounds themselves).\r
-     * Saying 12 months == 1 year should be non-controversial.\r
-     */\r
-    if (*m < 1 || *m > 12) {\r
-        --*m;\r
-        normalize_pair(y, m, 12);\r
-        ++*m;\r
-        /* |y| can't be bigger than about\r
-         * |original y| + |original m|/12 now.\r
-         */\r
-    }\r
-    assert(1 <= *m && *m <= 12);\r
-\r
-    /* Now only day can be out of bounds (year may also be out of bounds\r
-     * for a datetime object, but we don't care about that here).\r
-     * If day is out of bounds, what to do is arguable, but at least the\r
-     * method here is principled and explainable.\r
-     */\r
-    dim = days_in_month(*y, *m);\r
-    if (*d < 1 || *d > dim) {\r
-        /* Move day-1 days from the first of the month.  First try to\r
-         * get off cheap if we're only one day out of range\r
-         * (adjustments for timezone alone can't be worse than that).\r
-         */\r
-        if (*d == 0) {\r
-            --*m;\r
-            if (*m > 0)\r
-                *d = days_in_month(*y, *m);\r
-            else {\r
-                --*y;\r
-                *m = 12;\r
-                *d = 31;\r
-            }\r
-        }\r
-        else if (*d == dim + 1) {\r
-            /* move forward a day */\r
-            ++*m;\r
-            *d = 1;\r
-            if (*m > 12) {\r
-                *m = 1;\r
-                ++*y;\r
-            }\r
-        }\r
-        else {\r
-            int ordinal = ymd_to_ord(*y, *m, 1) +\r
-                                      *d - 1;\r
-            if (ordinal < 1 || ordinal > MAXORDINAL) {\r
-                goto error;\r
-            } else {\r
-                ord_to_ymd(ordinal, y, m, d);\r
-                return 0;\r
-            }\r
-        }\r
-    }\r
-    assert(*m > 0);\r
-    assert(*d > 0);\r
-    if (MINYEAR <= *y && *y <= MAXYEAR)\r
-        return 0;\r
- error:\r
-    PyErr_SetString(PyExc_OverflowError,\r
-            "date value out of range");\r
-    return -1;\r
-\r
-}\r
-\r
-/* Fiddle out-of-bounds months and days so that the result makes some kind\r
- * of sense.  The parameters are both inputs and outputs.  Returns < 0 on\r
- * failure, where failure means the adjusted year is out of bounds.\r
- */\r
-static int\r
-normalize_date(int *year, int *month, int *day)\r
-{\r
-    return normalize_y_m_d(year, month, day);\r
-}\r
-\r
-/* Force all the datetime fields into range.  The parameters are both\r
- * inputs and outputs.  Returns < 0 on error.\r
- */\r
-static int\r
-normalize_datetime(int *year, int *month, int *day,\r
-                   int *hour, int *minute, int *second,\r
-                   int *microsecond)\r
-{\r
-    normalize_pair(second, microsecond, 1000000);\r
-    normalize_pair(minute, second, 60);\r
-    normalize_pair(hour, minute, 60);\r
-    normalize_pair(day, hour, 24);\r
-    return normalize_date(year, month, day);\r
-}\r
-\r
-/* ---------------------------------------------------------------------------\r
- * Basic object allocation:  tp_alloc implementations.  These allocate\r
- * Python objects of the right size and type, and do the Python object-\r
- * initialization bit.  If there's not enough memory, they return NULL after\r
- * setting MemoryError.  All data members remain uninitialized trash.\r
- *\r
- * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo\r
- * member is needed.  This is ugly, imprecise, and possibly insecure.\r
- * tp_basicsize for the time and datetime types is set to the size of the\r
- * struct that has room for the tzinfo member, so subclasses in Python will\r
- * allocate enough space for a tzinfo member whether or not one is actually\r
- * needed.  That's the "ugly and imprecise" parts.  The "possibly insecure"\r
- * part is that PyType_GenericAlloc() (which subclasses in Python end up\r
- * using) just happens today to effectively ignore the nitems argument\r
- * when tp_itemsize is 0, which it is for these type objects.  If that\r
- * changes, perhaps the callers of tp_alloc slots in this file should\r
- * be changed to force a 0 nitems argument unless the type being allocated\r
- * is a base type implemented in this file (so that tp_alloc is time_alloc\r
- * or datetime_alloc below, which know about the nitems abuse).\r
- */\r
-\r
-static PyObject *\r
-time_alloc(PyTypeObject *type, Py_ssize_t aware)\r
-{\r
-    PyObject *self;\r
-\r
-    self = (PyObject *)\r
-        PyObject_MALLOC(aware ?\r
-                        sizeof(PyDateTime_Time) :\r
-                sizeof(_PyDateTime_BaseTime));\r
-    if (self == NULL)\r
-        return (PyObject *)PyErr_NoMemory();\r
-    PyObject_INIT(self, type);\r
-    return self;\r
-}\r
-\r
-static PyObject *\r
-datetime_alloc(PyTypeObject *type, Py_ssize_t aware)\r
-{\r
-    PyObject *self;\r
-\r
-    self = (PyObject *)\r
-        PyObject_MALLOC(aware ?\r
-                        sizeof(PyDateTime_DateTime) :\r
-                sizeof(_PyDateTime_BaseDateTime));\r
-    if (self == NULL)\r
-        return (PyObject *)PyErr_NoMemory();\r
-    PyObject_INIT(self, type);\r
-    return self;\r
-}\r
-\r
-/* ---------------------------------------------------------------------------\r
- * Helpers for setting object fields.  These work on pointers to the\r
- * appropriate base class.\r
- */\r
-\r
-/* For date and datetime. */\r
-static void\r
-set_date_fields(PyDateTime_Date *self, int y, int m, int d)\r
-{\r
-    self->hashcode = -1;\r
-    SET_YEAR(self, y);\r
-    SET_MONTH(self, m);\r
-    SET_DAY(self, d);\r
-}\r
-\r
-/* ---------------------------------------------------------------------------\r
- * Create various objects, mostly without range checking.\r
- */\r
-\r
-/* Create a date instance with no range checking. */\r
-static PyObject *\r
-new_date_ex(int year, int month, int day, PyTypeObject *type)\r
-{\r
-    PyDateTime_Date *self;\r
-\r
-    self = (PyDateTime_Date *) (type->tp_alloc(type, 0));\r
-    if (self != NULL)\r
-        set_date_fields(self, year, month, day);\r
-    return (PyObject *) self;\r
-}\r
-\r
-#define new_date(year, month, day) \\r
-    new_date_ex(year, month, day, &PyDateTime_DateType)\r
-\r
-/* Create a datetime instance with no range checking. */\r
-static PyObject *\r
-new_datetime_ex(int year, int month, int day, int hour, int minute,\r
-             int second, int usecond, PyObject *tzinfo, PyTypeObject *type)\r
-{\r
-    PyDateTime_DateTime *self;\r
-    char aware = tzinfo != Py_None;\r
-\r
-    self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));\r
-    if (self != NULL) {\r
-        self->hastzinfo = aware;\r
-        set_date_fields((PyDateTime_Date *)self, year, month, day);\r
-        DATE_SET_HOUR(self, hour);\r
-        DATE_SET_MINUTE(self, minute);\r
-        DATE_SET_SECOND(self, second);\r
-        DATE_SET_MICROSECOND(self, usecond);\r
-        if (aware) {\r
-            Py_INCREF(tzinfo);\r
-            self->tzinfo = tzinfo;\r
-        }\r
-    }\r
-    return (PyObject *)self;\r
-}\r
-\r
-#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo)           \\r
-    new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo,            \\r
-                    &PyDateTime_DateTimeType)\r
-\r
-/* Create a time instance with no range checking. */\r
-static PyObject *\r
-new_time_ex(int hour, int minute, int second, int usecond,\r
-            PyObject *tzinfo, PyTypeObject *type)\r
-{\r
-    PyDateTime_Time *self;\r
-    char aware = tzinfo != Py_None;\r
-\r
-    self = (PyDateTime_Time *) (type->tp_alloc(type, aware));\r
-    if (self != NULL) {\r
-        self->hastzinfo = aware;\r
-        self->hashcode = -1;\r
-        TIME_SET_HOUR(self, hour);\r
-        TIME_SET_MINUTE(self, minute);\r
-        TIME_SET_SECOND(self, second);\r
-        TIME_SET_MICROSECOND(self, usecond);\r
-        if (aware) {\r
-            Py_INCREF(tzinfo);\r
-            self->tzinfo = tzinfo;\r
-        }\r
-    }\r
-    return (PyObject *)self;\r
-}\r
-\r
-#define new_time(hh, mm, ss, us, tzinfo)                \\r
-    new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)\r
-\r
-/* Create a timedelta instance.  Normalize the members iff normalize is\r
- * true.  Passing false is a speed optimization, if you know for sure\r
- * that seconds and microseconds are already in their proper ranges.  In any\r
- * case, raises OverflowError and returns NULL if the normalized days is out\r
- * of range).\r
- */\r
-static PyObject *\r
-new_delta_ex(int days, int seconds, int microseconds, int normalize,\r
-             PyTypeObject *type)\r
-{\r
-    PyDateTime_Delta *self;\r
-\r
-    if (normalize)\r
-        normalize_d_s_us(&days, &seconds, &microseconds);\r
-    assert(0 <= seconds && seconds < 24*3600);\r
-    assert(0 <= microseconds && microseconds < 1000000);\r
-\r
-    if (check_delta_day_range(days) < 0)\r
-        return NULL;\r
-\r
-    self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));\r
-    if (self != NULL) {\r
-        self->hashcode = -1;\r
-        SET_TD_DAYS(self, days);\r
-        SET_TD_SECONDS(self, seconds);\r
-        SET_TD_MICROSECONDS(self, microseconds);\r
-    }\r
-    return (PyObject *) self;\r
-}\r
-\r
-#define new_delta(d, s, us, normalize)  \\r
-    new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)\r
-\r
-/* ---------------------------------------------------------------------------\r
- * tzinfo helpers.\r
- */\r
-\r
-/* Ensure that p is None or of a tzinfo subclass.  Return 0 if OK; if not\r
- * raise TypeError and return -1.\r
- */\r
-static int\r
-check_tzinfo_subclass(PyObject *p)\r
-{\r
-    if (p == Py_None || PyTZInfo_Check(p))\r
-        return 0;\r
-    PyErr_Format(PyExc_TypeError,\r
-                 "tzinfo argument must be None or of a tzinfo subclass, "\r
-                 "not type '%s'",\r
-                 Py_TYPE(p)->tp_name);\r
-    return -1;\r
-}\r
-\r
-/* Return tzinfo.methname(tzinfoarg), without any checking of results.\r
- * If tzinfo is None, returns None.\r
- */\r
-static PyObject *\r
-call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)\r
-{\r
-    PyObject *result;\r
-\r
-    assert(tzinfo && methname && tzinfoarg);\r
-    assert(check_tzinfo_subclass(tzinfo) >= 0);\r
-    if (tzinfo == Py_None) {\r
-        result = Py_None;\r
-        Py_INCREF(result);\r
-    }\r
-    else\r
-        result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);\r
-    return result;\r
-}\r
-\r
-/* If self has a tzinfo member, return a BORROWED reference to it.  Else\r
- * return NULL, which is NOT AN ERROR.  There are no error returns here,\r
- * and the caller must not decref the result.\r
- */\r
-static PyObject *\r
-get_tzinfo_member(PyObject *self)\r
-{\r
-    PyObject *tzinfo = NULL;\r
-\r
-    if (PyDateTime_Check(self) && HASTZINFO(self))\r
-        tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;\r
-    else if (PyTime_Check(self) && HASTZINFO(self))\r
-        tzinfo = ((PyDateTime_Time *)self)->tzinfo;\r
-\r
-    return tzinfo;\r
-}\r
-\r
-/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the\r
- * result.  tzinfo must be an instance of the tzinfo class.  If the method\r
- * returns None, this returns 0 and sets *none to 1.  If the method doesn't\r
- * return None or timedelta, TypeError is raised and this returns -1.  If it\r
- * returnsa timedelta and the value is out of range or isn't a whole number\r
- * of minutes, ValueError is raised and this returns -1.\r
- * Else *none is set to 0 and the integer method result is returned.\r
- */\r
-static int\r
-call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,\r
-                       int *none)\r
-{\r
-    PyObject *u;\r
-    int result = -1;\r
-\r
-    assert(tzinfo != NULL);\r
-    assert(PyTZInfo_Check(tzinfo));\r
-    assert(tzinfoarg != NULL);\r
-\r
-    *none = 0;\r
-    u = call_tzinfo_method(tzinfo, name, tzinfoarg);\r
-    if (u == NULL)\r
-        return -1;\r
-\r
-    else if (u == Py_None) {\r
-        result = 0;\r
-        *none = 1;\r
-    }\r
-    else if (PyDelta_Check(u)) {\r
-        const int days = GET_TD_DAYS(u);\r
-        if (days < -1 || days > 0)\r
-            result = 24*60;             /* trigger ValueError below */\r
-        else {\r
-            /* next line can't overflow because we know days\r
-             * is -1 or 0 now\r
-             */\r
-            int ss = days * 24 * 3600 + GET_TD_SECONDS(u);\r
-            result = divmod(ss, 60, &ss);\r
-            if (ss || GET_TD_MICROSECONDS(u)) {\r
-                PyErr_Format(PyExc_ValueError,\r
-                             "tzinfo.%s() must return a "\r
-                             "whole number of minutes",\r
-                             name);\r
-                result = -1;\r
-            }\r
-        }\r
-    }\r
-    else {\r
-        PyErr_Format(PyExc_TypeError,\r
-                     "tzinfo.%s() must return None or "\r
-                     "timedelta, not '%s'",\r
-                     name, Py_TYPE(u)->tp_name);\r
-    }\r
-\r
-    Py_DECREF(u);\r
-    if (result < -1439 || result > 1439) {\r
-        PyErr_Format(PyExc_ValueError,\r
-                     "tzinfo.%s() returned %d; must be in "\r
-                     "-1439 .. 1439",\r
-                     name, result);\r
-        result = -1;\r
-    }\r
-    return result;\r
-}\r
-\r
-/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the\r
- * result.  tzinfo must be an instance of the tzinfo class.  If utcoffset()\r
- * returns None, call_utcoffset returns 0 and sets *none to 1.  If uctoffset()\r
- * doesn't return None or timedelta, TypeError is raised and this returns -1.\r
- * If utcoffset() returns an invalid timedelta (out of range, or not a whole\r
- * # of minutes), ValueError is raised and this returns -1.  Else *none is\r
- * set to 0 and the offset is returned (as int # of minutes east of UTC).\r
- */\r
-static int\r
-call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)\r
-{\r
-    return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);\r
-}\r
-\r
-/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.\r
- */\r
-static PyObject *\r
-offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {\r
-    PyObject *result;\r
-\r
-    assert(tzinfo && name && tzinfoarg);\r
-    if (tzinfo == Py_None) {\r
-        result = Py_None;\r
-        Py_INCREF(result);\r
-    }\r
-    else {\r
-        int none;\r
-        int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,\r
-                                            &none);\r
-        if (offset < 0 && PyErr_Occurred())\r
-            return NULL;\r
-        if (none) {\r
-            result = Py_None;\r
-            Py_INCREF(result);\r
-        }\r
-        else\r
-            result = new_delta(0, offset * 60, 0, 1);\r
-    }\r
-    return result;\r
-}\r
-\r
-/* Call tzinfo.dst(tzinfoarg), and extract an integer from the\r
- * result.  tzinfo must be an instance of the tzinfo class.  If dst()\r
- * returns None, call_dst returns 0 and sets *none to 1.  If dst()\r
- & doesn't return None or timedelta, TypeError is raised and this\r
- * returns -1.  If dst() returns an invalid timedelta for a UTC offset,\r
- * ValueError is raised and this returns -1.  Else *none is set to 0 and\r
- * the offset is returned (as an int # of minutes east of UTC).\r
- */\r
-static int\r
-call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)\r
-{\r
-    return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);\r
-}\r
-\r
-/* Call tzinfo.tzname(tzinfoarg), and return the result.  tzinfo must be\r
- * an instance of the tzinfo class or None.  If tzinfo isn't None, and\r
- * tzname() doesn't return None or a string, TypeError is raised and this\r
- * returns NULL.\r
- */\r
-static PyObject *\r
-call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)\r
-{\r
-    PyObject *result;\r
-\r
-    assert(tzinfo != NULL);\r
-    assert(check_tzinfo_subclass(tzinfo) >= 0);\r
-    assert(tzinfoarg != NULL);\r
-\r
-    if (tzinfo == Py_None) {\r
-        result = Py_None;\r
-        Py_INCREF(result);\r
-    }\r
-    else\r
-        result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);\r
-\r
-    if (result != NULL && result != Py_None && ! PyString_Check(result)) {\r
-        PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "\r
-                     "return None or a string, not '%s'",\r
-                     Py_TYPE(result)->tp_name);\r
-        Py_DECREF(result);\r
-        result = NULL;\r
-    }\r
-    return result;\r
-}\r
-\r
-typedef enum {\r
-              /* an exception has been set; the caller should pass it on */\r
-          OFFSET_ERROR,\r
-\r
-          /* type isn't date, datetime, or time subclass */\r
-          OFFSET_UNKNOWN,\r
-\r
-          /* date,\r
-           * datetime with !hastzinfo\r
-           * datetime with None tzinfo,\r
-           * datetime where utcoffset() returns None\r
-           * time with !hastzinfo\r
-           * time with None tzinfo,\r
-           * time where utcoffset() returns None\r
-           */\r
-          OFFSET_NAIVE,\r
-\r
-          /* time or datetime where utcoffset() doesn't return None */\r
-          OFFSET_AWARE\r
-} naivety;\r
-\r
-/* Classify an object as to whether it's naive or offset-aware.  See\r
- * the "naivety" typedef for details.  If the type is aware, *offset is set\r
- * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).\r
- * If the type is offset-naive (or unknown, or error), *offset is set to 0.\r
- * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.\r
- */\r
-static naivety\r
-classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)\r
-{\r
-    int none;\r
-    PyObject *tzinfo;\r
-\r
-    assert(tzinfoarg != NULL);\r
-    *offset = 0;\r
-    tzinfo = get_tzinfo_member(op);     /* NULL means no tzinfo, not error */\r
-    if (tzinfo == Py_None)\r
-        return OFFSET_NAIVE;\r
-    if (tzinfo == NULL) {\r
-        /* note that a datetime passes the PyDate_Check test */\r
-        return (PyTime_Check(op) || PyDate_Check(op)) ?\r
-               OFFSET_NAIVE : OFFSET_UNKNOWN;\r
-    }\r
-    *offset = call_utcoffset(tzinfo, tzinfoarg, &none);\r
-    if (*offset == -1 && PyErr_Occurred())\r
-        return OFFSET_ERROR;\r
-    return none ? OFFSET_NAIVE : OFFSET_AWARE;\r
-}\r
-\r
-/* Classify two objects as to whether they're naive or offset-aware.\r
- * This isn't quite the same as calling classify_utcoffset() twice:  for\r
- * binary operations (comparison and subtraction), we generally want to\r
- * ignore the tzinfo members if they're identical.  This is by design,\r
- * so that results match "naive" expectations when mixing objects from a\r
- * single timezone.  So in that case, this sets both offsets to 0 and\r
- * both naiveties to OFFSET_NAIVE.\r
- * The function returns 0 if everything's OK, and -1 on error.\r
- */\r
-static int\r
-classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,\r
-                        PyObject *tzinfoarg1,\r
-                        PyObject *o2, int *offset2, naivety *n2,\r
-                        PyObject *tzinfoarg2)\r
-{\r
-    if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {\r
-        *offset1 = *offset2 = 0;\r
-        *n1 = *n2 = OFFSET_NAIVE;\r
-    }\r
-    else {\r
-        *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);\r
-        if (*n1 == OFFSET_ERROR)\r
-            return -1;\r
-        *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);\r
-        if (*n2 == OFFSET_ERROR)\r
-            return -1;\r
-    }\r
-    return 0;\r
-}\r
-\r
-/* repr is like "someclass(arg1, arg2)".  If tzinfo isn't None,\r
- * stuff\r
- *     ", tzinfo=" + repr(tzinfo)\r
- * before the closing ")".\r
- */\r
-static PyObject *\r
-append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)\r
-{\r
-    PyObject *temp;\r
-\r
-    assert(PyString_Check(repr));\r
-    assert(tzinfo);\r
-    if (tzinfo == Py_None)\r
-        return repr;\r
-    /* Get rid of the trailing ')'. */\r
-    assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');\r
-    temp = PyString_FromStringAndSize(PyString_AsString(repr),\r
-                                      PyString_Size(repr) - 1);\r
-    Py_DECREF(repr);\r
-    if (temp == NULL)\r
-        return NULL;\r
-    repr = temp;\r
-\r
-    /* Append ", tzinfo=". */\r
-    PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));\r
-\r
-    /* Append repr(tzinfo). */\r
-    PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));\r
-\r
-    /* Add a closing paren. */\r
-    PyString_ConcatAndDel(&repr, PyString_FromString(")"));\r
-    return repr;\r
-}\r
-\r
-/* ---------------------------------------------------------------------------\r
- * String format helpers.\r
- */\r
-\r
-static PyObject *\r
-format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)\r
-{\r
-    static const char *DayNames[] = {\r
-        "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"\r
-    };\r
-    static const char *MonthNames[] = {\r
-        "Jan", "Feb", "Mar", "Apr", "May", "Jun",\r
-        "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"\r
-    };\r
-\r
-    char buffer[128];\r
-    int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));\r
-\r
-    PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",\r
-                  DayNames[wday], MonthNames[GET_MONTH(date) - 1],\r
-                  GET_DAY(date), hours, minutes, seconds,\r
-                  GET_YEAR(date));\r
-    return PyString_FromString(buffer);\r
-}\r
-\r
-/* Add an hours & minutes UTC offset string to buf.  buf has no more than\r
- * buflen bytes remaining.  The UTC offset is gotten by calling\r
- * tzinfo.uctoffset(tzinfoarg).  If that returns None, \0 is stored into\r
- * *buf, and that's all.  Else the returned value is checked for sanity (an\r
- * integer in range), and if that's OK it's converted to an hours & minutes\r
- * string of the form\r
- *   sign HH sep MM\r
- * Returns 0 if everything is OK.  If the return value from utcoffset() is\r
- * bogus, an appropriate exception is set and -1 is returned.\r
- */\r
-static int\r
-format_utcoffset(char *buf, size_t buflen, const char *sep,\r
-                PyObject *tzinfo, PyObject *tzinfoarg)\r
-{\r
-    int offset;\r
-    int hours;\r
-    int minutes;\r
-    char sign;\r
-    int none;\r
-\r
-    assert(buflen >= 1);\r
-\r
-    offset = call_utcoffset(tzinfo, tzinfoarg, &none);\r
-    if (offset == -1 && PyErr_Occurred())\r
-        return -1;\r
-    if (none) {\r
-        *buf = '\0';\r
-        return 0;\r
-    }\r
-    sign = '+';\r
-    if (offset < 0) {\r
-        sign = '-';\r
-        offset = - offset;\r
-    }\r
-    hours = divmod(offset, 60, &minutes);\r
-    PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);\r
-    return 0;\r
-}\r
-\r
-static PyObject *\r
-make_freplacement(PyObject *object)\r
-{\r
-    char freplacement[64];\r
-    if (PyTime_Check(object))\r
-        sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));\r
-    else if (PyDateTime_Check(object))\r
-        sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));\r
-    else\r
-        sprintf(freplacement, "%06d", 0);\r
-\r
-    return PyString_FromStringAndSize(freplacement, strlen(freplacement));\r
-}\r
-\r
-/* I sure don't want to reproduce the strftime code from the time module,\r
- * so this imports the module and calls it.  All the hair is due to\r
- * giving special meanings to the %z, %Z and %f format codes via a\r
- * preprocessing step on the format string.\r
- * tzinfoarg is the argument to pass to the object's tzinfo method, if\r
- * needed.\r
- */\r
-static PyObject *\r
-wrap_strftime(PyObject *object, const char *format, size_t format_len,\r
-                PyObject *timetuple, PyObject *tzinfoarg)\r
-{\r
-    PyObject *result = NULL;            /* guilty until proved innocent */\r
-\r
-    PyObject *zreplacement = NULL;      /* py string, replacement for %z */\r
-    PyObject *Zreplacement = NULL;      /* py string, replacement for %Z */\r
-    PyObject *freplacement = NULL;      /* py string, replacement for %f */\r
-\r
-    const char *pin;            /* pointer to next char in input format */\r
-    char ch;                    /* next char in input format */\r
-\r
-    PyObject *newfmt = NULL;            /* py string, the output format */\r
-    char *pnew;         /* pointer to available byte in output format */\r
-    size_t totalnew;            /* number bytes total in output format buffer,\r
-                               exclusive of trailing \0 */\r
-    size_t usednew;     /* number bytes used so far in output format buffer */\r
-\r
-    const char *ptoappend;      /* ptr to string to append to output buffer */\r
-    size_t ntoappend;           /* # of bytes to append to output buffer */\r
-\r
-    assert(object && format && timetuple);\r
-\r
-    /* Give up if the year is before 1900.\r
-     * Python strftime() plays games with the year, and different\r
-     * games depending on whether envar PYTHON2K is set.  This makes\r
-     * years before 1900 a nightmare, even if the platform strftime\r
-     * supports them (and not all do).\r
-     * We could get a lot farther here by avoiding Python's strftime\r
-     * wrapper and calling the C strftime() directly, but that isn't\r
-     * an option in the Python implementation of this module.\r
-     */\r
-    {\r
-        long year;\r
-        PyObject *pyyear = PySequence_GetItem(timetuple, 0);\r
-        if (pyyear == NULL) return NULL;\r
-        assert(PyInt_Check(pyyear));\r
-        year = PyInt_AsLong(pyyear);\r
-        Py_DECREF(pyyear);\r
-        if (year < 1900) {\r
-            PyErr_Format(PyExc_ValueError, "year=%ld is before "\r
-                         "1900; the datetime strftime() "\r
-                         "methods require year >= 1900",\r
-                         year);\r
-            return NULL;\r
-        }\r
-    }\r
-\r
-    /* Scan the input format, looking for %z/%Z/%f escapes, building\r
-     * a new format.  Since computing the replacements for those codes\r
-     * is expensive, don't unless they're actually used.\r
-     */\r
-    if (format_len > INT_MAX - 1) {\r
-        PyErr_NoMemory();\r
-        goto Done;\r
-    }\r
-\r
-    totalnew = format_len + 1;          /* realistic if no %z/%Z/%f */\r
-    newfmt = PyString_FromStringAndSize(NULL, totalnew);\r
-    if (newfmt == NULL) goto Done;\r
-    pnew = PyString_AsString(newfmt);\r
-    usednew = 0;\r
-\r
-    pin = format;\r
-    while ((ch = *pin++) != '\0') {\r
-        if (ch != '%') {\r
-            ptoappend = pin - 1;\r
-            ntoappend = 1;\r
-        }\r
-        else if ((ch = *pin++) == '\0') {\r
-            /* There's a lone trailing %; doesn't make sense. */\r
-            PyErr_SetString(PyExc_ValueError, "strftime format "\r
-                            "ends with raw %");\r
-            goto Done;\r
-        }\r
-        /* A % has been seen and ch is the character after it. */\r
-        else if (ch == 'z') {\r
-            if (zreplacement == NULL) {\r
-                /* format utcoffset */\r
-                char buf[100];\r
-                PyObject *tzinfo = get_tzinfo_member(object);\r
-                zreplacement = PyString_FromString("");\r
-                if (zreplacement == NULL) goto Done;\r
-                if (tzinfo != Py_None && tzinfo != NULL) {\r
-                    assert(tzinfoarg != NULL);\r
-                    if (format_utcoffset(buf,\r
-                                         sizeof(buf),\r
-                                         "",\r
-                                         tzinfo,\r
-                                         tzinfoarg) < 0)\r
-                        goto Done;\r
-                    Py_DECREF(zreplacement);\r
-                    zreplacement = PyString_FromString(buf);\r
-                    if (zreplacement == NULL) goto Done;\r
-                }\r
-            }\r
-            assert(zreplacement != NULL);\r
-            ptoappend = PyString_AS_STRING(zreplacement);\r
-            ntoappend = PyString_GET_SIZE(zreplacement);\r
-        }\r
-        else if (ch == 'Z') {\r
-            /* format tzname */\r
-            if (Zreplacement == NULL) {\r
-                PyObject *tzinfo = get_tzinfo_member(object);\r
-                Zreplacement = PyString_FromString("");\r
-                if (Zreplacement == NULL) goto Done;\r
-                if (tzinfo != Py_None && tzinfo != NULL) {\r
-                    PyObject *temp;\r
-                    assert(tzinfoarg != NULL);\r
-                    temp = call_tzname(tzinfo, tzinfoarg);\r
-                    if (temp == NULL) goto Done;\r
-                    if (temp != Py_None) {\r
-                        assert(PyString_Check(temp));\r
-                        /* Since the tzname is getting\r
-                         * stuffed into the format, we\r
-                         * have to double any % signs\r
-                         * so that strftime doesn't\r
-                         * treat them as format codes.\r
-                         */\r
-                        Py_DECREF(Zreplacement);\r
-                        Zreplacement = PyObject_CallMethod(\r
-                            temp, "replace",\r
-                            "ss", "%", "%%");\r
-                        Py_DECREF(temp);\r
-                        if (Zreplacement == NULL)\r
-                            goto Done;\r
-                        if (!PyString_Check(Zreplacement)) {\r
-                            PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");\r
-                            goto Done;\r
-                        }\r
-                    }\r
-                    else\r
-                        Py_DECREF(temp);\r
-                }\r
-            }\r
-            assert(Zreplacement != NULL);\r
-            ptoappend = PyString_AS_STRING(Zreplacement);\r
-            ntoappend = PyString_GET_SIZE(Zreplacement);\r
-        }\r
-        else if (ch == 'f') {\r
-            /* format microseconds */\r
-            if (freplacement == NULL) {\r
-                freplacement = make_freplacement(object);\r
-                if (freplacement == NULL)\r
-                    goto Done;\r
-            }\r
-            assert(freplacement != NULL);\r
-            assert(PyString_Check(freplacement));\r
-            ptoappend = PyString_AS_STRING(freplacement);\r
-            ntoappend = PyString_GET_SIZE(freplacement);\r
-        }\r
-        else {\r
-            /* percent followed by neither z nor Z */\r
-            ptoappend = pin - 2;\r
-            ntoappend = 2;\r
-        }\r
-\r
-        /* Append the ntoappend chars starting at ptoappend to\r
-         * the new format.\r
-         */\r
-        assert(ptoappend != NULL);\r
-        assert(ntoappend >= 0);\r
-        if (ntoappend == 0)\r
-            continue;\r
-        while (usednew + ntoappend > totalnew) {\r
-            size_t bigger = totalnew << 1;\r
-            if ((bigger >> 1) != totalnew) { /* overflow */\r
-                PyErr_NoMemory();\r
-                goto Done;\r
-            }\r
-            if (_PyString_Resize(&newfmt, bigger) < 0)\r
-                goto Done;\r
-            totalnew = bigger;\r
-            pnew = PyString_AsString(newfmt) + usednew;\r
-        }\r
-        memcpy(pnew, ptoappend, ntoappend);\r
-        pnew += ntoappend;\r
-        usednew += ntoappend;\r
-        assert(usednew <= totalnew);\r
-    }  /* end while() */\r
-\r
-    if (_PyString_Resize(&newfmt, usednew) < 0)\r
-        goto Done;\r
-    {\r
-        PyObject *time = PyImport_ImportModuleNoBlock("time");\r
-        if (time == NULL)\r
-            goto Done;\r
-        result = PyObject_CallMethod(time, "strftime", "OO",\r
-                                     newfmt, timetuple);\r
-        Py_DECREF(time);\r
-    }\r
- Done:\r
-    Py_XDECREF(freplacement);\r
-    Py_XDECREF(zreplacement);\r
-    Py_XDECREF(Zreplacement);\r
-    Py_XDECREF(newfmt);\r
-    return result;\r
-}\r
-\r
-static char *\r
-isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)\r
-{\r
-    int x;\r
-    x = PyOS_snprintf(buffer, bufflen,\r
-                      "%04d-%02d-%02d",\r
-                      GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));\r
-    assert(bufflen >= x);\r
-    return buffer + x;\r
-}\r
-\r
-static char *\r
-isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)\r
-{\r
-    int x;\r
-    int us = DATE_GET_MICROSECOND(dt);\r
-\r
-    x = PyOS_snprintf(buffer, bufflen,\r
-                      "%02d:%02d:%02d",\r
-                      DATE_GET_HOUR(dt),\r
-                      DATE_GET_MINUTE(dt),\r
-                      DATE_GET_SECOND(dt));\r
-    assert(bufflen >= x);\r
-    if (us)\r
-        x += PyOS_snprintf(buffer + x, bufflen - x, ".%06d", us);\r
-    assert(bufflen >= x);\r
-    return buffer + x;\r
-}\r
-\r
-/* ---------------------------------------------------------------------------\r
- * Wrap functions from the time module.  These aren't directly available\r
- * from C.  Perhaps they should be.\r
- */\r
-\r
-/* Call time.time() and return its result (a Python float). */\r
-static PyObject *\r
-time_time(void)\r
-{\r
-    PyObject *result = NULL;\r
-    PyObject *time = PyImport_ImportModuleNoBlock("time");\r
-\r
-    if (time != NULL) {\r
-        result = PyObject_CallMethod(time, "time", "()");\r
-        Py_DECREF(time);\r
-    }\r
-    return result;\r
-}\r
-\r
-/* Build a time.struct_time.  The weekday and day number are automatically\r
- * computed from the y,m,d args.\r
- */\r
-static PyObject *\r
-build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)\r
-{\r
-    PyObject *time;\r
-    PyObject *result = NULL;\r
-\r
-    time = PyImport_ImportModuleNoBlock("time");\r
-    if (time != NULL) {\r
-        result = PyObject_CallMethod(time, "struct_time",\r
-                                     "((iiiiiiiii))",\r
-                                     y, m, d,\r
-                                     hh, mm, ss,\r
-                                     weekday(y, m, d),\r
-                                     days_before_month(y, m) + d,\r
-                                     dstflag);\r
-        Py_DECREF(time);\r
-    }\r
-    return result;\r
-}\r
-\r
-/* ---------------------------------------------------------------------------\r
- * Miscellaneous helpers.\r
- */\r
-\r
-/* For obscure reasons, we need to use tp_richcompare instead of tp_compare.\r
- * The comparisons here all most naturally compute a cmp()-like result.\r
- * This little helper turns that into a bool result for rich comparisons.\r
- */\r
-static PyObject *\r
-diff_to_bool(int diff, int op)\r
-{\r
-    PyObject *result;\r
-    int istrue;\r
-\r
-    switch (op) {\r
-        case Py_EQ: istrue = diff == 0; break;\r
-        case Py_NE: istrue = diff != 0; break;\r
-        case Py_LE: istrue = diff <= 0; break;\r
-        case Py_GE: istrue = diff >= 0; break;\r
-        case Py_LT: istrue = diff < 0; break;\r
-        case Py_GT: istrue = diff > 0; break;\r
-        default:\r
-            assert(! "op unknown");\r
-            istrue = 0; /* To shut up compiler */\r
-    }\r
-    result = istrue ? Py_True : Py_False;\r
-    Py_INCREF(result);\r
-    return result;\r
-}\r
-\r
-/* Raises a "can't compare" TypeError and returns NULL. */\r
-static PyObject *\r
-cmperror(PyObject *a, PyObject *b)\r
-{\r
-    PyErr_Format(PyExc_TypeError,\r
-                 "can't compare %s to %s",\r
-                 Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);\r
-    return NULL;\r
-}\r
-\r
-/* ---------------------------------------------------------------------------\r
- * Cached Python objects; these are set by the module init function.\r
- */\r
-\r
-/* Conversion factors. */\r
-static PyObject *us_per_us = NULL;      /* 1 */\r
-static PyObject *us_per_ms = NULL;      /* 1000 */\r
-static PyObject *us_per_second = NULL;  /* 1000000 */\r
-static PyObject *us_per_minute = NULL;  /* 1e6 * 60 as Python int */\r
-static PyObject *us_per_hour = NULL;    /* 1e6 * 3600 as Python long */\r
-static PyObject *us_per_day = NULL;     /* 1e6 * 3600 * 24 as Python long */\r
-static PyObject *us_per_week = NULL;    /* 1e6*3600*24*7 as Python long */\r
-static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */\r
-\r
-/* ---------------------------------------------------------------------------\r
- * Class implementations.\r
- */\r
-\r
-/*\r
- * PyDateTime_Delta implementation.\r
- */\r
-\r
-/* Convert a timedelta to a number of us,\r
- *      (24*3600*self.days + self.seconds)*1000000 + self.microseconds\r
- * as a Python int or long.\r
- * Doing mixed-radix arithmetic by hand instead is excruciating in C,\r
- * due to ubiquitous overflow possibilities.\r
- */\r
-static PyObject *\r
-delta_to_microseconds(PyDateTime_Delta *self)\r
-{\r
-    PyObject *x1 = NULL;\r
-    PyObject *x2 = NULL;\r
-    PyObject *x3 = NULL;\r
-    PyObject *result = NULL;\r
-\r
-    x1 = PyInt_FromLong(GET_TD_DAYS(self));\r
-    if (x1 == NULL)\r
-        goto Done;\r
-    x2 = PyNumber_Multiply(x1, seconds_per_day);        /* days in seconds */\r
-    if (x2 == NULL)\r
-        goto Done;\r
-    Py_DECREF(x1);\r
-    x1 = NULL;\r
-\r
-    /* x2 has days in seconds */\r
-    x1 = PyInt_FromLong(GET_TD_SECONDS(self));          /* seconds */\r
-    if (x1 == NULL)\r
-        goto Done;\r
-    x3 = PyNumber_Add(x1, x2);          /* days and seconds in seconds */\r
-    if (x3 == NULL)\r
-        goto Done;\r
-    Py_DECREF(x1);\r
-    Py_DECREF(x2);\r
-    x2 = NULL;\r
-\r
-    /* x3 has days+seconds in seconds */\r
-    x1 = PyNumber_Multiply(x3, us_per_second);          /* us */\r
-    if (x1 == NULL)\r
-        goto Done;\r
-    Py_DECREF(x3);\r
-    x3 = NULL;\r
-\r
-    /* x1 has days+seconds in us */\r
-    x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));\r
-    if (x2 == NULL)\r
-        goto Done;\r
-    result = PyNumber_Add(x1, x2);\r
-\r
-Done:\r
-    Py_XDECREF(x1);\r
-    Py_XDECREF(x2);\r
-    Py_XDECREF(x3);\r
-    return result;\r
-}\r
-\r
-/* Convert a number of us (as a Python int or long) to a timedelta.\r
- */\r
-static PyObject *\r
-microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)\r
-{\r
-    int us;\r
-    int s;\r
-    int d;\r
-    long temp;\r
-\r
-    PyObject *tuple = NULL;\r
-    PyObject *num = NULL;\r
-    PyObject *result = NULL;\r
-\r
-    tuple = PyNumber_Divmod(pyus, us_per_second);\r
-    if (tuple == NULL)\r
-        goto Done;\r
-\r
-    num = PyTuple_GetItem(tuple, 1);            /* us */\r
-    if (num == NULL)\r
-        goto Done;\r
-    temp = PyLong_AsLong(num);\r
-    num = NULL;\r
-    if (temp == -1 && PyErr_Occurred())\r
-        goto Done;\r
-    assert(0 <= temp && temp < 1000000);\r
-    us = (int)temp;\r
-    if (us < 0) {\r
-        /* The divisor was positive, so this must be an error. */\r
-        assert(PyErr_Occurred());\r
-        goto Done;\r
-    }\r
-\r
-    num = PyTuple_GetItem(tuple, 0);            /* leftover seconds */\r
-    if (num == NULL)\r
-        goto Done;\r
-    Py_INCREF(num);\r
-    Py_DECREF(tuple);\r
-\r
-    tuple = PyNumber_Divmod(num, seconds_per_day);\r
-    if (tuple == NULL)\r
-        goto Done;\r
-    Py_DECREF(num);\r
-\r
-    num = PyTuple_GetItem(tuple, 1);            /* seconds */\r
-    if (num == NULL)\r
-        goto Done;\r
-    temp = PyLong_AsLong(num);\r
-    num = NULL;\r
-    if (temp == -1 && PyErr_Occurred())\r
-        goto Done;\r
-    assert(0 <= temp && temp < 24*3600);\r
-    s = (int)temp;\r
-\r
-    if (s < 0) {\r
-        /* The divisor was positive, so this must be an error. */\r
-        assert(PyErr_Occurred());\r
-        goto Done;\r
-    }\r
-\r
-    num = PyTuple_GetItem(tuple, 0);            /* leftover days */\r
-    if (num == NULL)\r
-        goto Done;\r
-    Py_INCREF(num);\r
-    temp = PyLong_AsLong(num);\r
-    if (temp == -1 && PyErr_Occurred())\r
-        goto Done;\r
-    d = (int)temp;\r
-    if ((long)d != temp) {\r
-        PyErr_SetString(PyExc_OverflowError, "normalized days too "\r
-                        "large to fit in a C int");\r
-        goto Done;\r
-    }\r
-    result = new_delta_ex(d, s, us, 0, type);\r
-\r
-Done:\r
-    Py_XDECREF(tuple);\r
-    Py_XDECREF(num);\r
-    return result;\r
-}\r
-\r
-#define microseconds_to_delta(pymicros) \\r
-    microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)\r
-\r
-static PyObject *\r
-multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)\r
-{\r
-    PyObject *pyus_in;\r
-    PyObject *pyus_out;\r
-    PyObject *result;\r
-\r
-    pyus_in = delta_to_microseconds(delta);\r
-    if (pyus_in == NULL)\r
-        return NULL;\r
-\r
-    pyus_out = PyNumber_Multiply(pyus_in, intobj);\r
-    Py_DECREF(pyus_in);\r
-    if (pyus_out == NULL)\r
-        return NULL;\r
-\r
-    result = microseconds_to_delta(pyus_out);\r
-    Py_DECREF(pyus_out);\r
-    return result;\r
-}\r
-\r
-static PyObject *\r
-divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)\r
-{\r
-    PyObject *pyus_in;\r
-    PyObject *pyus_out;\r
-    PyObject *result;\r
-\r
-    pyus_in = delta_to_microseconds(delta);\r
-    if (pyus_in == NULL)\r
-        return NULL;\r
-\r
-    pyus_out = PyNumber_FloorDivide(pyus_in, intobj);\r
-    Py_DECREF(pyus_in);\r
-    if (pyus_out == NULL)\r
-        return NULL;\r
-\r
-    result = microseconds_to_delta(pyus_out);\r
-    Py_DECREF(pyus_out);\r
-    return result;\r
-}\r
-\r
-static PyObject *\r
-delta_add(PyObject *left, PyObject *right)\r
-{\r
-    PyObject *result = Py_NotImplemented;\r
-\r
-    if (PyDelta_Check(left) && PyDelta_Check(right)) {\r
-        /* delta + delta */\r
-        /* The C-level additions can't overflow because of the\r
-         * invariant bounds.\r
-         */\r
-        int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);\r
-        int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);\r
-        int microseconds = GET_TD_MICROSECONDS(left) +\r
-                           GET_TD_MICROSECONDS(right);\r
-        result = new_delta(days, seconds, microseconds, 1);\r
-    }\r
-\r
-    if (result == Py_NotImplemented)\r
-        Py_INCREF(result);\r
-    return result;\r
-}\r
-\r
-static PyObject *\r
-delta_negative(PyDateTime_Delta *self)\r
-{\r
-    return new_delta(-GET_TD_DAYS(self),\r
-                     -GET_TD_SECONDS(self),\r
-                     -GET_TD_MICROSECONDS(self),\r
-                     1);\r
-}\r
-\r
-static PyObject *\r
-delta_positive(PyDateTime_Delta *self)\r
-{\r
-    /* Could optimize this (by returning self) if this isn't a\r
-     * subclass -- but who uses unary + ?  Approximately nobody.\r
-     */\r
-    return new_delta(GET_TD_DAYS(self),\r
-                     GET_TD_SECONDS(self),\r
-                     GET_TD_MICROSECONDS(self),\r
-                     0);\r
-}\r
-\r
-static PyObject *\r
-delta_abs(PyDateTime_Delta *self)\r
-{\r
-    PyObject *result;\r
-\r
-    assert(GET_TD_MICROSECONDS(self) >= 0);\r
-    assert(GET_TD_SECONDS(self) >= 0);\r
-\r
-    if (GET_TD_DAYS(self) < 0)\r
-        result = delta_negative(self);\r
-    else\r
-        result = delta_positive(self);\r
-\r
-    return result;\r
-}\r
-\r
-static PyObject *\r
-delta_subtract(PyObject *left, PyObject *right)\r
-{\r
-    PyObject *result = Py_NotImplemented;\r
-\r
-    if (PyDelta_Check(left) && PyDelta_Check(right)) {\r
-        /* delta - delta */\r
-        /* The C-level additions can't overflow because of the\r
-         * invariant bounds.\r
-         */\r
-        int days = GET_TD_DAYS(left) - GET_TD_DAYS(right);\r
-        int seconds = GET_TD_SECONDS(left) - GET_TD_SECONDS(right);\r
-        int microseconds = GET_TD_MICROSECONDS(left) -\r
-                           GET_TD_MICROSECONDS(right);\r
-        result = new_delta(days, seconds, microseconds, 1);\r
-    }\r
-\r
-    if (result == Py_NotImplemented)\r
-        Py_INCREF(result);\r
-    return result;\r
-}\r
-\r
-/* This is more natural as a tp_compare, but doesn't work then:  for whatever\r
- * reason, Python's try_3way_compare ignores tp_compare unless\r
- * PyInstance_Check returns true, but these aren't old-style classes.\r
- */\r
-static PyObject *\r
-delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)\r
-{\r
-    int diff = 42;      /* nonsense */\r
-\r
-    if (PyDelta_Check(other)) {\r
-        diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);\r
-        if (diff == 0) {\r
-            diff = GET_TD_SECONDS(self) - GET_TD_SECONDS(other);\r
-            if (diff == 0)\r
-                diff = GET_TD_MICROSECONDS(self) -\r
-                       GET_TD_MICROSECONDS(other);\r
-        }\r
-    }\r
-    else if (op == Py_EQ || op == Py_NE)\r
-        diff = 1;               /* any non-zero value will do */\r
-\r
-    else /* stop this from falling back to address comparison */\r
-        return cmperror((PyObject *)self, other);\r
-\r
-    return diff_to_bool(diff, op);\r
-}\r
-\r
-static PyObject *delta_getstate(PyDateTime_Delta *self);\r
-\r
-static long\r
-delta_hash(PyDateTime_Delta *self)\r
-{\r
-    if (self->hashcode == -1) {\r
-        PyObject *temp = delta_getstate(self);\r
-        if (temp != NULL) {\r
-            self->hashcode = PyObject_Hash(temp);\r
-            Py_DECREF(temp);\r
-        }\r
-    }\r
-    return self->hashcode;\r
-}\r
-\r
-static PyObject *\r
-delta_multiply(PyObject *left, PyObject *right)\r
-{\r
-    PyObject *result = Py_NotImplemented;\r
-\r
-    if (PyDelta_Check(left)) {\r
-        /* delta * ??? */\r
-        if (PyInt_Check(right) || PyLong_Check(right))\r
-            result = multiply_int_timedelta(right,\r
-                            (PyDateTime_Delta *) left);\r
-    }\r
-    else if (PyInt_Check(left) || PyLong_Check(left))\r
-        result = multiply_int_timedelta(left,\r
-                                        (PyDateTime_Delta *) right);\r
-\r
-    if (result == Py_NotImplemented)\r
-        Py_INCREF(result);\r
-    return result;\r
-}\r
-\r
-static PyObject *\r
-delta_divide(PyObject *left, PyObject *right)\r
-{\r
-    PyObject *result = Py_NotImplemented;\r
-\r
-    if (PyDelta_Check(left)) {\r
-        /* delta * ??? */\r
-        if (PyInt_Check(right) || PyLong_Check(right))\r
-            result = divide_timedelta_int(\r
-                            (PyDateTime_Delta *)left,\r
-                            right);\r
-    }\r
-\r
-    if (result == Py_NotImplemented)\r
-        Py_INCREF(result);\r
-    return result;\r
-}\r
-\r
-/* Fold in the value of the tag ("seconds", "weeks", etc) component of a\r
- * timedelta constructor.  sofar is the # of microseconds accounted for\r
- * so far, and there are factor microseconds per current unit, the number\r
- * of which is given by num.  num * factor is added to sofar in a\r
- * numerically careful way, and that's the result.  Any fractional\r
- * microseconds left over (this can happen if num is a float type) are\r
- * added into *leftover.\r
- * Note that there are many ways this can give an error (NULL) return.\r
- */\r
-static PyObject *\r
-accum(const char* tag, PyObject *sofar, PyObject *num, PyObject *factor,\r
-      double *leftover)\r
-{\r
-    PyObject *prod;\r
-    PyObject *sum;\r
-\r
-    assert(num != NULL);\r
-\r
-    if (PyInt_Check(num) || PyLong_Check(num)) {\r
-        prod = PyNumber_Multiply(num, factor);\r
-        if (prod == NULL)\r
-            return NULL;\r
-        sum = PyNumber_Add(sofar, prod);\r
-        Py_DECREF(prod);\r
-        return sum;\r
-    }\r
-\r
-    if (PyFloat_Check(num)) {\r
-        double dnum;\r
-        double fracpart;\r
-        double intpart;\r
-        PyObject *x;\r
-        PyObject *y;\r
-\r
-        /* The Plan:  decompose num into an integer part and a\r
-         * fractional part, num = intpart + fracpart.\r
-         * Then num * factor ==\r
-         *      intpart * factor + fracpart * factor\r
-         * and the LHS can be computed exactly in long arithmetic.\r
-         * The RHS is again broken into an int part and frac part.\r
-         * and the frac part is added into *leftover.\r
-         */\r
-        dnum = PyFloat_AsDouble(num);\r
-        if (dnum == -1.0 && PyErr_Occurred())\r
-            return NULL;\r
-        fracpart = modf(dnum, &intpart);\r
-        x = PyLong_FromDouble(intpart);\r
-        if (x == NULL)\r
-            return NULL;\r
-\r
-        prod = PyNumber_Multiply(x, factor);\r
-        Py_DECREF(x);\r
-        if (prod == NULL)\r
-            return NULL;\r
-\r
-        sum = PyNumber_Add(sofar, prod);\r
-        Py_DECREF(prod);\r
-        if (sum == NULL)\r
-            return NULL;\r
-\r
-        if (fracpart == 0.0)\r
-            return sum;\r
-        /* So far we've lost no information.  Dealing with the\r
-         * fractional part requires float arithmetic, and may\r
-         * lose a little info.\r
-         */\r
-        assert(PyInt_Check(factor) || PyLong_Check(factor));\r
-        if (PyInt_Check(factor))\r
-            dnum = (double)PyInt_AsLong(factor);\r
-        else\r
-            dnum = PyLong_AsDouble(factor);\r
-\r
-        dnum *= fracpart;\r
-        fracpart = modf(dnum, &intpart);\r
-        x = PyLong_FromDouble(intpart);\r
-        if (x == NULL) {\r
-            Py_DECREF(sum);\r
-            return NULL;\r
-        }\r
-\r
-        y = PyNumber_Add(sum, x);\r
-        Py_DECREF(sum);\r
-        Py_DECREF(x);\r
-        *leftover += fracpart;\r
-        return y;\r
-    }\r
-\r
-    PyErr_Format(PyExc_TypeError,\r
-                 "unsupported type for timedelta %s component: %s",\r
-                 tag, Py_TYPE(num)->tp_name);\r
-    return NULL;\r
-}\r
-\r
-static PyObject *\r
-delta_new(PyTypeObject *type, PyObject *args, PyObject *kw)\r
-{\r
-    PyObject *self = NULL;\r
-\r
-    /* Argument objects. */\r
-    PyObject *day = NULL;\r
-    PyObject *second = NULL;\r
-    PyObject *us = NULL;\r
-    PyObject *ms = NULL;\r
-    PyObject *minute = NULL;\r
-    PyObject *hour = NULL;\r
-    PyObject *week = NULL;\r
-\r
-    PyObject *x = NULL;         /* running sum of microseconds */\r
-    PyObject *y = NULL;         /* temp sum of microseconds */\r
-    double leftover_us = 0.0;\r
-\r
-    static char *keywords[] = {\r
-        "days", "seconds", "microseconds", "milliseconds",\r
-        "minutes", "hours", "weeks", NULL\r
-    };\r
-\r
-    if (PyArg_ParseTupleAndKeywords(args, kw, "|OOOOOOO:__new__",\r
-                                    keywords,\r
-                                    &day, &second, &us,\r
-                                    &ms, &minute, &hour, &week) == 0)\r
-        goto Done;\r
-\r
-    x = PyInt_FromLong(0);\r
-    if (x == NULL)\r
-        goto Done;\r
-\r
-#define CLEANUP         \\r
-    Py_DECREF(x);       \\r
-    x = y;              \\r
-    if (x == NULL)      \\r
-        goto Done\r
-\r
-    if (us) {\r
-        y = accum("microseconds", x, us, us_per_us, &leftover_us);\r
-        CLEANUP;\r
-    }\r
-    if (ms) {\r
-        y = accum("milliseconds", x, ms, us_per_ms, &leftover_us);\r
-        CLEANUP;\r
-    }\r
-    if (second) {\r
-        y = accum("seconds", x, second, us_per_second, &leftover_us);\r
-        CLEANUP;\r
-    }\r
-    if (minute) {\r
-        y = accum("minutes", x, minute, us_per_minute, &leftover_us);\r
-        CLEANUP;\r
-    }\r
-    if (hour) {\r
-        y = accum("hours", x, hour, us_per_hour, &leftover_us);\r
-        CLEANUP;\r
-    }\r
-    if (day) {\r
-        y = accum("days", x, day, us_per_day, &leftover_us);\r
-        CLEANUP;\r
-    }\r
-    if (week) {\r
-        y = accum("weeks", x, week, us_per_week, &leftover_us);\r
-        CLEANUP;\r
-    }\r
-    if (leftover_us) {\r
-        /* Round to nearest whole # of us, and add into x. */\r
-        PyObject *temp = PyLong_FromLong(round_to_long(leftover_us));\r
-        if (temp == NULL) {\r
-            Py_DECREF(x);\r
-            goto Done;\r
-        }\r
-        y = PyNumber_Add(x, temp);\r
-        Py_DECREF(temp);\r
-        CLEANUP;\r
-    }\r
-\r
-    self = microseconds_to_delta_ex(x, type);\r
-    Py_DECREF(x);\r
-Done:\r
-    return self;\r
-\r
-#undef CLEANUP\r
-}\r
-\r
-static int\r
-delta_nonzero(PyDateTime_Delta *self)\r
-{\r
-    return (GET_TD_DAYS(self) != 0\r
-        || GET_TD_SECONDS(self) != 0\r
-        || GET_TD_MICROSECONDS(self) != 0);\r
-}\r
-\r
-static PyObject *\r
-delta_repr(PyDateTime_Delta *self)\r
-{\r
-    if (GET_TD_MICROSECONDS(self) != 0)\r
-        return PyString_FromFormat("%s(%d, %d, %d)",\r
-                                   Py_TYPE(self)->tp_name,\r
-                                   GET_TD_DAYS(self),\r
-                                   GET_TD_SECONDS(self),\r
-                                   GET_TD_MICROSECONDS(self));\r
-    if (GET_TD_SECONDS(self) != 0)\r
-        return PyString_FromFormat("%s(%d, %d)",\r
-                                   Py_TYPE(self)->tp_name,\r
-                                   GET_TD_DAYS(self),\r
-                                   GET_TD_SECONDS(self));\r
-\r
-    return PyString_FromFormat("%s(%d)",\r
-                               Py_TYPE(self)->tp_name,\r
-                               GET_TD_DAYS(self));\r
-}\r
-\r
-static PyObject *\r
-delta_str(PyDateTime_Delta *self)\r
-{\r
-    int days = GET_TD_DAYS(self);\r
-    int seconds = GET_TD_SECONDS(self);\r
-    int us = GET_TD_MICROSECONDS(self);\r
-    int hours;\r
-    int minutes;\r
-    char buf[100];\r
-    char *pbuf = buf;\r
-    size_t buflen = sizeof(buf);\r
-    int n;\r
-\r
-    minutes = divmod(seconds, 60, &seconds);\r
-    hours = divmod(minutes, 60, &minutes);\r
-\r
-    if (days) {\r
-        n = PyOS_snprintf(pbuf, buflen, "%d day%s, ", days,\r
-                          (days == 1 || days == -1) ? "" : "s");\r
-        if (n < 0 || (size_t)n >= buflen)\r
-            goto Fail;\r
-        pbuf += n;\r
-        buflen -= (size_t)n;\r
-    }\r
-\r
-    n = PyOS_snprintf(pbuf, buflen, "%d:%02d:%02d",\r
-                      hours, minutes, seconds);\r
-    if (n < 0 || (size_t)n >= buflen)\r
-        goto Fail;\r
-    pbuf += n;\r
-    buflen -= (size_t)n;\r
-\r
-    if (us) {\r
-        n = PyOS_snprintf(pbuf, buflen, ".%06d", us);\r
-        if (n < 0 || (size_t)n >= buflen)\r
-            goto Fail;\r
-        pbuf += n;\r
-    }\r
-\r
-    return PyString_FromStringAndSize(buf, pbuf - buf);\r
-\r
- Fail:\r
-    PyErr_SetString(PyExc_SystemError, "goofy result from PyOS_snprintf");\r
-    return NULL;\r
-}\r
-\r
-/* Pickle support, a simple use of __reduce__. */\r
-\r
-/* __getstate__ isn't exposed */\r
-static PyObject *\r
-delta_getstate(PyDateTime_Delta *self)\r
-{\r
-    return Py_BuildValue("iii", GET_TD_DAYS(self),\r
-                                GET_TD_SECONDS(self),\r
-                                GET_TD_MICROSECONDS(self));\r
-}\r
-\r
-static PyObject *\r
-delta_total_seconds(PyObject *self)\r
-{\r
-    PyObject *total_seconds;\r
-    PyObject *total_microseconds;\r
-    PyObject *one_million;\r
-\r
-    total_microseconds = delta_to_microseconds((PyDateTime_Delta *)self);\r
-    if (total_microseconds == NULL)\r
-        return NULL;\r
-\r
-    one_million = PyLong_FromLong(1000000L);\r
-    if (one_million == NULL) {\r
-        Py_DECREF(total_microseconds);\r
-        return NULL;\r
-    }\r
-\r
-    total_seconds = PyNumber_TrueDivide(total_microseconds, one_million);\r
-\r
-    Py_DECREF(total_microseconds);\r
-    Py_DECREF(one_million);\r
-    return total_seconds;\r
-}\r
-\r
-static PyObject *\r
-delta_reduce(PyDateTime_Delta* self)\r
-{\r
-    return Py_BuildValue("ON", Py_TYPE(self), delta_getstate(self));\r
-}\r
-\r
-#define OFFSET(field)  offsetof(PyDateTime_Delta, field)\r
-\r
-static PyMemberDef delta_members[] = {\r
-\r
-    {"days",         T_INT, OFFSET(days),         READONLY,\r
-     PyDoc_STR("Number of days.")},\r
-\r
-    {"seconds",      T_INT, OFFSET(seconds),      READONLY,\r
-     PyDoc_STR("Number of seconds (>= 0 and less than 1 day).")},\r
-\r
-    {"microseconds", T_INT, OFFSET(microseconds), READONLY,\r
-     PyDoc_STR("Number of microseconds (>= 0 and less than 1 second).")},\r
-    {NULL}\r
-};\r
-\r
-static PyMethodDef delta_methods[] = {\r
-    {"total_seconds", (PyCFunction)delta_total_seconds, METH_NOARGS,\r
-     PyDoc_STR("Total seconds in the duration.")},\r
-\r
-    {"__reduce__", (PyCFunction)delta_reduce, METH_NOARGS,\r
-     PyDoc_STR("__reduce__() -> (cls, state)")},\r
-\r
-    {NULL,      NULL},\r
-};\r
-\r
-static char delta_doc[] =\r
-PyDoc_STR("Difference between two datetime values.");\r
-\r
-static PyNumberMethods delta_as_number = {\r
-    delta_add,                                  /* nb_add */\r
-    delta_subtract,                             /* nb_subtract */\r
-    delta_multiply,                             /* nb_multiply */\r
-    delta_divide,                               /* nb_divide */\r
-    0,                                          /* nb_remainder */\r
-    0,                                          /* nb_divmod */\r
-    0,                                          /* nb_power */\r
-    (unaryfunc)delta_negative,                  /* nb_negative */\r
-    (unaryfunc)delta_positive,                  /* nb_positive */\r
-    (unaryfunc)delta_abs,                       /* nb_absolute */\r
-    (inquiry)delta_nonzero,                     /* nb_nonzero */\r
-    0,                                          /*nb_invert*/\r
-    0,                                          /*nb_lshift*/\r
-    0,                                          /*nb_rshift*/\r
-    0,                                          /*nb_and*/\r
-    0,                                          /*nb_xor*/\r
-    0,                                          /*nb_or*/\r
-    0,                                          /*nb_coerce*/\r
-    0,                                          /*nb_int*/\r
-    0,                                          /*nb_long*/\r
-    0,                                          /*nb_float*/\r
-    0,                                          /*nb_oct*/\r
-    0,                                          /*nb_hex*/\r
-    0,                                          /*nb_inplace_add*/\r
-    0,                                          /*nb_inplace_subtract*/\r
-    0,                                          /*nb_inplace_multiply*/\r
-    0,                                          /*nb_inplace_divide*/\r
-    0,                                          /*nb_inplace_remainder*/\r
-    0,                                          /*nb_inplace_power*/\r
-    0,                                          /*nb_inplace_lshift*/\r
-    0,                                          /*nb_inplace_rshift*/\r
-    0,                                          /*nb_inplace_and*/\r
-    0,                                          /*nb_inplace_xor*/\r
-    0,                                          /*nb_inplace_or*/\r
-    delta_divide,                               /* nb_floor_divide */\r
-    0,                                          /* nb_true_divide */\r
-    0,                                          /* nb_inplace_floor_divide */\r
-    0,                                          /* nb_inplace_true_divide */\r
-};\r
-\r
-static PyTypeObject PyDateTime_DeltaType = {\r
-    PyVarObject_HEAD_INIT(NULL, 0)\r
-    "datetime.timedelta",                               /* tp_name */\r
-    sizeof(PyDateTime_Delta),                           /* tp_basicsize */\r
-    0,                                                  /* tp_itemsize */\r
-    0,                                                  /* tp_dealloc */\r
-    0,                                                  /* tp_print */\r
-    0,                                                  /* tp_getattr */\r
-    0,                                                  /* tp_setattr */\r
-    0,                                                  /* tp_compare */\r
-    (reprfunc)delta_repr,                               /* tp_repr */\r
-    &delta_as_number,                                   /* tp_as_number */\r
-    0,                                                  /* tp_as_sequence */\r
-    0,                                                  /* tp_as_mapping */\r
-    (hashfunc)delta_hash,                               /* tp_hash */\r
-    0,                                                  /* tp_call */\r
-    (reprfunc)delta_str,                                /* tp_str */\r
-    PyObject_GenericGetAttr,                            /* tp_getattro */\r
-    0,                                                  /* tp_setattro */\r
-    0,                                                  /* tp_as_buffer */\r
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |\r
-        Py_TPFLAGS_BASETYPE,                            /* tp_flags */\r
-    delta_doc,                                          /* tp_doc */\r
-    0,                                                  /* tp_traverse */\r
-    0,                                                  /* tp_clear */\r
-    (richcmpfunc)delta_richcompare,                     /* tp_richcompare */\r
-    0,                                                  /* tp_weaklistoffset */\r
-    0,                                                  /* tp_iter */\r
-    0,                                                  /* tp_iternext */\r
-    delta_methods,                                      /* tp_methods */\r
-    delta_members,                                      /* tp_members */\r
-    0,                                                  /* tp_getset */\r
-    0,                                                  /* tp_base */\r
-    0,                                                  /* tp_dict */\r
-    0,                                                  /* tp_descr_get */\r
-    0,                                                  /* tp_descr_set */\r
-    0,                                                  /* tp_dictoffset */\r
-    0,                                                  /* tp_init */\r
-    0,                                                  /* tp_alloc */\r
-    delta_new,                                          /* tp_new */\r
-    0,                                                  /* tp_free */\r
-};\r
-\r
-/*\r
- * PyDateTime_Date implementation.\r
- */\r
-\r
-/* Accessor properties. */\r
-\r
-static PyObject *\r
-date_year(PyDateTime_Date *self, void *unused)\r
-{\r
-    return PyInt_FromLong(GET_YEAR(self));\r
-}\r
-\r
-static PyObject *\r
-date_month(PyDateTime_Date *self, void *unused)\r
-{\r
-    return PyInt_FromLong(GET_MONTH(self));\r
-}\r
-\r
-static PyObject *\r
-date_day(PyDateTime_Date *self, void *unused)\r
-{\r
-    return PyInt_FromLong(GET_DAY(self));\r
-}\r
-\r
-static PyGetSetDef date_getset[] = {\r
-    {"year",        (getter)date_year},\r
-    {"month",       (getter)date_month},\r
-    {"day",         (getter)date_day},\r
-    {NULL}\r
-};\r
-\r
-/* Constructors. */\r
-\r
-static char *date_kws[] = {"year", "month", "day", NULL};\r
-\r
-static PyObject *\r
-date_new(PyTypeObject *type, PyObject *args, PyObject *kw)\r
-{\r
-    PyObject *self = NULL;\r
-    PyObject *state;\r
-    int year;\r
-    int month;\r
-    int day;\r
-\r
-    /* Check for invocation from pickle with __getstate__ state */\r
-    if (PyTuple_GET_SIZE(args) == 1 &&\r
-        PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&\r
-        PyString_GET_SIZE(state) == _PyDateTime_DATE_DATASIZE &&\r
-        MONTH_IS_SANE(PyString_AS_STRING(state)[2]))\r
-    {\r
-        PyDateTime_Date *me;\r
-\r
-        me = (PyDateTime_Date *) (type->tp_alloc(type, 0));\r
-        if (me != NULL) {\r
-            char *pdata = PyString_AS_STRING(state);\r
-            memcpy(me->data, pdata, _PyDateTime_DATE_DATASIZE);\r
-            me->hashcode = -1;\r
-        }\r
-        return (PyObject *)me;\r
-    }\r
-\r
-    if (PyArg_ParseTupleAndKeywords(args, kw, "iii", date_kws,\r
-                                    &year, &month, &day)) {\r
-        if (check_date_args(year, month, day) < 0)\r
-            return NULL;\r
-        self = new_date_ex(year, month, day, type);\r
-    }\r
-    return self;\r
-}\r
-\r
-/* Return new date from localtime(t). */\r
-static PyObject *\r
-date_local_from_time_t(PyObject *cls, double ts)\r
-{\r
-    struct tm *tm;\r
-    time_t t;\r
-    PyObject *result = NULL;\r
-\r
-    t = _PyTime_DoubleToTimet(ts);\r
-    if (t == (time_t)-1 && PyErr_Occurred())\r
-        return NULL;\r
-    tm = localtime(&t);\r
-    if (tm)\r
-        result = PyObject_CallFunction(cls, "iii",\r
-                                       tm->tm_year + 1900,\r
-                                       tm->tm_mon + 1,\r
-                                       tm->tm_mday);\r
-    else\r
-        PyErr_SetString(PyExc_ValueError,\r
-                        "timestamp out of range for "\r
-                        "platform localtime() function");\r
-    return result;\r
-}\r
-\r
-/* Return new date from current time.\r
- * We say this is equivalent to fromtimestamp(time.time()), and the\r
- * only way to be sure of that is to *call* time.time().  That's not\r
- * generally the same as calling C's time.\r
- */\r
-static PyObject *\r
-date_today(PyObject *cls, PyObject *dummy)\r
-{\r
-    PyObject *time;\r
-    PyObject *result;\r
-\r
-    time = time_time();\r
-    if (time == NULL)\r
-        return NULL;\r
-\r
-    /* Note well:  today() is a class method, so this may not call\r
-     * date.fromtimestamp.  For example, it may call\r
-     * datetime.fromtimestamp.  That's why we need all the accuracy\r
-     * time.time() delivers; if someone were gonzo about optimization,\r
-     * date.today() could get away with plain C time().\r
-     */\r
-    result = PyObject_CallMethod(cls, "fromtimestamp", "O", time);\r
-    Py_DECREF(time);\r
-    return result;\r
-}\r
-\r
-/* Return new date from given timestamp (Python timestamp -- a double). */\r
-static PyObject *\r
-date_fromtimestamp(PyObject *cls, PyObject *args)\r
-{\r
-    double timestamp;\r
-    PyObject *result = NULL;\r
-\r
-    if (PyArg_ParseTuple(args, "d:fromtimestamp", &timestamp))\r
-        result = date_local_from_time_t(cls, timestamp);\r
-    return result;\r
-}\r
-\r
-/* Return new date from proleptic Gregorian ordinal.  Raises ValueError if\r
- * the ordinal is out of range.\r
- */\r
-static PyObject *\r
-date_fromordinal(PyObject *cls, PyObject *args)\r
-{\r
-    PyObject *result = NULL;\r
-    int ordinal;\r
-\r
-    if (PyArg_ParseTuple(args, "i:fromordinal", &ordinal)) {\r
-        int year;\r
-        int month;\r
-        int day;\r
-\r
-        if (ordinal < 1)\r
-            PyErr_SetString(PyExc_ValueError, "ordinal must be "\r
-                                              ">= 1");\r
-        else {\r
-            ord_to_ymd(ordinal, &year, &month, &day);\r
-            result = PyObject_CallFunction(cls, "iii",\r
-                                           year, month, day);\r
-        }\r
-    }\r
-    return result;\r
-}\r
-\r
-/*\r
- * Date arithmetic.\r
- */\r
-\r
-/* date + timedelta -> date.  If arg negate is true, subtract the timedelta\r
- * instead.\r
- */\r
-static PyObject *\r
-add_date_timedelta(PyDateTime_Date *date, PyDateTime_Delta *delta, int negate)\r
-{\r
-    PyObject *result = NULL;\r
-    int year = GET_YEAR(date);\r
-    int month = GET_MONTH(date);\r
-    int deltadays = GET_TD_DAYS(delta);\r
-    /* C-level overflow is impossible because |deltadays| < 1e9. */\r
-    int day = GET_DAY(date) + (negate ? -deltadays : deltadays);\r
-\r
-    if (normalize_date(&year, &month, &day) >= 0)\r
-        result = new_date(year, month, day);\r
-    return result;\r
-}\r
-\r
-static PyObject *\r
-date_add(PyObject *left, PyObject *right)\r
-{\r
-    if (PyDateTime_Check(left) || PyDateTime_Check(right)) {\r
-        Py_INCREF(Py_NotImplemented);\r
-        return Py_NotImplemented;\r
-    }\r
-    if (PyDate_Check(left)) {\r
-        /* date + ??? */\r
-        if (PyDelta_Check(right))\r
-            /* date + delta */\r
-            return add_date_timedelta((PyDateTime_Date *) left,\r
-                                      (PyDateTime_Delta *) right,\r
-                                      0);\r
-    }\r
-    else {\r
-        /* ??? + date\r
-         * 'right' must be one of us, or we wouldn't have been called\r
-         */\r
-        if (PyDelta_Check(left))\r
-            /* delta + date */\r
-            return add_date_timedelta((PyDateTime_Date *) right,\r
-                                      (PyDateTime_Delta *) left,\r
-                                      0);\r
-    }\r
-    Py_INCREF(Py_NotImplemented);\r
-    return Py_NotImplemented;\r
-}\r
-\r
-static PyObject *\r
-date_subtract(PyObject *left, PyObject *right)\r
-{\r
-    if (PyDateTime_Check(left) || PyDateTime_Check(right)) {\r
-        Py_INCREF(Py_NotImplemented);\r
-        return Py_NotImplemented;\r
-    }\r
-    if (PyDate_Check(left)) {\r
-        if (PyDate_Check(right)) {\r
-            /* date - date */\r
-            int left_ord = ymd_to_ord(GET_YEAR(left),\r
-                                      GET_MONTH(left),\r
-                                      GET_DAY(left));\r
-            int right_ord = ymd_to_ord(GET_YEAR(right),\r
-                                       GET_MONTH(right),\r
-                                       GET_DAY(right));\r
-            return new_delta(left_ord - right_ord, 0, 0, 0);\r
-        }\r
-        if (PyDelta_Check(right)) {\r
-            /* date - delta */\r
-            return add_date_timedelta((PyDateTime_Date *) left,\r
-                                      (PyDateTime_Delta *) right,\r
-                                      1);\r
-        }\r
-    }\r
-    Py_INCREF(Py_NotImplemented);\r
-    return Py_NotImplemented;\r
-}\r
-\r
-\r
-/* Various ways to turn a date into a string. */\r
-\r
-static PyObject *\r
-date_repr(PyDateTime_Date *self)\r
-{\r
-    char buffer[1028];\r
-    const char *type_name;\r
-\r
-    type_name = Py_TYPE(self)->tp_name;\r
-    PyOS_snprintf(buffer, sizeof(buffer), "%s(%d, %d, %d)",\r
-                  type_name,\r
-                  GET_YEAR(self), GET_MONTH(self), GET_DAY(self));\r
-\r
-    return PyString_FromString(buffer);\r
-}\r
-\r
-static PyObject *\r
-date_isoformat(PyDateTime_Date *self)\r
-{\r
-    char buffer[128];\r
-\r
-    isoformat_date(self, buffer, sizeof(buffer));\r
-    return PyString_FromString(buffer);\r
-}\r
-\r
-/* str() calls the appropriate isoformat() method. */\r
-static PyObject *\r
-date_str(PyDateTime_Date *self)\r
-{\r
-    return PyObject_CallMethod((PyObject *)self, "isoformat", "()");\r
-}\r
-\r
-\r
-static PyObject *\r
-date_ctime(PyDateTime_Date *self)\r
-{\r
-    return format_ctime(self, 0, 0, 0);\r
-}\r
-\r
-static PyObject *\r
-date_strftime(PyDateTime_Date *self, PyObject *args, PyObject *kw)\r
-{\r
-    /* This method can be inherited, and needs to call the\r
-     * timetuple() method appropriate to self's class.\r
-     */\r
-    PyObject *result;\r
-    PyObject *tuple;\r
-    const char *format;\r
-    Py_ssize_t format_len;\r
-    static char *keywords[] = {"format", NULL};\r
-\r
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,\r
-                                      &format, &format_len))\r
-        return NULL;\r
-\r
-    tuple = PyObject_CallMethod((PyObject *)self, "timetuple", "()");\r
-    if (tuple == NULL)\r
-        return NULL;\r
-    result = wrap_strftime((PyObject *)self, format, format_len, tuple,\r
-                           (PyObject *)self);\r
-    Py_DECREF(tuple);\r
-    return result;\r
-}\r
-\r
-static PyObject *\r
-date_format(PyDateTime_Date *self, PyObject *args)\r
-{\r
-    PyObject *format;\r
-\r
-    if (!PyArg_ParseTuple(args, "O:__format__", &format))\r
-        return NULL;\r
-\r
-    /* Check for str or unicode */\r
-    if (PyString_Check(format)) {\r
-        /* If format is zero length, return str(self) */\r
-        if (PyString_GET_SIZE(format) == 0)\r
-            return PyObject_Str((PyObject *)self);\r
-    } else if (PyUnicode_Check(format)) {\r
-        /* If format is zero length, return str(self) */\r
-        if (PyUnicode_GET_SIZE(format) == 0)\r
-            return PyObject_Unicode((PyObject *)self);\r
-    } else {\r
-        PyErr_Format(PyExc_ValueError,\r
-                     "__format__ expects str or unicode, not %.200s",\r
-                     Py_TYPE(format)->tp_name);\r
-        return NULL;\r
-    }\r
-    return PyObject_CallMethod((PyObject *)self, "strftime", "O", format);\r
-}\r
-\r
-/* ISO methods. */\r
-\r
-static PyObject *\r
-date_isoweekday(PyDateTime_Date *self)\r
-{\r
-    int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));\r
-\r
-    return PyInt_FromLong(dow + 1);\r
-}\r
-\r
-static PyObject *\r
-date_isocalendar(PyDateTime_Date *self)\r
-{\r
-    int  year         = GET_YEAR(self);\r
-    int  week1_monday = iso_week1_monday(year);\r
-    int today         = ymd_to_ord(year, GET_MONTH(self), GET_DAY(self));\r
-    int  week;\r
-    int  day;\r
-\r
-    week = divmod(today - week1_monday, 7, &day);\r
-    if (week < 0) {\r
-        --year;\r
-        week1_monday = iso_week1_monday(year);\r
-        week = divmod(today - week1_monday, 7, &day);\r
-    }\r
-    else if (week >= 52 && today >= iso_week1_monday(year + 1)) {\r
-        ++year;\r
-        week = 0;\r
-    }\r
-    return Py_BuildValue("iii", year, week + 1, day + 1);\r
-}\r
-\r
-/* Miscellaneous methods. */\r
-\r
-/* This is more natural as a tp_compare, but doesn't work then:  for whatever\r
- * reason, Python's try_3way_compare ignores tp_compare unless\r
- * PyInstance_Check returns true, but these aren't old-style classes.\r
- */\r
-static PyObject *\r
-date_richcompare(PyDateTime_Date *self, PyObject *other, int op)\r
-{\r
-    int diff = 42;      /* nonsense */\r
-\r
-    if (PyDate_Check(other))\r
-        diff = memcmp(self->data, ((PyDateTime_Date *)other)->data,\r
-                      _PyDateTime_DATE_DATASIZE);\r
-\r
-    else if (PyObject_HasAttrString(other, "timetuple")) {\r
-        /* A hook for other kinds of date objects. */\r
-        Py_INCREF(Py_NotImplemented);\r
-        return Py_NotImplemented;\r
-    }\r
-    else if (op == Py_EQ || op == Py_NE)\r
-        diff = 1;               /* any non-zero value will do */\r
-\r
-    else /* stop this from falling back to address comparison */\r
-        return cmperror((PyObject *)self, other);\r
-\r
-    return diff_to_bool(diff, op);\r
-}\r
-\r
-static PyObject *\r
-date_timetuple(PyDateTime_Date *self)\r
-{\r
-    return build_struct_time(GET_YEAR(self),\r
-                             GET_MONTH(self),\r
-                             GET_DAY(self),\r
-                             0, 0, 0, -1);\r
-}\r
-\r
-static PyObject *\r
-date_replace(PyDateTime_Date *self, PyObject *args, PyObject *kw)\r
-{\r
-    PyObject *clone;\r
-    PyObject *tuple;\r
-    int year = GET_YEAR(self);\r
-    int month = GET_MONTH(self);\r
-    int day = GET_DAY(self);\r
-\r
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "|iii:replace", date_kws,\r
-                                      &year, &month, &day))\r
-        return NULL;\r
-    tuple = Py_BuildValue("iii", year, month, day);\r
-    if (tuple == NULL)\r
-        return NULL;\r
-    clone = date_new(Py_TYPE(self), tuple, NULL);\r
-    Py_DECREF(tuple);\r
-    return clone;\r
-}\r
-\r
-static PyObject *date_getstate(PyDateTime_Date *self);\r
-\r
-static long\r
-date_hash(PyDateTime_Date *self)\r
-{\r
-    if (self->hashcode == -1) {\r
-        PyObject *temp = date_getstate(self);\r
-        if (temp != NULL) {\r
-            self->hashcode = PyObject_Hash(temp);\r
-            Py_DECREF(temp);\r
-        }\r
-    }\r
-    return self->hashcode;\r
-}\r
-\r
-static PyObject *\r
-date_toordinal(PyDateTime_Date *self)\r
-{\r
-    return PyInt_FromLong(ymd_to_ord(GET_YEAR(self), GET_MONTH(self),\r
-                                     GET_DAY(self)));\r
-}\r
-\r
-static PyObject *\r
-date_weekday(PyDateTime_Date *self)\r
-{\r
-    int dow = weekday(GET_YEAR(self), GET_MONTH(self), GET_DAY(self));\r
-\r
-    return PyInt_FromLong(dow);\r
-}\r
-\r
-/* Pickle support, a simple use of __reduce__. */\r
-\r
-/* __getstate__ isn't exposed */\r
-static PyObject *\r
-date_getstate(PyDateTime_Date *self)\r
-{\r
-    return Py_BuildValue(\r
-        "(N)",\r
-        PyString_FromStringAndSize((char *)self->data,\r
-                                   _PyDateTime_DATE_DATASIZE));\r
-}\r
-\r
-static PyObject *\r
-date_reduce(PyDateTime_Date *self, PyObject *arg)\r
-{\r
-    return Py_BuildValue("(ON)", Py_TYPE(self), date_getstate(self));\r
-}\r
-\r
-static PyMethodDef date_methods[] = {\r
-\r
-    /* Class methods: */\r
-\r
-    {"fromtimestamp", (PyCFunction)date_fromtimestamp, METH_VARARGS |\r
-                                                       METH_CLASS,\r
-     PyDoc_STR("timestamp -> local date from a POSIX timestamp (like "\r
-               "time.time()).")},\r
-\r
-    {"fromordinal", (PyCFunction)date_fromordinal,      METH_VARARGS |\r
-                                                    METH_CLASS,\r
-     PyDoc_STR("int -> date corresponding to a proleptic Gregorian "\r
-               "ordinal.")},\r
-\r
-    {"today",         (PyCFunction)date_today,   METH_NOARGS | METH_CLASS,\r
-     PyDoc_STR("Current date or datetime:  same as "\r
-               "self.__class__.fromtimestamp(time.time()).")},\r
-\r
-    /* Instance methods: */\r
-\r
-    {"ctime",       (PyCFunction)date_ctime,        METH_NOARGS,\r
-     PyDoc_STR("Return ctime() style string.")},\r
-\r
-    {"strftime",        (PyCFunction)date_strftime,     METH_VARARGS | METH_KEYWORDS,\r
-     PyDoc_STR("format -> strftime() style string.")},\r
-\r
-    {"__format__",      (PyCFunction)date_format,       METH_VARARGS,\r
-     PyDoc_STR("Formats self with strftime.")},\r
-\r
-    {"timetuple",   (PyCFunction)date_timetuple,    METH_NOARGS,\r
-     PyDoc_STR("Return time tuple, compatible with time.localtime().")},\r
-\r
-    {"isocalendar", (PyCFunction)date_isocalendar,  METH_NOARGS,\r
-     PyDoc_STR("Return a 3-tuple containing ISO year, week number, and "\r
-               "weekday.")},\r
-\r
-    {"isoformat",   (PyCFunction)date_isoformat,        METH_NOARGS,\r
-     PyDoc_STR("Return string in ISO 8601 format, YYYY-MM-DD.")},\r
-\r
-    {"isoweekday",  (PyCFunction)date_isoweekday,   METH_NOARGS,\r
-     PyDoc_STR("Return the day of the week represented by the date.\n"\r
-               "Monday == 1 ... Sunday == 7")},\r
-\r
-    {"toordinal",   (PyCFunction)date_toordinal,    METH_NOARGS,\r
-     PyDoc_STR("Return proleptic Gregorian ordinal.  January 1 of year "\r
-               "1 is day 1.")},\r
-\r
-    {"weekday",     (PyCFunction)date_weekday,      METH_NOARGS,\r
-     PyDoc_STR("Return the day of the week represented by the date.\n"\r
-               "Monday == 0 ... Sunday == 6")},\r
-\r
-    {"replace",     (PyCFunction)date_replace,      METH_VARARGS | METH_KEYWORDS,\r
-     PyDoc_STR("Return date with new specified fields.")},\r
-\r
-    {"__reduce__", (PyCFunction)date_reduce,        METH_NOARGS,\r
-     PyDoc_STR("__reduce__() -> (cls, state)")},\r
-\r
-    {NULL,      NULL}\r
-};\r
-\r
-static char date_doc[] =\r
-PyDoc_STR("date(year, month, day) --> date object");\r
-\r
-static PyNumberMethods date_as_number = {\r
-    date_add,                                           /* nb_add */\r
-    date_subtract,                                      /* nb_subtract */\r
-    0,                                                  /* nb_multiply */\r
-    0,                                                  /* nb_divide */\r
-    0,                                                  /* nb_remainder */\r
-    0,                                                  /* nb_divmod */\r
-    0,                                                  /* nb_power */\r
-    0,                                                  /* nb_negative */\r
-    0,                                                  /* nb_positive */\r
-    0,                                                  /* nb_absolute */\r
-    0,                                                  /* nb_nonzero */\r
-};\r
-\r
-static PyTypeObject PyDateTime_DateType = {\r
-    PyVarObject_HEAD_INIT(NULL, 0)\r
-    "datetime.date",                                    /* tp_name */\r
-    sizeof(PyDateTime_Date),                            /* tp_basicsize */\r
-    0,                                                  /* tp_itemsize */\r
-    0,                                                  /* tp_dealloc */\r
-    0,                                                  /* tp_print */\r
-    0,                                                  /* tp_getattr */\r
-    0,                                                  /* tp_setattr */\r
-    0,                                                  /* tp_compare */\r
-    (reprfunc)date_repr,                                /* tp_repr */\r
-    &date_as_number,                                    /* tp_as_number */\r
-    0,                                                  /* tp_as_sequence */\r
-    0,                                                  /* tp_as_mapping */\r
-    (hashfunc)date_hash,                                /* tp_hash */\r
-    0,                                                  /* tp_call */\r
-    (reprfunc)date_str,                                 /* tp_str */\r
-    PyObject_GenericGetAttr,                            /* tp_getattro */\r
-    0,                                                  /* tp_setattro */\r
-    0,                                                  /* tp_as_buffer */\r
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |\r
-    Py_TPFLAGS_BASETYPE,                                /* tp_flags */\r
-    date_doc,                                           /* tp_doc */\r
-    0,                                                  /* tp_traverse */\r
-    0,                                                  /* tp_clear */\r
-    (richcmpfunc)date_richcompare,                      /* tp_richcompare */\r
-    0,                                                  /* tp_weaklistoffset */\r
-    0,                                                  /* tp_iter */\r
-    0,                                                  /* tp_iternext */\r
-    date_methods,                                       /* tp_methods */\r
-    0,                                                  /* tp_members */\r
-    date_getset,                                        /* tp_getset */\r
-    0,                                                  /* tp_base */\r
-    0,                                                  /* tp_dict */\r
-    0,                                                  /* tp_descr_get */\r
-    0,                                                  /* tp_descr_set */\r
-    0,                                                  /* tp_dictoffset */\r
-    0,                                                  /* tp_init */\r
-    0,                                                  /* tp_alloc */\r
-    date_new,                                           /* tp_new */\r
-    0,                                                  /* tp_free */\r
-};\r
-\r
-/*\r
- * PyDateTime_TZInfo implementation.\r
- */\r
-\r
-/* This is a pure abstract base class, so doesn't do anything beyond\r
- * raising NotImplemented exceptions.  Real tzinfo classes need\r
- * to derive from this.  This is mostly for clarity, and for efficiency in\r
- * datetime and time constructors (their tzinfo arguments need to\r
- * be subclasses of this tzinfo class, which is easy and quick to check).\r
- *\r
- * Note:  For reasons having to do with pickling of subclasses, we have\r
- * to allow tzinfo objects to be instantiated.  This wasn't an issue\r
- * in the Python implementation (__init__() could raise NotImplementedError\r
- * there without ill effect), but doing so in the C implementation hit a\r
- * brick wall.\r
- */\r
-\r
-static PyObject *\r
-tzinfo_nogo(const char* methodname)\r
-{\r
-    PyErr_Format(PyExc_NotImplementedError,\r
-                 "a tzinfo subclass must implement %s()",\r
-                 methodname);\r
-    return NULL;\r
-}\r
-\r
-/* Methods.  A subclass must implement these. */\r
-\r
-static PyObject *\r
-tzinfo_tzname(PyDateTime_TZInfo *self, PyObject *dt)\r
-{\r
-    return tzinfo_nogo("tzname");\r
-}\r
-\r
-static PyObject *\r
-tzinfo_utcoffset(PyDateTime_TZInfo *self, PyObject *dt)\r
-{\r
-    return tzinfo_nogo("utcoffset");\r
-}\r
-\r
-static PyObject *\r
-tzinfo_dst(PyDateTime_TZInfo *self, PyObject *dt)\r
-{\r
-    return tzinfo_nogo("dst");\r
-}\r
-\r
-static PyObject *\r
-tzinfo_fromutc(PyDateTime_TZInfo *self, PyDateTime_DateTime *dt)\r
-{\r
-    int y, m, d, hh, mm, ss, us;\r
-\r
-    PyObject *result;\r
-    int off, dst;\r
-    int none;\r
-    int delta;\r
-\r
-    if (! PyDateTime_Check(dt)) {\r
-        PyErr_SetString(PyExc_TypeError,\r
-                        "fromutc: argument must be a datetime");\r
-        return NULL;\r
-    }\r
-    if (! HASTZINFO(dt) || dt->tzinfo != (PyObject *)self) {\r
-        PyErr_SetString(PyExc_ValueError, "fromutc: dt.tzinfo "\r
-                        "is not self");\r
-        return NULL;\r
-    }\r
-\r
-    off = call_utcoffset(dt->tzinfo, (PyObject *)dt, &none);\r
-    if (off == -1 && PyErr_Occurred())\r
-        return NULL;\r
-    if (none) {\r
-        PyErr_SetString(PyExc_ValueError, "fromutc: non-None "\r
-                        "utcoffset() result required");\r
-        return NULL;\r
-    }\r
-\r
-    dst = call_dst(dt->tzinfo, (PyObject *)dt, &none);\r
-    if (dst == -1 && PyErr_Occurred())\r
-        return NULL;\r
-    if (none) {\r
-        PyErr_SetString(PyExc_ValueError, "fromutc: non-None "\r
-                        "dst() result required");\r
-        return NULL;\r
-    }\r
-\r
-    y = GET_YEAR(dt);\r
-    m = GET_MONTH(dt);\r
-    d = GET_DAY(dt);\r
-    hh = DATE_GET_HOUR(dt);\r
-    mm = DATE_GET_MINUTE(dt);\r
-    ss = DATE_GET_SECOND(dt);\r
-    us = DATE_GET_MICROSECOND(dt);\r
-\r
-    delta = off - dst;\r
-    mm += delta;\r
-    if ((mm < 0 || mm >= 60) &&\r
-        normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)\r
-        return NULL;\r
-    result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);\r
-    if (result == NULL)\r
-        return result;\r
-\r
-    dst = call_dst(dt->tzinfo, result, &none);\r
-    if (dst == -1 && PyErr_Occurred())\r
-        goto Fail;\r
-    if (none)\r
-        goto Inconsistent;\r
-    if (dst == 0)\r
-        return result;\r
-\r
-    mm += dst;\r
-    if ((mm < 0 || mm >= 60) &&\r
-        normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)\r
-        goto Fail;\r
-    Py_DECREF(result);\r
-    result = new_datetime(y, m, d, hh, mm, ss, us, dt->tzinfo);\r
-    return result;\r
-\r
-Inconsistent:\r
-    PyErr_SetString(PyExc_ValueError, "fromutc: tz.dst() gave"\r
-                    "inconsistent results; cannot convert");\r
-\r
-    /* fall thru to failure */\r
-Fail:\r
-    Py_DECREF(result);\r
-    return NULL;\r
-}\r
-\r
-/*\r
- * Pickle support.  This is solely so that tzinfo subclasses can use\r
- * pickling -- tzinfo itself is supposed to be uninstantiable.\r
- */\r
-\r
-static PyObject *\r
-tzinfo_reduce(PyObject *self)\r
-{\r
-    PyObject *args, *state, *tmp;\r
-    PyObject *getinitargs, *getstate;\r
-\r
-    tmp = PyTuple_New(0);\r
-    if (tmp == NULL)\r
-        return NULL;\r
-\r
-    getinitargs = PyObject_GetAttrString(self, "__getinitargs__");\r
-    if (getinitargs != NULL) {\r
-        args = PyObject_CallObject(getinitargs, tmp);\r
-        Py_DECREF(getinitargs);\r
-        if (args == NULL) {\r
-            Py_DECREF(tmp);\r
-            return NULL;\r
-        }\r
-    }\r
-    else {\r
-        PyErr_Clear();\r
-        args = tmp;\r
-        Py_INCREF(args);\r
-    }\r
-\r
-    getstate = PyObject_GetAttrString(self, "__getstate__");\r
-    if (getstate != NULL) {\r
-        state = PyObject_CallObject(getstate, tmp);\r
-        Py_DECREF(getstate);\r
-        if (state == NULL) {\r
-            Py_DECREF(args);\r
-            Py_DECREF(tmp);\r
-            return NULL;\r
-        }\r
-    }\r
-    else {\r
-        PyObject **dictptr;\r
-        PyErr_Clear();\r
-        state = Py_None;\r
-        dictptr = _PyObject_GetDictPtr(self);\r
-        if (dictptr && *dictptr && PyDict_Size(*dictptr))\r
-            state = *dictptr;\r
-        Py_INCREF(state);\r
-    }\r
-\r
-    Py_DECREF(tmp);\r
-\r
-    if (state == Py_None) {\r
-        Py_DECREF(state);\r
-        return Py_BuildValue("(ON)", Py_TYPE(self), args);\r
-    }\r
-    else\r
-        return Py_BuildValue("(ONN)", Py_TYPE(self), args, state);\r
-}\r
-\r
-static PyMethodDef tzinfo_methods[] = {\r
-\r
-    {"tzname",          (PyCFunction)tzinfo_tzname,             METH_O,\r
-     PyDoc_STR("datetime -> string name of time zone.")},\r
-\r
-    {"utcoffset",       (PyCFunction)tzinfo_utcoffset,          METH_O,\r
-     PyDoc_STR("datetime -> minutes east of UTC (negative for "\r
-               "west of UTC).")},\r
-\r
-    {"dst",             (PyCFunction)tzinfo_dst,                METH_O,\r
-     PyDoc_STR("datetime -> DST offset in minutes east of UTC.")},\r
-\r
-    {"fromutc",         (PyCFunction)tzinfo_fromutc,            METH_O,\r
-     PyDoc_STR("datetime in UTC -> datetime in local time.")},\r
-\r
-    {"__reduce__",  (PyCFunction)tzinfo_reduce,             METH_NOARGS,\r
-     PyDoc_STR("-> (cls, state)")},\r
-\r
-    {NULL, NULL}\r
-};\r
-\r
-static char tzinfo_doc[] =\r
-PyDoc_STR("Abstract base class for time zone info objects.");\r
-\r
-statichere PyTypeObject PyDateTime_TZInfoType = {\r
-    PyObject_HEAD_INIT(NULL)\r
-    0,                                          /* ob_size */\r
-    "datetime.tzinfo",                          /* tp_name */\r
-    sizeof(PyDateTime_TZInfo),                  /* tp_basicsize */\r
-    0,                                          /* tp_itemsize */\r
-    0,                                          /* tp_dealloc */\r
-    0,                                          /* tp_print */\r
-    0,                                          /* tp_getattr */\r
-    0,                                          /* tp_setattr */\r
-    0,                                          /* tp_compare */\r
-    0,                                          /* tp_repr */\r
-    0,                                          /* tp_as_number */\r
-    0,                                          /* tp_as_sequence */\r
-    0,                                          /* tp_as_mapping */\r
-    0,                                          /* tp_hash */\r
-    0,                                          /* tp_call */\r
-    0,                                          /* tp_str */\r
-    PyObject_GenericGetAttr,                    /* tp_getattro */\r
-    0,                                          /* tp_setattro */\r
-    0,                                          /* tp_as_buffer */\r
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |\r
-    Py_TPFLAGS_BASETYPE,                        /* tp_flags */\r
-    tzinfo_doc,                                 /* tp_doc */\r
-    0,                                          /* tp_traverse */\r
-    0,                                          /* tp_clear */\r
-    0,                                          /* tp_richcompare */\r
-    0,                                          /* tp_weaklistoffset */\r
-    0,                                          /* tp_iter */\r
-    0,                                          /* tp_iternext */\r
-    tzinfo_methods,                             /* tp_methods */\r
-    0,                                          /* tp_members */\r
-    0,                                          /* tp_getset */\r
-    0,                                          /* tp_base */\r
-    0,                                          /* tp_dict */\r
-    0,                                          /* tp_descr_get */\r
-    0,                                          /* tp_descr_set */\r
-    0,                                          /* tp_dictoffset */\r
-    0,                                          /* tp_init */\r
-    0,                                          /* tp_alloc */\r
-    PyType_GenericNew,                          /* tp_new */\r
-    0,                                          /* tp_free */\r
-};\r
-\r
-/*\r
- * PyDateTime_Time implementation.\r
- */\r
-\r
-/* Accessor properties.\r
- */\r
-\r
-static PyObject *\r
-time_hour(PyDateTime_Time *self, void *unused)\r
-{\r
-    return PyInt_FromLong(TIME_GET_HOUR(self));\r
-}\r
-\r
-static PyObject *\r
-time_minute(PyDateTime_Time *self, void *unused)\r
-{\r
-    return PyInt_FromLong(TIME_GET_MINUTE(self));\r
-}\r
-\r
-/* The name time_second conflicted with some platform header file. */\r
-static PyObject *\r
-py_time_second(PyDateTime_Time *self, void *unused)\r
-{\r
-    return PyInt_FromLong(TIME_GET_SECOND(self));\r
-}\r
-\r
-static PyObject *\r
-time_microsecond(PyDateTime_Time *self, void *unused)\r
-{\r
-    return PyInt_FromLong(TIME_GET_MICROSECOND(self));\r
-}\r
-\r
-static PyObject *\r
-time_tzinfo(PyDateTime_Time *self, void *unused)\r
-{\r
-    PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;\r
-    Py_INCREF(result);\r
-    return result;\r
-}\r
-\r
-static PyGetSetDef time_getset[] = {\r
-    {"hour",        (getter)time_hour},\r
-    {"minute",      (getter)time_minute},\r
-    {"second",      (getter)py_time_second},\r
-    {"microsecond", (getter)time_microsecond},\r
-    {"tzinfo",          (getter)time_tzinfo},\r
-    {NULL}\r
-};\r
-\r
-/*\r
- * Constructors.\r
- */\r
-\r
-static char *time_kws[] = {"hour", "minute", "second", "microsecond",\r
-                           "tzinfo", NULL};\r
-\r
-static PyObject *\r
-time_new(PyTypeObject *type, PyObject *args, PyObject *kw)\r
-{\r
-    PyObject *self = NULL;\r
-    PyObject *state;\r
-    int hour = 0;\r
-    int minute = 0;\r
-    int second = 0;\r
-    int usecond = 0;\r
-    PyObject *tzinfo = Py_None;\r
-\r
-    /* Check for invocation from pickle with __getstate__ state */\r
-    if (PyTuple_GET_SIZE(args) >= 1 &&\r
-        PyTuple_GET_SIZE(args) <= 2 &&\r
-        PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&\r
-        PyString_GET_SIZE(state) == _PyDateTime_TIME_DATASIZE &&\r
-        ((unsigned char) (PyString_AS_STRING(state)[0])) < 24)\r
-    {\r
-        PyDateTime_Time *me;\r
-        char aware;\r
-\r
-        if (PyTuple_GET_SIZE(args) == 2) {\r
-            tzinfo = PyTuple_GET_ITEM(args, 1);\r
-            if (check_tzinfo_subclass(tzinfo) < 0) {\r
-                PyErr_SetString(PyExc_TypeError, "bad "\r
-                    "tzinfo state arg");\r
-                return NULL;\r
-            }\r
-        }\r
-        aware = (char)(tzinfo != Py_None);\r
-        me = (PyDateTime_Time *) (type->tp_alloc(type, aware));\r
-        if (me != NULL) {\r
-            char *pdata = PyString_AS_STRING(state);\r
-\r
-            memcpy(me->data, pdata, _PyDateTime_TIME_DATASIZE);\r
-            me->hashcode = -1;\r
-            me->hastzinfo = aware;\r
-            if (aware) {\r
-                Py_INCREF(tzinfo);\r
-                me->tzinfo = tzinfo;\r
-            }\r
-        }\r
-        return (PyObject *)me;\r
-    }\r
-\r
-    if (PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO", time_kws,\r
-                                    &hour, &minute, &second, &usecond,\r
-                                    &tzinfo)) {\r
-        if (check_time_args(hour, minute, second, usecond) < 0)\r
-            return NULL;\r
-        if (check_tzinfo_subclass(tzinfo) < 0)\r
-            return NULL;\r
-        self = new_time_ex(hour, minute, second, usecond, tzinfo,\r
-                           type);\r
-    }\r
-    return self;\r
-}\r
-\r
-/*\r
- * Destructor.\r
- */\r
-\r
-static void\r
-time_dealloc(PyDateTime_Time *self)\r
-{\r
-    if (HASTZINFO(self)) {\r
-        Py_XDECREF(self->tzinfo);\r
-    }\r
-    Py_TYPE(self)->tp_free((PyObject *)self);\r
-}\r
-\r
-/*\r
- * Indirect access to tzinfo methods.\r
- */\r
-\r
-/* These are all METH_NOARGS, so don't need to check the arglist. */\r
-static PyObject *\r
-time_utcoffset(PyDateTime_Time *self, PyObject *unused) {\r
-    return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,\r
-                               "utcoffset", Py_None);\r
-}\r
-\r
-static PyObject *\r
-time_dst(PyDateTime_Time *self, PyObject *unused) {\r
-    return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,\r
-                               "dst", Py_None);\r
-}\r
-\r
-static PyObject *\r
-time_tzname(PyDateTime_Time *self, PyObject *unused) {\r
-    return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,\r
-                       Py_None);\r
-}\r
-\r
-/*\r
- * Various ways to turn a time into a string.\r
- */\r
-\r
-static PyObject *\r
-time_repr(PyDateTime_Time *self)\r
-{\r
-    char buffer[100];\r
-    const char *type_name = Py_TYPE(self)->tp_name;\r
-    int h = TIME_GET_HOUR(self);\r
-    int m = TIME_GET_MINUTE(self);\r
-    int s = TIME_GET_SECOND(self);\r
-    int us = TIME_GET_MICROSECOND(self);\r
-    PyObject *result = NULL;\r
-\r
-    if (us)\r
-        PyOS_snprintf(buffer, sizeof(buffer),\r
-                      "%s(%d, %d, %d, %d)", type_name, h, m, s, us);\r
-    else if (s)\r
-        PyOS_snprintf(buffer, sizeof(buffer),\r
-                      "%s(%d, %d, %d)", type_name, h, m, s);\r
-    else\r
-        PyOS_snprintf(buffer, sizeof(buffer),\r
-                      "%s(%d, %d)", type_name, h, m);\r
-    result = PyString_FromString(buffer);\r
-    if (result != NULL && HASTZINFO(self))\r
-        result = append_keyword_tzinfo(result, self->tzinfo);\r
-    return result;\r
-}\r
-\r
-static PyObject *\r
-time_str(PyDateTime_Time *self)\r
-{\r
-    return PyObject_CallMethod((PyObject *)self, "isoformat", "()");\r
-}\r
-\r
-static PyObject *\r
-time_isoformat(PyDateTime_Time *self, PyObject *unused)\r
-{\r
-    char buf[100];\r
-    PyObject *result;\r
-    /* Reuse the time format code from the datetime type. */\r
-    PyDateTime_DateTime datetime;\r
-    PyDateTime_DateTime *pdatetime = &datetime;\r
-\r
-    /* Copy over just the time bytes. */\r
-    memcpy(pdatetime->data + _PyDateTime_DATE_DATASIZE,\r
-           self->data,\r
-           _PyDateTime_TIME_DATASIZE);\r
-\r
-    isoformat_time(pdatetime, buf, sizeof(buf));\r
-    result = PyString_FromString(buf);\r
-    if (result == NULL || ! HASTZINFO(self) || self->tzinfo == Py_None)\r
-        return result;\r
-\r
-    /* We need to append the UTC offset. */\r
-    if (format_utcoffset(buf, sizeof(buf), ":", self->tzinfo,\r
-                         Py_None) < 0) {\r
-        Py_DECREF(result);\r
-        return NULL;\r
-    }\r
-    PyString_ConcatAndDel(&result, PyString_FromString(buf));\r
-    return result;\r
-}\r
-\r
-static PyObject *\r
-time_strftime(PyDateTime_Time *self, PyObject *args, PyObject *kw)\r
-{\r
-    PyObject *result;\r
-    PyObject *tuple;\r
-    const char *format;\r
-    Py_ssize_t format_len;\r
-    static char *keywords[] = {"format", NULL};\r
-\r
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "s#:strftime", keywords,\r
-                                      &format, &format_len))\r
-        return NULL;\r
-\r
-    /* Python's strftime does insane things with the year part of the\r
-     * timetuple.  The year is forced to (the otherwise nonsensical)\r
-     * 1900 to worm around that.\r
-     */\r
-    tuple = Py_BuildValue("iiiiiiiii",\r
-                          1900, 1, 1, /* year, month, day */\r
-                  TIME_GET_HOUR(self),\r
-                  TIME_GET_MINUTE(self),\r
-                  TIME_GET_SECOND(self),\r
-                  0, 1, -1); /* weekday, daynum, dst */\r
-    if (tuple == NULL)\r
-        return NULL;\r
-    assert(PyTuple_Size(tuple) == 9);\r
-    result = wrap_strftime((PyObject *)self, format, format_len, tuple,\r
-                           Py_None);\r
-    Py_DECREF(tuple);\r
-    return result;\r
-}\r
-\r
-/*\r
- * Miscellaneous methods.\r
- */\r
-\r
-/* This is more natural as a tp_compare, but doesn't work then:  for whatever\r
- * reason, Python's try_3way_compare ignores tp_compare unless\r
- * PyInstance_Check returns true, but these aren't old-style classes.\r
- */\r
-static PyObject *\r
-time_richcompare(PyDateTime_Time *self, PyObject *other, int op)\r
-{\r
-    int diff;\r
-    naivety n1, n2;\r
-    int offset1, offset2;\r
-\r
-    if (! PyTime_Check(other)) {\r
-        if (op == Py_EQ || op == Py_NE) {\r
-            PyObject *result = op == Py_EQ ? Py_False : Py_True;\r
-            Py_INCREF(result);\r
-            return result;\r
-        }\r
-        /* Stop this from falling back to address comparison. */\r
-        return cmperror((PyObject *)self, other);\r
-    }\r
-    if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1, Py_None,\r
-                                 other, &offset2, &n2, Py_None) < 0)\r
-        return NULL;\r
-    assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);\r
-    /* If they're both naive, or both aware and have the same offsets,\r
-     * we get off cheap.  Note that if they're both naive, offset1 ==\r
-     * offset2 == 0 at this point.\r
-     */\r
-    if (n1 == n2 && offset1 == offset2) {\r
-        diff = memcmp(self->data, ((PyDateTime_Time *)other)->data,\r
-                      _PyDateTime_TIME_DATASIZE);\r
-        return diff_to_bool(diff, op);\r
-    }\r
-\r
-    if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {\r
-        assert(offset1 != offset2);             /* else last "if" handled it */\r
-        /* Convert everything except microseconds to seconds.  These\r
-         * can't overflow (no more than the # of seconds in 2 days).\r
-         */\r
-        offset1 = TIME_GET_HOUR(self) * 3600 +\r
-                  (TIME_GET_MINUTE(self) - offset1) * 60 +\r
-                  TIME_GET_SECOND(self);\r
-        offset2 = TIME_GET_HOUR(other) * 3600 +\r
-                  (TIME_GET_MINUTE(other) - offset2) * 60 +\r
-                  TIME_GET_SECOND(other);\r
-        diff = offset1 - offset2;\r
-        if (diff == 0)\r
-            diff = TIME_GET_MICROSECOND(self) -\r
-                   TIME_GET_MICROSECOND(other);\r
-        return diff_to_bool(diff, op);\r
-    }\r
-\r
-    assert(n1 != n2);\r
-    PyErr_SetString(PyExc_TypeError,\r
-                    "can't compare offset-naive and "\r
-                    "offset-aware times");\r
-    return NULL;\r
-}\r
-\r
-static long\r
-time_hash(PyDateTime_Time *self)\r
-{\r
-    if (self->hashcode == -1) {\r
-        naivety n;\r
-        int offset;\r
-        PyObject *temp;\r
-\r
-        n = classify_utcoffset((PyObject *)self, Py_None, &offset);\r
-        assert(n != OFFSET_UNKNOWN);\r
-        if (n == OFFSET_ERROR)\r
-            return -1;\r
-\r
-        /* Reduce this to a hash of another object. */\r
-        if (offset == 0)\r
-            temp = PyString_FromStringAndSize((char *)self->data,\r
-                                    _PyDateTime_TIME_DATASIZE);\r
-        else {\r
-            int hour;\r
-            int minute;\r
-\r
-            assert(n == OFFSET_AWARE);\r
-            assert(HASTZINFO(self));\r
-            hour = divmod(TIME_GET_HOUR(self) * 60 +\r
-                            TIME_GET_MINUTE(self) - offset,\r
-                          60,\r
-                          &minute);\r
-            if (0 <= hour && hour < 24)\r
-                temp = new_time(hour, minute,\r
-                                TIME_GET_SECOND(self),\r
-                                TIME_GET_MICROSECOND(self),\r
-                                Py_None);\r
-            else\r
-                temp = Py_BuildValue("iiii",\r
-                           hour, minute,\r
-                           TIME_GET_SECOND(self),\r
-                           TIME_GET_MICROSECOND(self));\r
-        }\r
-        if (temp != NULL) {\r
-            self->hashcode = PyObject_Hash(temp);\r
-            Py_DECREF(temp);\r
-        }\r
-    }\r
-    return self->hashcode;\r
-}\r
-\r
-static PyObject *\r
-time_replace(PyDateTime_Time *self, PyObject *args, PyObject *kw)\r
-{\r
-    PyObject *clone;\r
-    PyObject *tuple;\r
-    int hh = TIME_GET_HOUR(self);\r
-    int mm = TIME_GET_MINUTE(self);\r
-    int ss = TIME_GET_SECOND(self);\r
-    int us = TIME_GET_MICROSECOND(self);\r
-    PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;\r
-\r
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiO:replace",\r
-                                      time_kws,\r
-                                      &hh, &mm, &ss, &us, &tzinfo))\r
-        return NULL;\r
-    tuple = Py_BuildValue("iiiiO", hh, mm, ss, us, tzinfo);\r
-    if (tuple == NULL)\r
-        return NULL;\r
-    clone = time_new(Py_TYPE(self), tuple, NULL);\r
-    Py_DECREF(tuple);\r
-    return clone;\r
-}\r
-\r
-static int\r
-time_nonzero(PyDateTime_Time *self)\r
-{\r
-    int offset;\r
-    int none;\r
-\r
-    if (TIME_GET_SECOND(self) || TIME_GET_MICROSECOND(self)) {\r
-        /* Since utcoffset is in whole minutes, nothing can\r
-         * alter the conclusion that this is nonzero.\r
-         */\r
-        return 1;\r
-    }\r
-    offset = 0;\r
-    if (HASTZINFO(self) && self->tzinfo != Py_None) {\r
-        offset = call_utcoffset(self->tzinfo, Py_None, &none);\r
-        if (offset == -1 && PyErr_Occurred())\r
-            return -1;\r
-    }\r
-    return (TIME_GET_MINUTE(self) - offset + TIME_GET_HOUR(self)*60) != 0;\r
-}\r
-\r
-/* Pickle support, a simple use of __reduce__. */\r
-\r
-/* Let basestate be the non-tzinfo data string.\r
- * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).\r
- * So it's a tuple in any (non-error) case.\r
- * __getstate__ isn't exposed.\r
- */\r
-static PyObject *\r
-time_getstate(PyDateTime_Time *self)\r
-{\r
-    PyObject *basestate;\r
-    PyObject *result = NULL;\r
-\r
-    basestate =  PyString_FromStringAndSize((char *)self->data,\r
-                                            _PyDateTime_TIME_DATASIZE);\r
-    if (basestate != NULL) {\r
-        if (! HASTZINFO(self) || self->tzinfo == Py_None)\r
-            result = PyTuple_Pack(1, basestate);\r
-        else\r
-            result = PyTuple_Pack(2, basestate, self->tzinfo);\r
-        Py_DECREF(basestate);\r
-    }\r
-    return result;\r
-}\r
-\r
-static PyObject *\r
-time_reduce(PyDateTime_Time *self, PyObject *arg)\r
-{\r
-    return Py_BuildValue("(ON)", Py_TYPE(self), time_getstate(self));\r
-}\r
-\r
-static PyMethodDef time_methods[] = {\r
-\r
-    {"isoformat",   (PyCFunction)time_isoformat,        METH_NOARGS,\r
-     PyDoc_STR("Return string in ISO 8601 format, HH:MM:SS[.mmmmmm]"\r
-               "[+HH:MM].")},\r
-\r
-    {"strftime",        (PyCFunction)time_strftime,     METH_VARARGS | METH_KEYWORDS,\r
-     PyDoc_STR("format -> strftime() style string.")},\r
-\r
-    {"__format__",      (PyCFunction)date_format,       METH_VARARGS,\r
-     PyDoc_STR("Formats self with strftime.")},\r
-\r
-    {"utcoffset",       (PyCFunction)time_utcoffset,    METH_NOARGS,\r
-     PyDoc_STR("Return self.tzinfo.utcoffset(self).")},\r
-\r
-    {"tzname",          (PyCFunction)time_tzname,       METH_NOARGS,\r
-     PyDoc_STR("Return self.tzinfo.tzname(self).")},\r
-\r
-    {"dst",             (PyCFunction)time_dst,          METH_NOARGS,\r
-     PyDoc_STR("Return self.tzinfo.dst(self).")},\r
-\r
-    {"replace",     (PyCFunction)time_replace,          METH_VARARGS | METH_KEYWORDS,\r
-     PyDoc_STR("Return time with new specified fields.")},\r
-\r
-    {"__reduce__", (PyCFunction)time_reduce,        METH_NOARGS,\r
-     PyDoc_STR("__reduce__() -> (cls, state)")},\r
-\r
-    {NULL,      NULL}\r
-};\r
-\r
-static char time_doc[] =\r
-PyDoc_STR("time([hour[, minute[, second[, microsecond[, tzinfo]]]]]) --> a time object\n\\r
-\n\\r
-All arguments are optional. tzinfo may be None, or an instance of\n\\r
-a tzinfo subclass. The remaining arguments may be ints or longs.\n");\r
-\r
-static PyNumberMethods time_as_number = {\r
-    0,                                          /* nb_add */\r
-    0,                                          /* nb_subtract */\r
-    0,                                          /* nb_multiply */\r
-    0,                                          /* nb_divide */\r
-    0,                                          /* nb_remainder */\r
-    0,                                          /* nb_divmod */\r
-    0,                                          /* nb_power */\r
-    0,                                          /* nb_negative */\r
-    0,                                          /* nb_positive */\r
-    0,                                          /* nb_absolute */\r
-    (inquiry)time_nonzero,                      /* nb_nonzero */\r
-};\r
-\r
-statichere PyTypeObject PyDateTime_TimeType = {\r
-    PyObject_HEAD_INIT(NULL)\r
-    0,                                          /* ob_size */\r
-    "datetime.time",                            /* tp_name */\r
-    sizeof(PyDateTime_Time),                    /* tp_basicsize */\r
-    0,                                          /* tp_itemsize */\r
-    (destructor)time_dealloc,                   /* tp_dealloc */\r
-    0,                                          /* tp_print */\r
-    0,                                          /* tp_getattr */\r
-    0,                                          /* tp_setattr */\r
-    0,                                          /* tp_compare */\r
-    (reprfunc)time_repr,                        /* tp_repr */\r
-    &time_as_number,                            /* tp_as_number */\r
-    0,                                          /* tp_as_sequence */\r
-    0,                                          /* tp_as_mapping */\r
-    (hashfunc)time_hash,                        /* tp_hash */\r
-    0,                                          /* tp_call */\r
-    (reprfunc)time_str,                         /* tp_str */\r
-    PyObject_GenericGetAttr,                    /* tp_getattro */\r
-    0,                                          /* tp_setattro */\r
-    0,                                          /* tp_as_buffer */\r
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |\r
-    Py_TPFLAGS_BASETYPE,                        /* tp_flags */\r
-    time_doc,                                   /* tp_doc */\r
-    0,                                          /* tp_traverse */\r
-    0,                                          /* tp_clear */\r
-    (richcmpfunc)time_richcompare,              /* tp_richcompare */\r
-    0,                                          /* tp_weaklistoffset */\r
-    0,                                          /* tp_iter */\r
-    0,                                          /* tp_iternext */\r
-    time_methods,                               /* tp_methods */\r
-    0,                                          /* tp_members */\r
-    time_getset,                                /* tp_getset */\r
-    0,                                          /* tp_base */\r
-    0,                                          /* tp_dict */\r
-    0,                                          /* tp_descr_get */\r
-    0,                                          /* tp_descr_set */\r
-    0,                                          /* tp_dictoffset */\r
-    0,                                          /* tp_init */\r
-    time_alloc,                                 /* tp_alloc */\r
-    time_new,                                   /* tp_new */\r
-    0,                                          /* tp_free */\r
-};\r
-\r
-/*\r
- * PyDateTime_DateTime implementation.\r
- */\r
-\r
-/* Accessor properties.  Properties for day, month, and year are inherited\r
- * from date.\r
- */\r
-\r
-static PyObject *\r
-datetime_hour(PyDateTime_DateTime *self, void *unused)\r
-{\r
-    return PyInt_FromLong(DATE_GET_HOUR(self));\r
-}\r
-\r
-static PyObject *\r
-datetime_minute(PyDateTime_DateTime *self, void *unused)\r
-{\r
-    return PyInt_FromLong(DATE_GET_MINUTE(self));\r
-}\r
-\r
-static PyObject *\r
-datetime_second(PyDateTime_DateTime *self, void *unused)\r
-{\r
-    return PyInt_FromLong(DATE_GET_SECOND(self));\r
-}\r
-\r
-static PyObject *\r
-datetime_microsecond(PyDateTime_DateTime *self, void *unused)\r
-{\r
-    return PyInt_FromLong(DATE_GET_MICROSECOND(self));\r
-}\r
-\r
-static PyObject *\r
-datetime_tzinfo(PyDateTime_DateTime *self, void *unused)\r
-{\r
-    PyObject *result = HASTZINFO(self) ? self->tzinfo : Py_None;\r
-    Py_INCREF(result);\r
-    return result;\r
-}\r
-\r
-static PyGetSetDef datetime_getset[] = {\r
-    {"hour",        (getter)datetime_hour},\r
-    {"minute",      (getter)datetime_minute},\r
-    {"second",      (getter)datetime_second},\r
-    {"microsecond", (getter)datetime_microsecond},\r
-    {"tzinfo",          (getter)datetime_tzinfo},\r
-    {NULL}\r
-};\r
-\r
-/*\r
- * Constructors.\r
- */\r
-\r
-static char *datetime_kws[] = {\r
-    "year", "month", "day", "hour", "minute", "second",\r
-    "microsecond", "tzinfo", NULL\r
-};\r
-\r
-static PyObject *\r
-datetime_new(PyTypeObject *type, PyObject *args, PyObject *kw)\r
-{\r
-    PyObject *self = NULL;\r
-    PyObject *state;\r
-    int year;\r
-    int month;\r
-    int day;\r
-    int hour = 0;\r
-    int minute = 0;\r
-    int second = 0;\r
-    int usecond = 0;\r
-    PyObject *tzinfo = Py_None;\r
-\r
-    /* Check for invocation from pickle with __getstate__ state */\r
-    if (PyTuple_GET_SIZE(args) >= 1 &&\r
-        PyTuple_GET_SIZE(args) <= 2 &&\r
-        PyString_Check(state = PyTuple_GET_ITEM(args, 0)) &&\r
-        PyString_GET_SIZE(state) == _PyDateTime_DATETIME_DATASIZE &&\r
-        MONTH_IS_SANE(PyString_AS_STRING(state)[2]))\r
-    {\r
-        PyDateTime_DateTime *me;\r
-        char aware;\r
-\r
-        if (PyTuple_GET_SIZE(args) == 2) {\r
-            tzinfo = PyTuple_GET_ITEM(args, 1);\r
-            if (check_tzinfo_subclass(tzinfo) < 0) {\r
-                PyErr_SetString(PyExc_TypeError, "bad "\r
-                    "tzinfo state arg");\r
-                return NULL;\r
-            }\r
-        }\r
-        aware = (char)(tzinfo != Py_None);\r
-        me = (PyDateTime_DateTime *) (type->tp_alloc(type , aware));\r
-        if (me != NULL) {\r
-            char *pdata = PyString_AS_STRING(state);\r
-\r
-            memcpy(me->data, pdata, _PyDateTime_DATETIME_DATASIZE);\r
-            me->hashcode = -1;\r
-            me->hastzinfo = aware;\r
-            if (aware) {\r
-                Py_INCREF(tzinfo);\r
-                me->tzinfo = tzinfo;\r
-            }\r
-        }\r
-        return (PyObject *)me;\r
-    }\r
-\r
-    if (PyArg_ParseTupleAndKeywords(args, kw, "iii|iiiiO", datetime_kws,\r
-                                    &year, &month, &day, &hour, &minute,\r
-                                    &second, &usecond, &tzinfo)) {\r
-        if (check_date_args(year, month, day) < 0)\r
-            return NULL;\r
-        if (check_time_args(hour, minute, second, usecond) < 0)\r
-            return NULL;\r
-        if (check_tzinfo_subclass(tzinfo) < 0)\r
-            return NULL;\r
-        self = new_datetime_ex(year, month, day,\r
-                                hour, minute, second, usecond,\r
-                                tzinfo, type);\r
-    }\r
-    return self;\r
-}\r
-\r
-/* TM_FUNC is the shared type of localtime() and gmtime(). */\r
-typedef struct tm *(*TM_FUNC)(const time_t *timer);\r
-\r
-/* Internal helper.\r
- * Build datetime from a time_t and a distinct count of microseconds.\r
- * Pass localtime or gmtime for f, to control the interpretation of timet.\r
- */\r
-static PyObject *\r
-datetime_from_timet_and_us(PyObject *cls, TM_FUNC f, time_t timet, int us,\r
-                           PyObject *tzinfo)\r
-{\r
-    struct tm *tm;\r
-    PyObject *result = NULL;\r
-\r
-    tm = f(&timet);\r
-    if (tm) {\r
-        /* The platform localtime/gmtime may insert leap seconds,\r
-         * indicated by tm->tm_sec > 59.  We don't care about them,\r
-         * except to the extent that passing them on to the datetime\r
-         * constructor would raise ValueError for a reason that\r
-         * made no sense to the user.\r
-         */\r
-        if (tm->tm_sec > 59)\r
-            tm->tm_sec = 59;\r
-        result = PyObject_CallFunction(cls, "iiiiiiiO",\r
-                                       tm->tm_year + 1900,\r
-                                       tm->tm_mon + 1,\r
-                                       tm->tm_mday,\r
-                                       tm->tm_hour,\r
-                                       tm->tm_min,\r
-                                       tm->tm_sec,\r
-                                       us,\r
-                                       tzinfo);\r
-    }\r
-    else\r
-        PyErr_SetString(PyExc_ValueError,\r
-                        "timestamp out of range for "\r
-                        "platform localtime()/gmtime() function");\r
-    return result;\r
-}\r
-\r
-/* Internal helper.\r
- * Build datetime from a Python timestamp.  Pass localtime or gmtime for f,\r
- * to control the interpretation of the timestamp.  Since a double doesn't\r
- * have enough bits to cover a datetime's full range of precision, it's\r
- * better to call datetime_from_timet_and_us provided you have a way\r
- * to get that much precision (e.g., C time() isn't good enough).\r
- */\r
-static PyObject *\r
-datetime_from_timestamp(PyObject *cls, TM_FUNC f, double timestamp,\r
-                        PyObject *tzinfo)\r
-{\r
-    time_t timet;\r
-    double fraction;\r
-    int us;\r
-\r
-    timet = _PyTime_DoubleToTimet(timestamp);\r
-    if (timet == (time_t)-1 && PyErr_Occurred())\r
-        return NULL;\r
-    fraction = timestamp - (double)timet;\r
-    us = (int)round_to_long(fraction * 1e6);\r
-    if (us < 0) {\r
-        /* Truncation towards zero is not what we wanted\r
-           for negative numbers (Python's mod semantics) */\r
-        timet -= 1;\r
-        us += 1000000;\r
-    }\r
-    /* If timestamp is less than one microsecond smaller than a\r
-     * full second, round up. Otherwise, ValueErrors are raised\r
-     * for some floats. */\r
-    if (us == 1000000) {\r
-        timet += 1;\r
-        us = 0;\r
-    }\r
-    return datetime_from_timet_and_us(cls, f, timet, us, tzinfo);\r
-}\r
-\r
-/* Internal helper.\r
- * Build most accurate possible datetime for current time.  Pass localtime or\r
- * gmtime for f as appropriate.\r
- */\r
-static PyObject *\r
-datetime_best_possible(PyObject *cls, TM_FUNC f, PyObject *tzinfo)\r
-{\r
-#ifdef HAVE_GETTIMEOFDAY\r
-    struct timeval t;\r
-\r
-#ifdef GETTIMEOFDAY_NO_TZ\r
-    gettimeofday(&t);\r
-#else\r
-    gettimeofday(&t, (struct timezone *)NULL);\r
-#endif\r
-    return datetime_from_timet_and_us(cls, f, t.tv_sec, (int)t.tv_usec,\r
-                                      tzinfo);\r
-\r
-#else   /* ! HAVE_GETTIMEOFDAY */\r
-    /* No flavor of gettimeofday exists on this platform.  Python's\r
-     * time.time() does a lot of other platform tricks to get the\r
-     * best time it can on the platform, and we're not going to do\r
-     * better than that (if we could, the better code would belong\r
-     * in time.time()!)  We're limited by the precision of a double,\r
-     * though.\r
-     */\r
-    PyObject *time;\r
-    double dtime;\r
-\r
-    time = time_time();\r
-    if (time == NULL)\r
-        return NULL;\r
-    dtime = PyFloat_AsDouble(time);\r
-    Py_DECREF(time);\r
-    if (dtime == -1.0 && PyErr_Occurred())\r
-        return NULL;\r
-    return datetime_from_timestamp(cls, f, dtime, tzinfo);\r
-#endif  /* ! HAVE_GETTIMEOFDAY */\r
-}\r
-\r
-/* Return best possible local time -- this isn't constrained by the\r
- * precision of a timestamp.\r
- */\r
-static PyObject *\r
-datetime_now(PyObject *cls, PyObject *args, PyObject *kw)\r
-{\r
-    PyObject *self;\r
-    PyObject *tzinfo = Py_None;\r
-    static char *keywords[] = {"tz", NULL};\r
-\r
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "|O:now", keywords,\r
-                                      &tzinfo))\r
-        return NULL;\r
-    if (check_tzinfo_subclass(tzinfo) < 0)\r
-        return NULL;\r
-\r
-    self = datetime_best_possible(cls,\r
-                                  tzinfo == Py_None ? localtime : gmtime,\r
-                                  tzinfo);\r
-    if (self != NULL && tzinfo != Py_None) {\r
-        /* Convert UTC to tzinfo's zone. */\r
-        PyObject *temp = self;\r
-        self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);\r
-        Py_DECREF(temp);\r
-    }\r
-    return self;\r
-}\r
-\r
-/* Return best possible UTC time -- this isn't constrained by the\r
- * precision of a timestamp.\r
- */\r
-static PyObject *\r
-datetime_utcnow(PyObject *cls, PyObject *dummy)\r
-{\r
-    return datetime_best_possible(cls, gmtime, Py_None);\r
-}\r
-\r
-/* Return new local datetime from timestamp (Python timestamp -- a double). */\r
-static PyObject *\r
-datetime_fromtimestamp(PyObject *cls, PyObject *args, PyObject *kw)\r
-{\r
-    PyObject *self;\r
-    double timestamp;\r
-    PyObject *tzinfo = Py_None;\r
-    static char *keywords[] = {"timestamp", "tz", NULL};\r
-\r
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "d|O:fromtimestamp",\r
-                                      keywords, &timestamp, &tzinfo))\r
-        return NULL;\r
-    if (check_tzinfo_subclass(tzinfo) < 0)\r
-        return NULL;\r
-\r
-    self = datetime_from_timestamp(cls,\r
-                                   tzinfo == Py_None ? localtime : gmtime,\r
-                                   timestamp,\r
-                                   tzinfo);\r
-    if (self != NULL && tzinfo != Py_None) {\r
-        /* Convert UTC to tzinfo's zone. */\r
-        PyObject *temp = self;\r
-        self = PyObject_CallMethod(tzinfo, "fromutc", "O", self);\r
-        Py_DECREF(temp);\r
-    }\r
-    return self;\r
-}\r
-\r
-/* Return new UTC datetime from timestamp (Python timestamp -- a double). */\r
-static PyObject *\r
-datetime_utcfromtimestamp(PyObject *cls, PyObject *args)\r
-{\r
-    double timestamp;\r
-    PyObject *result = NULL;\r
-\r
-    if (PyArg_ParseTuple(args, "d:utcfromtimestamp", &timestamp))\r
-        result = datetime_from_timestamp(cls, gmtime, timestamp,\r
-                                         Py_None);\r
-    return result;\r
-}\r
-\r
-/* Return new datetime from time.strptime(). */\r
-static PyObject *\r
-datetime_strptime(PyObject *cls, PyObject *args)\r
-{\r
-    static PyObject *module = NULL;\r
-    PyObject *result = NULL, *obj, *st = NULL, *frac = NULL;\r
-    const char *string, *format;\r
-\r
-    if (!PyArg_ParseTuple(args, "ss:strptime", &string, &format))\r
-        return NULL;\r
-\r
-    if (module == NULL &&\r
-        (module = PyImport_ImportModuleNoBlock("_strptime")) == NULL)\r
-        return NULL;\r
-\r
-    /* _strptime._strptime returns a two-element tuple.  The first\r
-       element is a time.struct_time object.  The second is the\r
-       microseconds (which are not defined for time.struct_time). */\r
-    obj = PyObject_CallMethod(module, "_strptime", "ss", string, format);\r
-    if (obj != NULL) {\r
-        int i, good_timetuple = 1;\r
-        long int ia[7];\r
-        if (PySequence_Check(obj) && PySequence_Size(obj) == 2) {\r
-            st = PySequence_GetItem(obj, 0);\r
-            frac = PySequence_GetItem(obj, 1);\r
-            if (st == NULL || frac == NULL)\r
-                good_timetuple = 0;\r
-            /* copy y/m/d/h/m/s values out of the\r
-               time.struct_time */\r
-            if (good_timetuple &&\r
-                PySequence_Check(st) &&\r
-                PySequence_Size(st) >= 6) {\r
-                for (i=0; i < 6; i++) {\r
-                    PyObject *p = PySequence_GetItem(st, i);\r
-                    if (p == NULL) {\r
-                        good_timetuple = 0;\r
-                        break;\r
-                    }\r
-                    if (PyInt_Check(p))\r
-                        ia[i] = PyInt_AsLong(p);\r
-                    else\r
-                        good_timetuple = 0;\r
-                    Py_DECREF(p);\r
-                }\r
-            }\r
-            else\r
-                good_timetuple = 0;\r
-            /* follow that up with a little dose of microseconds */\r
-            if (good_timetuple && PyInt_Check(frac))\r
-                ia[6] = PyInt_AsLong(frac);\r
-            else\r
-                good_timetuple = 0;\r
-        }\r
-        else\r
-            good_timetuple = 0;\r
-        if (good_timetuple)\r
-            result = PyObject_CallFunction(cls, "iiiiiii",\r
-                                           ia[0], ia[1], ia[2],\r
-                                           ia[3], ia[4], ia[5],\r
-                                           ia[6]);\r
-        else\r
-            PyErr_SetString(PyExc_ValueError,\r
-                "unexpected value from _strptime._strptime");\r
-    }\r
-    Py_XDECREF(obj);\r
-    Py_XDECREF(st);\r
-    Py_XDECREF(frac);\r
-    return result;\r
-}\r
-\r
-/* Return new datetime from date/datetime and time arguments. */\r
-static PyObject *\r
-datetime_combine(PyObject *cls, PyObject *args, PyObject *kw)\r
-{\r
-    static char *keywords[] = {"date", "time", NULL};\r
-    PyObject *date;\r
-    PyObject *time;\r
-    PyObject *result = NULL;\r
-\r
-    if (PyArg_ParseTupleAndKeywords(args, kw, "O!O!:combine", keywords,\r
-                                    &PyDateTime_DateType, &date,\r
-                                    &PyDateTime_TimeType, &time)) {\r
-        PyObject *tzinfo = Py_None;\r
-\r
-        if (HASTZINFO(time))\r
-            tzinfo = ((PyDateTime_Time *)time)->tzinfo;\r
-        result = PyObject_CallFunction(cls, "iiiiiiiO",\r
-                                        GET_YEAR(date),\r
-                                        GET_MONTH(date),\r
-                                        GET_DAY(date),\r
-                                        TIME_GET_HOUR(time),\r
-                                        TIME_GET_MINUTE(time),\r
-                                        TIME_GET_SECOND(time),\r
-                                        TIME_GET_MICROSECOND(time),\r
-                                        tzinfo);\r
-    }\r
-    return result;\r
-}\r
-\r
-/*\r
- * Destructor.\r
- */\r
-\r
-static void\r
-datetime_dealloc(PyDateTime_DateTime *self)\r
-{\r
-    if (HASTZINFO(self)) {\r
-        Py_XDECREF(self->tzinfo);\r
-    }\r
-    Py_TYPE(self)->tp_free((PyObject *)self);\r
-}\r
-\r
-/*\r
- * Indirect access to tzinfo methods.\r
- */\r
-\r
-/* These are all METH_NOARGS, so don't need to check the arglist. */\r
-static PyObject *\r
-datetime_utcoffset(PyDateTime_DateTime *self, PyObject *unused) {\r
-    return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,\r
-                               "utcoffset", (PyObject *)self);\r
-}\r
-\r
-static PyObject *\r
-datetime_dst(PyDateTime_DateTime *self, PyObject *unused) {\r
-    return offset_as_timedelta(HASTZINFO(self) ? self->tzinfo : Py_None,\r
-                               "dst", (PyObject *)self);\r
-}\r
-\r
-static PyObject *\r
-datetime_tzname(PyDateTime_DateTime *self, PyObject *unused) {\r
-    return call_tzname(HASTZINFO(self) ? self->tzinfo : Py_None,\r
-                       (PyObject *)self);\r
-}\r
-\r
-/*\r
- * datetime arithmetic.\r
- */\r
-\r
-/* factor must be 1 (to add) or -1 (to subtract).  The result inherits\r
- * the tzinfo state of date.\r
- */\r
-static PyObject *\r
-add_datetime_timedelta(PyDateTime_DateTime *date, PyDateTime_Delta *delta,\r
-                       int factor)\r
-{\r
-    /* Note that the C-level additions can't overflow, because of\r
-     * invariant bounds on the member values.\r
-     */\r
-    int year = GET_YEAR(date);\r
-    int month = GET_MONTH(date);\r
-    int day = GET_DAY(date) + GET_TD_DAYS(delta) * factor;\r
-    int hour = DATE_GET_HOUR(date);\r
-    int minute = DATE_GET_MINUTE(date);\r
-    int second = DATE_GET_SECOND(date) + GET_TD_SECONDS(delta) * factor;\r
-    int microsecond = DATE_GET_MICROSECOND(date) +\r
-                      GET_TD_MICROSECONDS(delta) * factor;\r
-\r
-    assert(factor == 1 || factor == -1);\r
-    if (normalize_datetime(&year, &month, &day,\r
-                           &hour, &minute, &second, &microsecond) < 0)\r
-        return NULL;\r
-    else\r
-        return new_datetime(year, month, day,\r
-                            hour, minute, second, microsecond,\r
-                            HASTZINFO(date) ? date->tzinfo : Py_None);\r
-}\r
-\r
-static PyObject *\r
-datetime_add(PyObject *left, PyObject *right)\r
-{\r
-    if (PyDateTime_Check(left)) {\r
-        /* datetime + ??? */\r
-        if (PyDelta_Check(right))\r
-            /* datetime + delta */\r
-            return add_datetime_timedelta(\r
-                            (PyDateTime_DateTime *)left,\r
-                            (PyDateTime_Delta *)right,\r
-                            1);\r
-    }\r
-    else if (PyDelta_Check(left)) {\r
-        /* delta + datetime */\r
-        return add_datetime_timedelta((PyDateTime_DateTime *) right,\r
-                                      (PyDateTime_Delta *) left,\r
-                                      1);\r
-    }\r
-    Py_INCREF(Py_NotImplemented);\r
-    return Py_NotImplemented;\r
-}\r
-\r
-static PyObject *\r
-datetime_subtract(PyObject *left, PyObject *right)\r
-{\r
-    PyObject *result = Py_NotImplemented;\r
-\r
-    if (PyDateTime_Check(left)) {\r
-        /* datetime - ??? */\r
-        if (PyDateTime_Check(right)) {\r
-            /* datetime - datetime */\r
-            naivety n1, n2;\r
-            int offset1, offset2;\r
-            int delta_d, delta_s, delta_us;\r
-\r
-            if (classify_two_utcoffsets(left, &offset1, &n1, left,\r
-                                        right, &offset2, &n2,\r
-                                        right) < 0)\r
-                return NULL;\r
-            assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);\r
-            if (n1 != n2) {\r
-                PyErr_SetString(PyExc_TypeError,\r
-                    "can't subtract offset-naive and "\r
-                    "offset-aware datetimes");\r
-                return NULL;\r
-            }\r
-            delta_d = ymd_to_ord(GET_YEAR(left),\r
-                                 GET_MONTH(left),\r
-                                 GET_DAY(left)) -\r
-                      ymd_to_ord(GET_YEAR(right),\r
-                                 GET_MONTH(right),\r
-                                 GET_DAY(right));\r
-            /* These can't overflow, since the values are\r
-             * normalized.  At most this gives the number of\r
-             * seconds in one day.\r
-             */\r
-            delta_s = (DATE_GET_HOUR(left) -\r
-                       DATE_GET_HOUR(right)) * 3600 +\r
-                      (DATE_GET_MINUTE(left) -\r
-                       DATE_GET_MINUTE(right)) * 60 +\r
-                      (DATE_GET_SECOND(left) -\r
-                       DATE_GET_SECOND(right));\r
-            delta_us = DATE_GET_MICROSECOND(left) -\r
-                       DATE_GET_MICROSECOND(right);\r
-            /* (left - offset1) - (right - offset2) =\r
-             * (left - right) + (offset2 - offset1)\r
-             */\r
-            delta_s += (offset2 - offset1) * 60;\r
-            result = new_delta(delta_d, delta_s, delta_us, 1);\r
-        }\r
-        else if (PyDelta_Check(right)) {\r
-            /* datetime - delta */\r
-            result = add_datetime_timedelta(\r
-                            (PyDateTime_DateTime *)left,\r
-                            (PyDateTime_Delta *)right,\r
-                            -1);\r
-        }\r
-    }\r
-\r
-    if (result == Py_NotImplemented)\r
-        Py_INCREF(result);\r
-    return result;\r
-}\r
-\r
-/* Various ways to turn a datetime into a string. */\r
-\r
-static PyObject *\r
-datetime_repr(PyDateTime_DateTime *self)\r
-{\r
-    char buffer[1000];\r
-    const char *type_name = Py_TYPE(self)->tp_name;\r
-    PyObject *baserepr;\r
-\r
-    if (DATE_GET_MICROSECOND(self)) {\r
-        PyOS_snprintf(buffer, sizeof(buffer),\r
-                      "%s(%d, %d, %d, %d, %d, %d, %d)",\r
-                      type_name,\r
-                      GET_YEAR(self), GET_MONTH(self), GET_DAY(self),\r
-                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self),\r
-                      DATE_GET_SECOND(self),\r
-                      DATE_GET_MICROSECOND(self));\r
-    }\r
-    else if (DATE_GET_SECOND(self)) {\r
-        PyOS_snprintf(buffer, sizeof(buffer),\r
-                      "%s(%d, %d, %d, %d, %d, %d)",\r
-                      type_name,\r
-                      GET_YEAR(self), GET_MONTH(self), GET_DAY(self),\r
-                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self),\r
-                      DATE_GET_SECOND(self));\r
-    }\r
-    else {\r
-        PyOS_snprintf(buffer, sizeof(buffer),\r
-                      "%s(%d, %d, %d, %d, %d)",\r
-                      type_name,\r
-                      GET_YEAR(self), GET_MONTH(self), GET_DAY(self),\r
-                      DATE_GET_HOUR(self), DATE_GET_MINUTE(self));\r
-    }\r
-    baserepr = PyString_FromString(buffer);\r
-    if (baserepr == NULL || ! HASTZINFO(self))\r
-        return baserepr;\r
-    return append_keyword_tzinfo(baserepr, self->tzinfo);\r
-}\r
-\r
-static PyObject *\r
-datetime_str(PyDateTime_DateTime *self)\r
-{\r
-    return PyObject_CallMethod((PyObject *)self, "isoformat", "(s)", " ");\r
-}\r
-\r
-static PyObject *\r
-datetime_isoformat(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)\r
-{\r
-    char sep = 'T';\r
-    static char *keywords[] = {"sep", NULL};\r
-    char buffer[100];\r
-    char *cp;\r
-    PyObject *result;\r
-\r
-    if (!PyArg_ParseTupleAndKeywords(args, kw, "|c:isoformat", keywords,\r
-                                     &sep))\r
-        return NULL;\r
-    cp = isoformat_date((PyDateTime_Date *)self, buffer, sizeof(buffer));\r
-    assert(cp != NULL);\r
-    *cp++ = sep;\r
-    cp = isoformat_time(self, cp, sizeof(buffer) - (cp - buffer));\r
-    result = PyString_FromStringAndSize(buffer, cp - buffer);\r
-    if (result == NULL || ! HASTZINFO(self))\r
-        return result;\r
-\r
-    /* We need to append the UTC offset. */\r
-    if (format_utcoffset(buffer, sizeof(buffer), ":", self->tzinfo,\r
-                         (PyObject *)self) < 0) {\r
-        Py_DECREF(result);\r
-        return NULL;\r
-    }\r
-    PyString_ConcatAndDel(&result, PyString_FromString(buffer));\r
-    return result;\r
-}\r
-\r
-static PyObject *\r
-datetime_ctime(PyDateTime_DateTime *self)\r
-{\r
-    return format_ctime((PyDateTime_Date *)self,\r
-                        DATE_GET_HOUR(self),\r
-                        DATE_GET_MINUTE(self),\r
-                        DATE_GET_SECOND(self));\r
-}\r
-\r
-/* Miscellaneous methods. */\r
-\r
-/* This is more natural as a tp_compare, but doesn't work then:  for whatever\r
- * reason, Python's try_3way_compare ignores tp_compare unless\r
- * PyInstance_Check returns true, but these aren't old-style classes.\r
- */\r
-static PyObject *\r
-datetime_richcompare(PyDateTime_DateTime *self, PyObject *other, int op)\r
-{\r
-    int diff;\r
-    naivety n1, n2;\r
-    int offset1, offset2;\r
-\r
-    if (! PyDateTime_Check(other)) {\r
-        /* If other has a "timetuple" attr, that's an advertised\r
-         * hook for other classes to ask to get comparison control.\r
-         * However, date instances have a timetuple attr, and we\r
-         * don't want to allow that comparison.  Because datetime\r
-         * is a subclass of date, when mixing date and datetime\r
-         * in a comparison, Python gives datetime the first shot\r
-         * (it's the more specific subtype).  So we can stop that\r
-         * combination here reliably.\r
-         */\r
-        if (PyObject_HasAttrString(other, "timetuple") &&\r
-            ! PyDate_Check(other)) {\r
-            /* A hook for other kinds of datetime objects. */\r
-            Py_INCREF(Py_NotImplemented);\r
-            return Py_NotImplemented;\r
-        }\r
-        if (op == Py_EQ || op == Py_NE) {\r
-            PyObject *result = op == Py_EQ ? Py_False : Py_True;\r
-            Py_INCREF(result);\r
-            return result;\r
-        }\r
-        /* Stop this from falling back to address comparison. */\r
-        return cmperror((PyObject *)self, other);\r
-    }\r
-\r
-    if (classify_two_utcoffsets((PyObject *)self, &offset1, &n1,\r
-                                (PyObject *)self,\r
-                                 other, &offset2, &n2,\r
-                                 other) < 0)\r
-        return NULL;\r
-    assert(n1 != OFFSET_UNKNOWN && n2 != OFFSET_UNKNOWN);\r
-    /* If they're both naive, or both aware and have the same offsets,\r
-     * we get off cheap.  Note that if they're both naive, offset1 ==\r
-     * offset2 == 0 at this point.\r
-     */\r
-    if (n1 == n2 && offset1 == offset2) {\r
-        diff = memcmp(self->data, ((PyDateTime_DateTime *)other)->data,\r
-                      _PyDateTime_DATETIME_DATASIZE);\r
-        return diff_to_bool(diff, op);\r
-    }\r
-\r
-    if (n1 == OFFSET_AWARE && n2 == OFFSET_AWARE) {\r
-        PyDateTime_Delta *delta;\r
-\r
-        assert(offset1 != offset2);             /* else last "if" handled it */\r
-        delta = (PyDateTime_Delta *)datetime_subtract((PyObject *)self,\r
-                                                       other);\r
-        if (delta == NULL)\r
-            return NULL;\r
-        diff = GET_TD_DAYS(delta);\r
-        if (diff == 0)\r
-            diff = GET_TD_SECONDS(delta) |\r
-                   GET_TD_MICROSECONDS(delta);\r
-        Py_DECREF(delta);\r
-        return diff_to_bool(diff, op);\r
-    }\r
-\r
-    assert(n1 != n2);\r
-    PyErr_SetString(PyExc_TypeError,\r
-                    "can't compare offset-naive and "\r
-                    "offset-aware datetimes");\r
-    return NULL;\r
-}\r
-\r
-static long\r
-datetime_hash(PyDateTime_DateTime *self)\r
-{\r
-    if (self->hashcode == -1) {\r
-        naivety n;\r
-        int offset;\r
-        PyObject *temp;\r
-\r
-        n = classify_utcoffset((PyObject *)self, (PyObject *)self,\r
-                               &offset);\r
-        assert(n != OFFSET_UNKNOWN);\r
-        if (n == OFFSET_ERROR)\r
-            return -1;\r
-\r
-        /* Reduce this to a hash of another object. */\r
-        if (n == OFFSET_NAIVE)\r
-            temp = PyString_FromStringAndSize(\r
-                            (char *)self->data,\r
-                            _PyDateTime_DATETIME_DATASIZE);\r
-        else {\r
-            int days;\r
-            int seconds;\r
-\r
-            assert(n == OFFSET_AWARE);\r
-            assert(HASTZINFO(self));\r
-            days = ymd_to_ord(GET_YEAR(self),\r
-                              GET_MONTH(self),\r
-                              GET_DAY(self));\r
-            seconds = DATE_GET_HOUR(self) * 3600 +\r
-                      (DATE_GET_MINUTE(self) - offset) * 60 +\r
-                      DATE_GET_SECOND(self);\r
-            temp = new_delta(days,\r
-                             seconds,\r
-                             DATE_GET_MICROSECOND(self),\r
-                             1);\r
-        }\r
-        if (temp != NULL) {\r
-            self->hashcode = PyObject_Hash(temp);\r
-            Py_DECREF(temp);\r
-        }\r
-    }\r
-    return self->hashcode;\r
-}\r
-\r
-static PyObject *\r
-datetime_replace(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)\r
-{\r
-    PyObject *clone;\r
-    PyObject *tuple;\r
-    int y = GET_YEAR(self);\r
-    int m = GET_MONTH(self);\r
-    int d = GET_DAY(self);\r
-    int hh = DATE_GET_HOUR(self);\r
-    int mm = DATE_GET_MINUTE(self);\r
-    int ss = DATE_GET_SECOND(self);\r
-    int us = DATE_GET_MICROSECOND(self);\r
-    PyObject *tzinfo = HASTZINFO(self) ? self->tzinfo : Py_None;\r
-\r
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "|iiiiiiiO:replace",\r
-                                      datetime_kws,\r
-                                      &y, &m, &d, &hh, &mm, &ss, &us,\r
-                                      &tzinfo))\r
-        return NULL;\r
-    tuple = Py_BuildValue("iiiiiiiO", y, m, d, hh, mm, ss, us, tzinfo);\r
-    if (tuple == NULL)\r
-        return NULL;\r
-    clone = datetime_new(Py_TYPE(self), tuple, NULL);\r
-    Py_DECREF(tuple);\r
-    return clone;\r
-}\r
-\r
-static PyObject *\r
-datetime_astimezone(PyDateTime_DateTime *self, PyObject *args, PyObject *kw)\r
-{\r
-    int y, m, d, hh, mm, ss, us;\r
-    PyObject *result;\r
-    int offset, none;\r
-\r
-    PyObject *tzinfo;\r
-    static char *keywords[] = {"tz", NULL};\r
-\r
-    if (! PyArg_ParseTupleAndKeywords(args, kw, "O!:astimezone", keywords,\r
-                                      &PyDateTime_TZInfoType, &tzinfo))\r
-        return NULL;\r
-\r
-    if (!HASTZINFO(self) || self->tzinfo == Py_None)\r
-        goto NeedAware;\r
-\r
-    /* Conversion to self's own time zone is a NOP. */\r
-    if (self->tzinfo == tzinfo) {\r
-        Py_INCREF(self);\r
-        return (PyObject *)self;\r
-    }\r
-\r
-    /* Convert self to UTC. */\r
-    offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);\r
-    if (offset == -1 && PyErr_Occurred())\r
-        return NULL;\r
-    if (none)\r
-        goto NeedAware;\r
-\r
-    y = GET_YEAR(self);\r
-    m = GET_MONTH(self);\r
-    d = GET_DAY(self);\r
-    hh = DATE_GET_HOUR(self);\r
-    mm = DATE_GET_MINUTE(self);\r
-    ss = DATE_GET_SECOND(self);\r
-    us = DATE_GET_MICROSECOND(self);\r
-\r
-    mm -= offset;\r
-    if ((mm < 0 || mm >= 60) &&\r
-        normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us) < 0)\r
-        return NULL;\r
-\r
-    /* Attach new tzinfo and let fromutc() do the rest. */\r
-    result = new_datetime(y, m, d, hh, mm, ss, us, tzinfo);\r
-    if (result != NULL) {\r
-        PyObject *temp = result;\r
-\r
-        result = PyObject_CallMethod(tzinfo, "fromutc", "O", temp);\r
-        Py_DECREF(temp);\r
-    }\r
-    return result;\r
-\r
-NeedAware:\r
-    PyErr_SetString(PyExc_ValueError, "astimezone() cannot be applied to "\r
-                                      "a naive datetime");\r
-    return NULL;\r
-}\r
-\r
-static PyObject *\r
-datetime_timetuple(PyDateTime_DateTime *self)\r
-{\r
-    int dstflag = -1;\r
-\r
-    if (HASTZINFO(self) && self->tzinfo != Py_None) {\r
-        int none;\r
-\r
-        dstflag = call_dst(self->tzinfo, (PyObject *)self, &none);\r
-        if (dstflag == -1 && PyErr_Occurred())\r
-            return NULL;\r
-\r
-        if (none)\r
-            dstflag = -1;\r
-        else if (dstflag != 0)\r
-            dstflag = 1;\r
-\r
-    }\r
-    return build_struct_time(GET_YEAR(self),\r
-                             GET_MONTH(self),\r
-                             GET_DAY(self),\r
-                             DATE_GET_HOUR(self),\r
-                             DATE_GET_MINUTE(self),\r
-                             DATE_GET_SECOND(self),\r
-                             dstflag);\r
-}\r
-\r
-static PyObject *\r
-datetime_getdate(PyDateTime_DateTime *self)\r
-{\r
-    return new_date(GET_YEAR(self),\r
-                    GET_MONTH(self),\r
-                    GET_DAY(self));\r
-}\r
-\r
-static PyObject *\r
-datetime_gettime(PyDateTime_DateTime *self)\r
-{\r
-    return new_time(DATE_GET_HOUR(self),\r
-                    DATE_GET_MINUTE(self),\r
-                    DATE_GET_SECOND(self),\r
-                    DATE_GET_MICROSECOND(self),\r
-                    Py_None);\r
-}\r
-\r
-static PyObject *\r
-datetime_gettimetz(PyDateTime_DateTime *self)\r
-{\r
-    return new_time(DATE_GET_HOUR(self),\r
-                    DATE_GET_MINUTE(self),\r
-                    DATE_GET_SECOND(self),\r
-                    DATE_GET_MICROSECOND(self),\r
-                    HASTZINFO(self) ? self->tzinfo : Py_None);\r
-}\r
-\r
-static PyObject *\r
-datetime_utctimetuple(PyDateTime_DateTime *self)\r
-{\r
-    int y = GET_YEAR(self);\r
-    int m = GET_MONTH(self);\r
-    int d = GET_DAY(self);\r
-    int hh = DATE_GET_HOUR(self);\r
-    int mm = DATE_GET_MINUTE(self);\r
-    int ss = DATE_GET_SECOND(self);\r
-    int us = 0;         /* microseconds are ignored in a timetuple */\r
-    int offset = 0;\r
-\r
-    if (HASTZINFO(self) && self->tzinfo != Py_None) {\r
-        int none;\r
-\r
-        offset = call_utcoffset(self->tzinfo, (PyObject *)self, &none);\r
-        if (offset == -1 && PyErr_Occurred())\r
-            return NULL;\r
-    }\r
-    /* Even if offset is 0, don't call timetuple() -- tm_isdst should be\r
-     * 0 in a UTC timetuple regardless of what dst() says.\r
-     */\r
-    if (offset) {\r
-        /* Subtract offset minutes & normalize. */\r
-        int stat;\r
-\r
-        mm -= offset;\r
-        stat = normalize_datetime(&y, &m, &d, &hh, &mm, &ss, &us);\r
-        if (stat < 0) {\r
-            /* At the edges, it's possible we overflowed\r
-             * beyond MINYEAR or MAXYEAR.\r
-             */\r
-            if (PyErr_ExceptionMatches(PyExc_OverflowError))\r
-                PyErr_Clear();\r
-            else\r
-                return NULL;\r
-        }\r
-    }\r
-    return build_struct_time(y, m, d, hh, mm, ss, 0);\r
-}\r
-\r
-/* Pickle support, a simple use of __reduce__. */\r
-\r
-/* Let basestate be the non-tzinfo data string.\r
- * If tzinfo is None, this returns (basestate,), else (basestate, tzinfo).\r
- * So it's a tuple in any (non-error) case.\r
- * __getstate__ isn't exposed.\r
- */\r
-static PyObject *\r
-datetime_getstate(PyDateTime_DateTime *self)\r
-{\r
-    PyObject *basestate;\r
-    PyObject *result = NULL;\r
-\r
-    basestate = PyString_FromStringAndSize((char *)self->data,\r
-                                      _PyDateTime_DATETIME_DATASIZE);\r
-    if (basestate != NULL) {\r
-        if (! HASTZINFO(self) || self->tzinfo == Py_None)\r
-            result = PyTuple_Pack(1, basestate);\r
-        else\r
-            result = PyTuple_Pack(2, basestate, self->tzinfo);\r
-        Py_DECREF(basestate);\r
-    }\r
-    return result;\r
-}\r
-\r
-static PyObject *\r
-datetime_reduce(PyDateTime_DateTime *self, PyObject *arg)\r
-{\r
-    return Py_BuildValue("(ON)", Py_TYPE(self), datetime_getstate(self));\r
-}\r
-\r
-static PyMethodDef datetime_methods[] = {\r
-\r
-    /* Class methods: */\r
-\r
-    {"now",         (PyCFunction)datetime_now,\r
-     METH_VARARGS | METH_KEYWORDS | METH_CLASS,\r
-     PyDoc_STR("[tz] -> new datetime with tz's local day and time.")},\r
-\r
-    {"utcnow",         (PyCFunction)datetime_utcnow,\r
-     METH_NOARGS | METH_CLASS,\r
-     PyDoc_STR("Return a new datetime representing UTC day and time.")},\r
-\r
-    {"fromtimestamp", (PyCFunction)datetime_fromtimestamp,\r
-     METH_VARARGS | METH_KEYWORDS | METH_CLASS,\r
-     PyDoc_STR("timestamp[, tz] -> tz's local time from POSIX timestamp.")},\r
-\r
-    {"utcfromtimestamp", (PyCFunction)datetime_utcfromtimestamp,\r
-     METH_VARARGS | METH_CLASS,\r
-     PyDoc_STR("timestamp -> UTC datetime from a POSIX timestamp "\r
-               "(like time.time()).")},\r
-\r
-    {"strptime", (PyCFunction)datetime_strptime,\r
-     METH_VARARGS | METH_CLASS,\r
-     PyDoc_STR("string, format -> new datetime parsed from a string "\r
-               "(like time.strptime()).")},\r
-\r
-    {"combine", (PyCFunction)datetime_combine,\r
-     METH_VARARGS | METH_KEYWORDS | METH_CLASS,\r
-     PyDoc_STR("date, time -> datetime with same date and time fields")},\r
-\r
-    /* Instance methods: */\r
-\r
-    {"date",   (PyCFunction)datetime_getdate, METH_NOARGS,\r
-     PyDoc_STR("Return date object with same year, month and day.")},\r
-\r
-    {"time",   (PyCFunction)datetime_gettime, METH_NOARGS,\r
-     PyDoc_STR("Return time object with same time but with tzinfo=None.")},\r
-\r
-    {"timetz",   (PyCFunction)datetime_gettimetz, METH_NOARGS,\r
-     PyDoc_STR("Return time object with same time and tzinfo.")},\r
-\r
-    {"ctime",       (PyCFunction)datetime_ctime,        METH_NOARGS,\r
-     PyDoc_STR("Return ctime() style string.")},\r
-\r
-    {"timetuple",   (PyCFunction)datetime_timetuple, METH_NOARGS,\r
-     PyDoc_STR("Return time tuple, compatible with time.localtime().")},\r
-\r
-    {"utctimetuple",   (PyCFunction)datetime_utctimetuple, METH_NOARGS,\r
-     PyDoc_STR("Return UTC time tuple, compatible with time.localtime().")},\r
-\r
-    {"isoformat",   (PyCFunction)datetime_isoformat, METH_VARARGS | METH_KEYWORDS,\r
-     PyDoc_STR("[sep] -> string in ISO 8601 format, "\r
-               "YYYY-MM-DDTHH:MM:SS[.mmmmmm][+HH:MM].\n\n"\r
-               "sep is used to separate the year from the time, and "\r
-               "defaults to 'T'.")},\r
-\r
-    {"utcoffset",       (PyCFunction)datetime_utcoffset, METH_NOARGS,\r
-     PyDoc_STR("Return self.tzinfo.utcoffset(self).")},\r
-\r
-    {"tzname",          (PyCFunction)datetime_tzname,   METH_NOARGS,\r
-     PyDoc_STR("Return self.tzinfo.tzname(self).")},\r
-\r
-    {"dst",             (PyCFunction)datetime_dst, METH_NOARGS,\r
-     PyDoc_STR("Return self.tzinfo.dst(self).")},\r
-\r
-    {"replace",     (PyCFunction)datetime_replace,      METH_VARARGS | METH_KEYWORDS,\r
-     PyDoc_STR("Return datetime with new specified fields.")},\r
-\r
-    {"astimezone",  (PyCFunction)datetime_astimezone, METH_VARARGS | METH_KEYWORDS,\r
-     PyDoc_STR("tz -> convert to local time in new timezone tz\n")},\r
-\r
-    {"__reduce__", (PyCFunction)datetime_reduce,     METH_NOARGS,\r
-     PyDoc_STR("__reduce__() -> (cls, state)")},\r
-\r
-    {NULL,      NULL}\r
-};\r
-\r
-static char datetime_doc[] =\r
-PyDoc_STR("datetime(year, month, day[, hour[, minute[, second[, microsecond[,tzinfo]]]]])\n\\r
-\n\\r
-The year, month and day arguments are required. tzinfo may be None, or an\n\\r
-instance of a tzinfo subclass. The remaining arguments may be ints or longs.\n");\r
-\r
-static PyNumberMethods datetime_as_number = {\r
-    datetime_add,                               /* nb_add */\r
-    datetime_subtract,                          /* nb_subtract */\r
-    0,                                          /* nb_multiply */\r
-    0,                                          /* nb_divide */\r
-    0,                                          /* nb_remainder */\r
-    0,                                          /* nb_divmod */\r
-    0,                                          /* nb_power */\r
-    0,                                          /* nb_negative */\r
-    0,                                          /* nb_positive */\r
-    0,                                          /* nb_absolute */\r
-    0,                                          /* nb_nonzero */\r
-};\r
-\r
-statichere PyTypeObject PyDateTime_DateTimeType = {\r
-    PyObject_HEAD_INIT(NULL)\r
-    0,                                          /* ob_size */\r
-    "datetime.datetime",                        /* tp_name */\r
-    sizeof(PyDateTime_DateTime),                /* tp_basicsize */\r
-    0,                                          /* tp_itemsize */\r
-    (destructor)datetime_dealloc,               /* tp_dealloc */\r
-    0,                                          /* tp_print */\r
-    0,                                          /* tp_getattr */\r
-    0,                                          /* tp_setattr */\r
-    0,                                          /* tp_compare */\r
-    (reprfunc)datetime_repr,                    /* tp_repr */\r
-    &datetime_as_number,                        /* tp_as_number */\r
-    0,                                          /* tp_as_sequence */\r
-    0,                                          /* tp_as_mapping */\r
-    (hashfunc)datetime_hash,                    /* tp_hash */\r
-    0,                                          /* tp_call */\r
-    (reprfunc)datetime_str,                     /* tp_str */\r
-    PyObject_GenericGetAttr,                    /* tp_getattro */\r
-    0,                                          /* tp_setattro */\r
-    0,                                          /* tp_as_buffer */\r
-    Py_TPFLAGS_DEFAULT | Py_TPFLAGS_CHECKTYPES |\r
-    Py_TPFLAGS_BASETYPE,                        /* tp_flags */\r
-    datetime_doc,                               /* tp_doc */\r
-    0,                                          /* tp_traverse */\r
-    0,                                          /* tp_clear */\r
-    (richcmpfunc)datetime_richcompare,          /* tp_richcompare */\r
-    0,                                          /* tp_weaklistoffset */\r
-    0,                                          /* tp_iter */\r
-    0,                                          /* tp_iternext */\r
-    datetime_methods,                           /* tp_methods */\r
-    0,                                          /* tp_members */\r
-    datetime_getset,                            /* tp_getset */\r
-    &PyDateTime_DateType,                       /* tp_base */\r
-    0,                                          /* tp_dict */\r
-    0,                                          /* tp_descr_get */\r
-    0,                                          /* tp_descr_set */\r
-    0,                                          /* tp_dictoffset */\r
-    0,                                          /* tp_init */\r
-    datetime_alloc,                             /* tp_alloc */\r
-    datetime_new,                               /* tp_new */\r
-    0,                                          /* tp_free */\r
-};\r
-\r
-/* ---------------------------------------------------------------------------\r
- * Module methods and initialization.\r
- */\r
-\r
-static PyMethodDef module_methods[] = {\r
-    {NULL, NULL}\r
-};\r
-\r
-/* C API.  Clients get at this via PyDateTime_IMPORT, defined in\r
- * datetime.h.\r
- */\r
-static PyDateTime_CAPI CAPI = {\r
-    &PyDateTime_DateType,\r
-    &PyDateTime_DateTimeType,\r
-    &PyDateTime_TimeType,\r
-    &PyDateTime_DeltaType,\r
-    &PyDateTime_TZInfoType,\r
-    new_date_ex,\r
-    new_datetime_ex,\r
-    new_time_ex,\r
-    new_delta_ex,\r
-    datetime_fromtimestamp,\r
-    date_fromtimestamp\r
-};\r
-\r
-\r
-PyMODINIT_FUNC\r
-initdatetime(void)\r
-{\r
-    PyObject *m;        /* a module object */\r
-    PyObject *d;        /* its dict */\r
-    PyObject *x;\r
-\r
-    m = Py_InitModule3("datetime", module_methods,\r
-                       "Fast implementation of the datetime type.");\r
-    if (m == NULL)\r
-        return;\r
-\r
-    if (PyType_Ready(&PyDateTime_DateType) < 0)\r
-        return;\r
-    if (PyType_Ready(&PyDateTime_DateTimeType) < 0)\r
-        return;\r
-    if (PyType_Ready(&PyDateTime_DeltaType) < 0)\r
-        return;\r
-    if (PyType_Ready(&PyDateTime_TimeType) < 0)\r
-        return;\r
-    if (PyType_Ready(&PyDateTime_TZInfoType) < 0)\r
-        return;\r
-\r
-    /* timedelta values */\r
-    d = PyDateTime_DeltaType.tp_dict;\r
-\r
-    x = new_delta(0, 0, 1, 0);\r
-    if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)\r
-        return;\r
-    Py_DECREF(x);\r
-\r
-    x = new_delta(-MAX_DELTA_DAYS, 0, 0, 0);\r
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)\r
-        return;\r
-    Py_DECREF(x);\r
-\r
-    x = new_delta(MAX_DELTA_DAYS, 24*3600-1, 1000000-1, 0);\r
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)\r
-        return;\r
-    Py_DECREF(x);\r
-\r
-    /* date values */\r
-    d = PyDateTime_DateType.tp_dict;\r
-\r
-    x = new_date(1, 1, 1);\r
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)\r
-        return;\r
-    Py_DECREF(x);\r
-\r
-    x = new_date(MAXYEAR, 12, 31);\r
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)\r
-        return;\r
-    Py_DECREF(x);\r
-\r
-    x = new_delta(1, 0, 0, 0);\r
-    if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)\r
-        return;\r
-    Py_DECREF(x);\r
-\r
-    /* time values */\r
-    d = PyDateTime_TimeType.tp_dict;\r
-\r
-    x = new_time(0, 0, 0, 0, Py_None);\r
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)\r
-        return;\r
-    Py_DECREF(x);\r
-\r
-    x = new_time(23, 59, 59, 999999, Py_None);\r
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)\r
-        return;\r
-    Py_DECREF(x);\r
-\r
-    x = new_delta(0, 0, 1, 0);\r
-    if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)\r
-        return;\r
-    Py_DECREF(x);\r
-\r
-    /* datetime values */\r
-    d = PyDateTime_DateTimeType.tp_dict;\r
-\r
-    x = new_datetime(1, 1, 1, 0, 0, 0, 0, Py_None);\r
-    if (x == NULL || PyDict_SetItemString(d, "min", x) < 0)\r
-        return;\r
-    Py_DECREF(x);\r
-\r
-    x = new_datetime(MAXYEAR, 12, 31, 23, 59, 59, 999999, Py_None);\r
-    if (x == NULL || PyDict_SetItemString(d, "max", x) < 0)\r
-        return;\r
-    Py_DECREF(x);\r
-\r
-    x = new_delta(0, 0, 1, 0);\r
-    if (x == NULL || PyDict_SetItemString(d, "resolution", x) < 0)\r
-        return;\r
-    Py_DECREF(x);\r
-\r
-    /* module initialization */\r
-    PyModule_AddIntConstant(m, "MINYEAR", MINYEAR);\r
-    PyModule_AddIntConstant(m, "MAXYEAR", MAXYEAR);\r
-\r
-    Py_INCREF(&PyDateTime_DateType);\r
-    PyModule_AddObject(m, "date", (PyObject *) &PyDateTime_DateType);\r
-\r
-    Py_INCREF(&PyDateTime_DateTimeType);\r
-    PyModule_AddObject(m, "datetime",\r
-                       (PyObject *)&PyDateTime_DateTimeType);\r
-\r
-    Py_INCREF(&PyDateTime_TimeType);\r
-    PyModule_AddObject(m, "time", (PyObject *) &PyDateTime_TimeType);\r
-\r
-    Py_INCREF(&PyDateTime_DeltaType);\r
-    PyModule_AddObject(m, "timedelta", (PyObject *) &PyDateTime_DeltaType);\r
-\r
-    Py_INCREF(&PyDateTime_TZInfoType);\r
-    PyModule_AddObject(m, "tzinfo", (PyObject *) &PyDateTime_TZInfoType);\r
-\r
-    x = PyCapsule_New(&CAPI, PyDateTime_CAPSULE_NAME, NULL);\r
-    if (x == NULL)\r
-        return;\r
-    PyModule_AddObject(m, "datetime_CAPI", x);\r
-\r
-    /* A 4-year cycle has an extra leap day over what we'd get from\r
-     * pasting together 4 single years.\r
-     */\r
-    assert(DI4Y == 4 * 365 + 1);\r
-    assert(DI4Y == days_before_year(4+1));\r
-\r
-    /* Similarly, a 400-year cycle has an extra leap day over what we'd\r
-     * get from pasting together 4 100-year cycles.\r
-     */\r
-    assert(DI400Y == 4 * DI100Y + 1);\r
-    assert(DI400Y == days_before_year(400+1));\r
-\r
-    /* OTOH, a 100-year cycle has one fewer leap day than we'd get from\r
-     * pasting together 25 4-year cycles.\r
-     */\r
-    assert(DI100Y == 25 * DI4Y - 1);\r
-    assert(DI100Y == days_before_year(100+1));\r
-\r
-    us_per_us = PyInt_FromLong(1);\r
-    us_per_ms = PyInt_FromLong(1000);\r
-    us_per_second = PyInt_FromLong(1000000);\r
-    us_per_minute = PyInt_FromLong(60000000);\r
-    seconds_per_day = PyInt_FromLong(24 * 3600);\r
-    if (us_per_us == NULL || us_per_ms == NULL || us_per_second == NULL ||\r
-        us_per_minute == NULL || seconds_per_day == NULL)\r
-        return;\r
-\r
-    /* The rest are too big for 32-bit ints, but even\r
-     * us_per_week fits in 40 bits, so doubles should be exact.\r
-     */\r
-    us_per_hour = PyLong_FromDouble(3600000000.0);\r
-    us_per_day = PyLong_FromDouble(86400000000.0);\r
-    us_per_week = PyLong_FromDouble(604800000000.0);\r
-    if (us_per_hour == NULL || us_per_day == NULL || us_per_week == NULL)\r
-        return;\r
-}\r
-\r
-/* ---------------------------------------------------------------------------\r
-Some time zone algebra.  For a datetime x, let\r
-    x.n = x stripped of its timezone -- its naive time.\r
-    x.o = x.utcoffset(), and assuming that doesn't raise an exception or\r
-      return None\r
-    x.d = x.dst(), and assuming that doesn't raise an exception or\r
-      return None\r
-    x.s = x's standard offset, x.o - x.d\r
-\r
-Now some derived rules, where k is a duration (timedelta).\r
-\r
-1. x.o = x.s + x.d\r
-   This follows from the definition of x.s.\r
-\r
-2. If x and y have the same tzinfo member, x.s = y.s.\r
-   This is actually a requirement, an assumption we need to make about\r
-   sane tzinfo classes.\r
-\r
-3. The naive UTC time corresponding to x is x.n - x.o.\r
-   This is again a requirement for a sane tzinfo class.\r
-\r
-4. (x+k).s = x.s\r
-   This follows from #2, and that datimetimetz+timedelta preserves tzinfo.\r
-\r
-5. (x+k).n = x.n + k\r
-   Again follows from how arithmetic is defined.\r
-\r
-Now we can explain tz.fromutc(x).  Let's assume it's an interesting case\r
-(meaning that the various tzinfo methods exist, and don't blow up or return\r
-None when called).\r
-\r
-The function wants to return a datetime y with timezone tz, equivalent to x.\r
-x is already in UTC.\r
-\r
-By #3, we want\r
-\r
-    y.n - y.o = x.n                             [1]\r
-\r
-The algorithm starts by attaching tz to x.n, and calling that y.  So\r
-x.n = y.n at the start.  Then it wants to add a duration k to y, so that [1]\r
-becomes true; in effect, we want to solve [2] for k:\r
-\r
-   (y+k).n - (y+k).o = x.n                      [2]\r
-\r
-By #1, this is the same as\r
-\r
-   (y+k).n - ((y+k).s + (y+k).d) = x.n          [3]\r
-\r
-By #5, (y+k).n = y.n + k, which equals x.n + k because x.n=y.n at the start.\r
-Substituting that into [3],\r
-\r
-   x.n + k - (y+k).s - (y+k).d = x.n; the x.n terms cancel, leaving\r
-   k - (y+k).s - (y+k).d = 0; rearranging,\r
-   k = (y+k).s - (y+k).d; by #4, (y+k).s == y.s, so\r
-   k = y.s - (y+k).d\r
-\r
-On the RHS, (y+k).d can't be computed directly, but y.s can be, and we\r
-approximate k by ignoring the (y+k).d term at first.  Note that k can't be\r
-very large, since all offset-returning methods return a duration of magnitude\r
-less than 24 hours.  For that reason, if y is firmly in std time, (y+k).d must\r
-be 0, so ignoring it has no consequence then.\r
-\r
-In any case, the new value is\r
-\r
-    z = y + y.s                                 [4]\r
-\r
-It's helpful to step back at look at [4] from a higher level:  it's simply\r
-mapping from UTC to tz's standard time.\r
-\r
-At this point, if\r
-\r
-    z.n - z.o = x.n                             [5]\r
-\r
-we have an equivalent time, and are almost done.  The insecurity here is\r
-at the start of daylight time.  Picture US Eastern for concreteness.  The wall\r
-time jumps from 1:59 to 3:00, and wall hours of the form 2:MM don't make good\r
-sense then.  The docs ask that an Eastern tzinfo class consider such a time to\r
-be EDT (because it's "after 2"), which is a redundant spelling of 1:MM EST\r
-on the day DST starts.  We want to return the 1:MM EST spelling because that's\r
-the only spelling that makes sense on the local wall clock.\r
-\r
-In fact, if [5] holds at this point, we do have the standard-time spelling,\r
-but that takes a bit of proof.  We first prove a stronger result.  What's the\r
-difference between the LHS and RHS of [5]?  Let\r
-\r
-    diff = x.n - (z.n - z.o)                    [6]\r
-\r
-Now\r
-    z.n =                       by [4]\r
-    (y + y.s).n =               by #5\r
-    y.n + y.s =                 since y.n = x.n\r
-    x.n + y.s =                 since z and y are have the same tzinfo member,\r
-                                    y.s = z.s by #2\r
-    x.n + z.s\r
-\r
-Plugging that back into [6] gives\r
-\r
-    diff =\r
-    x.n - ((x.n + z.s) - z.o) =     expanding\r
-    x.n - x.n - z.s + z.o =         cancelling\r
-    - z.s + z.o =                   by #2\r
-    z.d\r
-\r
-So diff = z.d.\r
-\r
-If [5] is true now, diff = 0, so z.d = 0 too, and we have the standard-time\r
-spelling we wanted in the endcase described above.  We're done.  Contrarily,\r
-if z.d = 0, then we have a UTC equivalent, and are also done.\r
-\r
-If [5] is not true now, diff = z.d != 0, and z.d is the offset we need to\r
-add to z (in effect, z is in tz's standard time, and we need to shift the\r
-local clock into tz's daylight time).\r
-\r
-Let\r
-\r
-    z' = z + z.d = z + diff                     [7]\r
-\r
-and we can again ask whether\r
-\r
-    z'.n - z'.o = x.n                           [8]\r
-\r
-If so, we're done.  If not, the tzinfo class is insane, according to the\r
-assumptions we've made.  This also requires a bit of proof.  As before, let's\r
-compute the difference between the LHS and RHS of [8] (and skipping some of\r
-the justifications for the kinds of substitutions we've done several times\r
-already):\r
-\r
-    diff' = x.n - (z'.n - z'.o) =           replacing z'.n via [7]\r
-        x.n  - (z.n + diff - z'.o) =    replacing diff via [6]\r
-        x.n - (z.n + x.n - (z.n - z.o) - z'.o) =\r
-        x.n - z.n - x.n + z.n - z.o + z'.o =    cancel x.n\r
-        - z.n + z.n - z.o + z'.o =              cancel z.n\r
-        - z.o + z'.o =                      #1 twice\r
-        -z.s - z.d + z'.s + z'.d =          z and z' have same tzinfo\r
-        z'.d - z.d\r
-\r
-So z' is UTC-equivalent to x iff z'.d = z.d at this point.  If they are equal,\r
-we've found the UTC-equivalent so are done.  In fact, we stop with [7] and\r
-return z', not bothering to compute z'.d.\r
-\r
-How could z.d and z'd differ?  z' = z + z.d [7], so merely moving z' by\r
-a dst() offset, and starting *from* a time already in DST (we know z.d != 0),\r
-would have to change the result dst() returns:  we start in DST, and moving\r
-a little further into it takes us out of DST.\r
-\r
-There isn't a sane case where this can happen.  The closest it gets is at\r
-the end of DST, where there's an hour in UTC with no spelling in a hybrid\r
-tzinfo class.  In US Eastern, that's 5:MM UTC = 0:MM EST = 1:MM EDT.  During\r
-that hour, on an Eastern clock 1:MM is taken as being in standard time (6:MM\r
-UTC) because the docs insist on that, but 0:MM is taken as being in daylight\r
-time (4:MM UTC).  There is no local time mapping to 5:MM UTC.  The local\r
-clock jumps from 1:59 back to 1:00 again, and repeats the 1:MM hour in\r
-standard time.  Since that's what the local clock *does*, we want to map both\r
-UTC hours 5:MM and 6:MM to 1:MM Eastern.  The result is ambiguous\r
-in local time, but so it goes -- it's the way the local clock works.\r
-\r
-When x = 5:MM UTC is the input to this algorithm, x.o=0, y.o=-5 and y.d=0,\r
-so z=0:MM.  z.d=60 (minutes) then, so [5] doesn't hold and we keep going.\r
-z' = z + z.d = 1:MM then, and z'.d=0, and z'.d - z.d = -60 != 0 so [8]\r
-(correctly) concludes that z' is not UTC-equivalent to x.\r
-\r
-Because we know z.d said z was in daylight time (else [5] would have held and\r
-we would have stopped then), and we know z.d != z'.d (else [8] would have held\r
-and we would have stopped then), and there are only 2 possible values dst() can\r
-return in Eastern, it follows that z'.d must be 0 (which it is in the example,\r
-but the reasoning doesn't depend on the example -- it depends on there being\r
-two possible dst() outcomes, one zero and the other non-zero).  Therefore\r
-z' must be in standard time, and is the spelling we want in this case.\r
-\r
-Note again that z' is not UTC-equivalent as far as the hybrid tzinfo class is\r
-concerned (because it takes z' as being in standard time rather than the\r
-daylight time we intend here), but returning it gives the real-life "local\r
-clock repeats an hour" behavior when mapping the "unspellable" UTC hour into\r
-tz.\r
-\r
-When the input is 6:MM, z=1:MM and z.d=0, and we stop at once, again with\r
-the 1:MM standard time spelling we want.\r
-\r
-So how can this break?  One of the assumptions must be violated.  Two\r
-possibilities:\r
-\r
-1) [2] effectively says that y.s is invariant across all y belong to a given\r
-   time zone.  This isn't true if, for political reasons or continental drift,\r
-   a region decides to change its base offset from UTC.\r
-\r
-2) There may be versions of "double daylight" time where the tail end of\r
-   the analysis gives up a step too early.  I haven't thought about that\r
-   enough to say.\r
-\r
-In any case, it's clear that the default fromutc() is strong enough to handle\r
-"almost all" time zones:  so long as the standard offset is invariant, it\r
-doesn't matter if daylight time transition points change from year to year, or\r
-if daylight time is skipped in some years; it doesn't matter how large or\r
-small dst() may get within its bounds; and it doesn't even matter if some\r
-perverse time zone returns a negative dst()).  So a breaking case must be\r
-pretty bizarre, and a tzinfo subclass can override fromutc() if it is.\r
---------------------------------------------------------------------------- */\r