/Modules/datetimemodule.c
http://unladen-swallow.googlecode.com/ · C · 5082 lines · 3579 code · 588 blank · 915 comment · 811 complexity · b4ed2e757fdff99a36013356d213a16c MD5 · raw file
Large files are truncated click here to view the full file
- /* C implementation for the date/time type documented at
- * http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
- */
- #define PY_SSIZE_T_CLEAN
- #include "Python.h"
- #include "modsupport.h"
- #include "structmember.h"
- #include <time.h>
- #include "timefuncs.h"
- /* Differentiate between building the core module and building extension
- * modules.
- */
- #ifndef Py_BUILD_CORE
- #define Py_BUILD_CORE
- #endif
- #include "datetime.h"
- #undef Py_BUILD_CORE
- /* We require that C int be at least 32 bits, and use int virtually
- * everywhere. In just a few cases we use a temp long, where a Python
- * API returns a C long. In such cases, we have to ensure that the
- * final result fits in a C int (this can be an issue on 64-bit boxes).
- */
- #if SIZEOF_INT < 4
- # error "datetime.c requires that C int have at least 32 bits"
- #endif
- #define MINYEAR 1
- #define MAXYEAR 9999
- /* Nine decimal digits is easy to communicate, and leaves enough room
- * so that two delta days can be added w/o fear of overflowing a signed
- * 32-bit int, and with plenty of room left over to absorb any possible
- * carries from adding seconds.
- */
- #define MAX_DELTA_DAYS 999999999
- /* Rename the long macros in datetime.h to more reasonable short names. */
- #define GET_YEAR PyDateTime_GET_YEAR
- #define GET_MONTH PyDateTime_GET_MONTH
- #define GET_DAY PyDateTime_GET_DAY
- #define DATE_GET_HOUR PyDateTime_DATE_GET_HOUR
- #define DATE_GET_MINUTE PyDateTime_DATE_GET_MINUTE
- #define DATE_GET_SECOND PyDateTime_DATE_GET_SECOND
- #define DATE_GET_MICROSECOND PyDateTime_DATE_GET_MICROSECOND
- /* Date accessors for date and datetime. */
- #define SET_YEAR(o, v) (((o)->data[0] = ((v) & 0xff00) >> 8), \
- ((o)->data[1] = ((v) & 0x00ff)))
- #define SET_MONTH(o, v) (PyDateTime_GET_MONTH(o) = (v))
- #define SET_DAY(o, v) (PyDateTime_GET_DAY(o) = (v))
- /* Date/Time accessors for datetime. */
- #define DATE_SET_HOUR(o, v) (PyDateTime_DATE_GET_HOUR(o) = (v))
- #define DATE_SET_MINUTE(o, v) (PyDateTime_DATE_GET_MINUTE(o) = (v))
- #define DATE_SET_SECOND(o, v) (PyDateTime_DATE_GET_SECOND(o) = (v))
- #define DATE_SET_MICROSECOND(o, v) \
- (((o)->data[7] = ((v) & 0xff0000) >> 16), \
- ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
- ((o)->data[9] = ((v) & 0x0000ff)))
- /* Time accessors for time. */
- #define TIME_GET_HOUR PyDateTime_TIME_GET_HOUR
- #define TIME_GET_MINUTE PyDateTime_TIME_GET_MINUTE
- #define TIME_GET_SECOND PyDateTime_TIME_GET_SECOND
- #define TIME_GET_MICROSECOND PyDateTime_TIME_GET_MICROSECOND
- #define TIME_SET_HOUR(o, v) (PyDateTime_TIME_GET_HOUR(o) = (v))
- #define TIME_SET_MINUTE(o, v) (PyDateTime_TIME_GET_MINUTE(o) = (v))
- #define TIME_SET_SECOND(o, v) (PyDateTime_TIME_GET_SECOND(o) = (v))
- #define TIME_SET_MICROSECOND(o, v) \
- (((o)->data[3] = ((v) & 0xff0000) >> 16), \
- ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
- ((o)->data[5] = ((v) & 0x0000ff)))
- /* Delta accessors for timedelta. */
- #define GET_TD_DAYS(o) (((PyDateTime_Delta *)(o))->days)
- #define GET_TD_SECONDS(o) (((PyDateTime_Delta *)(o))->seconds)
- #define GET_TD_MICROSECONDS(o) (((PyDateTime_Delta *)(o))->microseconds)
- #define SET_TD_DAYS(o, v) ((o)->days = (v))
- #define SET_TD_SECONDS(o, v) ((o)->seconds = (v))
- #define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
- /* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
- * p->hastzinfo.
- */
- #define HASTZINFO(p) (((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
- /* M is a char or int claiming to be a valid month. The macro is equivalent
- * to the two-sided Python test
- * 1 <= M <= 12
- */
- #define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
- /* Forward declarations. */
- static PyTypeObject PyDateTime_DateType;
- static PyTypeObject PyDateTime_DateTimeType;
- static PyTypeObject PyDateTime_DeltaType;
- static PyTypeObject PyDateTime_TimeType;
- static PyTypeObject PyDateTime_TZInfoType;
- /* ---------------------------------------------------------------------------
- * Math utilities.
- */
- /* k = i+j overflows iff k differs in sign from both inputs,
- * iff k^i has sign bit set and k^j has sign bit set,
- * iff (k^i)&(k^j) has sign bit set.
- */
- #define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
- ((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
- /* Compute Python divmod(x, y), returning the quotient and storing the
- * remainder into *r. The quotient is the floor of x/y, and that's
- * the real point of this. C will probably truncate instead (C99
- * requires truncation; C89 left it implementation-defined).
- * Simplification: we *require* that y > 0 here. That's appropriate
- * for all the uses made of it. This simplifies the code and makes
- * the overflow case impossible (divmod(LONG_MIN, -1) is the only
- * overflow case).
- */
- static int
- divmod(int x, int y, int *r)
- {
- int quo;
- assert(y > 0);
- quo = x / y;
- *r = x - quo * y;
- if (*r < 0) {
- --quo;
- *r += y;
- }
- assert(0 <= *r && *r < y);
- return quo;
- }
- /* Round a double to the nearest long. |x| must be small enough to fit
- * in a C long; this is not checked.
- */
- static long
- round_to_long(double x)
- {
- if (x >= 0.0)
- x = floor(x + 0.5);
- else
- x = ceil(x - 0.5);
- return (long)x;
- }
- /* ---------------------------------------------------------------------------
- * General calendrical helper functions
- */
- /* For each month ordinal in 1..12, the number of days in that month,
- * and the number of days before that month in the same year. These
- * are correct for non-leap years only.
- */
- static int _days_in_month[] = {
- 0, /* unused; this vector uses 1-based indexing */
- 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
- };
- static int _days_before_month[] = {
- 0, /* unused; this vector uses 1-based indexing */
- 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
- };
- /* year -> 1 if leap year, else 0. */
- static int
- is_leap(int year)
- {
- /* Cast year to unsigned. The result is the same either way, but
- * C can generate faster code for unsigned mod than for signed
- * mod (especially for % 4 -- a good compiler should just grab
- * the last 2 bits when the LHS is unsigned).
- */
- const unsigned int ayear = (unsigned int)year;
- return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
- }
- /* year, month -> number of days in that month in that year */
- static int
- days_in_month(int year, int month)
- {
- assert(month >= 1);
- assert(month <= 12);
- if (month == 2 && is_leap(year))
- return 29;
- else
- return _days_in_month[month];
- }
- /* year, month -> number of days in year preceeding first day of month */
- static int
- days_before_month(int year, int month)
- {
- int days;
- assert(month >= 1);
- assert(month <= 12);
- days = _days_before_month[month];
- if (month > 2 && is_leap(year))
- ++days;
- return days;
- }
- /* year -> number of days before January 1st of year. Remember that we
- * start with year 1, so days_before_year(1) == 0.
- */
- static int
- days_before_year(int year)
- {
- int y = year - 1;
- /* This is incorrect if year <= 0; we really want the floor
- * here. But so long as MINYEAR is 1, the smallest year this
- * can see is 0 (this can happen in some normalization endcases),
- * so we'll just special-case that.
- */
- assert (year >= 0);
- if (y >= 0)
- return y*365 + y/4 - y/100 + y/400;
- else {
- assert(y == -1);
- return -366;
- }
- }
- /* Number of days in 4, 100, and 400 year cycles. That these have
- * the correct values is asserted in the module init function.
- */
- #define DI4Y 1461 /* days_before_year(5); days in 4 years */
- #define DI100Y 36524 /* days_before_year(101); days in 100 years */
- #define DI400Y 146097 /* days_before_year(401); days in 400 years */
- /* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
- static void
- ord_to_ymd(int ordinal, int *year, int *month, int *day)
- {
- int n, n1, n4, n100, n400, leapyear, preceding;
- /* ordinal is a 1-based index, starting at 1-Jan-1. The pattern of
- * leap years repeats exactly every 400 years. The basic strategy is
- * to find the closest 400-year boundary at or before ordinal, then
- * work with the offset from that boundary to ordinal. Life is much
- * clearer if we subtract 1 from ordinal first -- then the values
- * of ordinal at 400-year boundaries are exactly those divisible
- * by DI400Y:
- *
- * D M Y n n-1
- * -- --- ---- ---------- ----------------
- * 31 Dec -400 -DI400Y -DI400Y -1
- * 1 Jan -399 -DI400Y +1 -DI400Y 400-year boundary
- * ...
- * 30 Dec 000 -1 -2
- * 31 Dec 000 0 -1
- * 1 Jan 001 1 0 400-year boundary
- * 2 Jan 001 2 1
- * 3 Jan 001 3 2
- * ...
- * 31 Dec 400 DI400Y DI400Y -1
- * 1 Jan 401 DI400Y +1 DI400Y 400-year boundary
- */
- assert(ordinal >= 1);
- --ordinal;
- n400 = ordinal / DI400Y;
- n = ordinal % DI400Y;
- *year = n400 * 400 + 1;
- /* Now n is the (non-negative) offset, in days, from January 1 of
- * year, to the desired date. Now compute how many 100-year cycles
- * precede n.
- * Note that it's possible for n100 to equal 4! In that case 4 full
- * 100-year cycles precede the desired day, which implies the
- * desired day is December 31 at the end of a 400-year cycle.
- */
- n100 = n / DI100Y;
- n = n % DI100Y;
- /* Now compute how many 4-year cycles precede it. */
- n4 = n / DI4Y;
- n = n % DI4Y;
- /* And now how many single years. Again n1 can be 4, and again
- * meaning that the desired day is December 31 at the end of the
- * 4-year cycle.
- */
- n1 = n / 365;
- n = n % 365;
- *year += n100 * 100 + n4 * 4 + n1;
- if (n1 == 4 || n100 == 4) {
- assert(n == 0);
- *year -= 1;
- *month = 12;
- *day = 31;
- return;
- }
- /* Now the year is correct, and n is the offset from January 1. We
- * find the month via an estimate that's either exact or one too
- * large.
- */
- leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
- assert(leapyear == is_leap(*year));
- *month = (n + 50) >> 5;
- preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
- if (preceding > n) {
- /* estimate is too large */
- *month -= 1;
- preceding -= days_in_month(*year, *month);
- }
- n -= preceding;
- assert(0 <= n);
- assert(n < days_in_month(*year, *month));
- *day = n + 1;
- }
- /* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
- static int
- ymd_to_ord(int year, int month, int day)
- {
- return days_before_year(year) + days_before_month(year, month) + day;
- }
- /* Day of week, where Monday==0, ..., Sunday==6. 1/1/1 was a Monday. */
- static int
- weekday(int year, int month, int day)
- {
- return (ymd_to_ord(year, month, day) + 6) % 7;
- }
- /* Ordinal of the Monday starting week 1 of the ISO year. Week 1 is the
- * first calendar week containing a Thursday.
- */
- static int
- iso_week1_monday(int year)
- {
- int first_day = ymd_to_ord(year, 1, 1); /* ord of 1/1 */
- /* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
- int first_weekday = (first_day + 6) % 7;
- /* ordinal of closest Monday at or before 1/1 */
- int week1_monday = first_day - first_weekday;
- if (first_weekday > 3) /* if 1/1 was Fri, Sat, Sun */
- week1_monday += 7;
- return week1_monday;
- }
- /* ---------------------------------------------------------------------------
- * Range checkers.
- */
- /* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS. If so, return 0.
- * If not, raise OverflowError and return -1.
- */
- static int
- check_delta_day_range(int days)
- {
- if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
- return 0;
- PyErr_Format(PyExc_OverflowError,
- "days=%d; must have magnitude <= %d",
- days, MAX_DELTA_DAYS);
- return -1;
- }
- /* Check that date arguments are in range. Return 0 if they are. If they
- * aren't, raise ValueError and return -1.
- */
- static int
- check_date_args(int year, int month, int day)
- {
- if (year < MINYEAR || year > MAXYEAR) {
- PyErr_SetString(PyExc_ValueError,
- "year is out of range");
- return -1;
- }
- if (month < 1 || month > 12) {
- PyErr_SetString(PyExc_ValueError,
- "month must be in 1..12");
- return -1;
- }
- if (day < 1 || day > days_in_month(year, month)) {
- PyErr_SetString(PyExc_ValueError,
- "day is out of range for month");
- return -1;
- }
- return 0;
- }
- /* Check that time arguments are in range. Return 0 if they are. If they
- * aren't, raise ValueError and return -1.
- */
- static int
- check_time_args(int h, int m, int s, int us)
- {
- if (h < 0 || h > 23) {
- PyErr_SetString(PyExc_ValueError,
- "hour must be in 0..23");
- return -1;
- }
- if (m < 0 || m > 59) {
- PyErr_SetString(PyExc_ValueError,
- "minute must be in 0..59");
- return -1;
- }
- if (s < 0 || s > 59) {
- PyErr_SetString(PyExc_ValueError,
- "second must be in 0..59");
- return -1;
- }
- if (us < 0 || us > 999999) {
- PyErr_SetString(PyExc_ValueError,
- "microsecond must be in 0..999999");
- return -1;
- }
- return 0;
- }
- /* ---------------------------------------------------------------------------
- * Normalization utilities.
- */
- /* One step of a mixed-radix conversion. A "hi" unit is equivalent to
- * factor "lo" units. factor must be > 0. If *lo is less than 0, or
- * at least factor, enough of *lo is converted into "hi" units so that
- * 0 <= *lo < factor. The input values must be such that int overflow
- * is impossible.
- */
- static void
- normalize_pair(int *hi, int *lo, int factor)
- {
- assert(factor > 0);
- assert(lo != hi);
- if (*lo < 0 || *lo >= factor) {
- const int num_hi = divmod(*lo, factor, lo);
- const int new_hi = *hi + num_hi;
- assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
- *hi = new_hi;
- }
- assert(0 <= *lo && *lo < factor);
- }
- /* Fiddle days (d), seconds (s), and microseconds (us) so that
- * 0 <= *s < 24*3600
- * 0 <= *us < 1000000
- * The input values must be such that the internals don't overflow.
- * The way this routine is used, we don't get close.
- */
- static void
- normalize_d_s_us(int *d, int *s, int *us)
- {
- if (*us < 0 || *us >= 1000000) {
- normalize_pair(s, us, 1000000);
- /* |s| can't be bigger than about
- * |original s| + |original us|/1000000 now.
- */
- }
- if (*s < 0 || *s >= 24*3600) {
- normalize_pair(d, s, 24*3600);
- /* |d| can't be bigger than about
- * |original d| +
- * (|original s| + |original us|/1000000) / (24*3600) now.
- */
- }
- assert(0 <= *s && *s < 24*3600);
- assert(0 <= *us && *us < 1000000);
- }
- /* Fiddle years (y), months (m), and days (d) so that
- * 1 <= *m <= 12
- * 1 <= *d <= days_in_month(*y, *m)
- * The input values must be such that the internals don't overflow.
- * The way this routine is used, we don't get close.
- */
- static void
- normalize_y_m_d(int *y, int *m, int *d)
- {
- int dim; /* # of days in month */
- /* This gets muddy: the proper range for day can't be determined
- * without knowing the correct month and year, but if day is, e.g.,
- * plus or minus a million, the current month and year values make
- * no sense (and may also be out of bounds themselves).
- * Saying 12 months == 1 year should be non-controversial.
- */
- if (*m < 1 || *m > 12) {
- --*m;
- normalize_pair(y, m, 12);
- ++*m;
- /* |y| can't be bigger than about
- * |original y| + |original m|/12 now.
- */
- }
- assert(1 <= *m && *m <= 12);
- /* Now only day can be out of bounds (year may also be out of bounds
- * for a datetime object, but we don't care about that here).
- * If day is out of bounds, what to do is arguable, but at least the
- * method here is principled and explainable.
- */
- dim = days_in_month(*y, *m);
- if (*d < 1 || *d > dim) {
- /* Move day-1 days from the first of the month. First try to
- * get off cheap if we're only one day out of range
- * (adjustments for timezone alone can't be worse than that).
- */
- if (*d == 0) {
- --*m;
- if (*m > 0)
- *d = days_in_month(*y, *m);
- else {
- --*y;
- *m = 12;
- *d = 31;
- }
- }
- else if (*d == dim + 1) {
- /* move forward a day */
- ++*m;
- *d = 1;
- if (*m > 12) {
- *m = 1;
- ++*y;
- }
- }
- else {
- int ordinal = ymd_to_ord(*y, *m, 1) +
- *d - 1;
- ord_to_ymd(ordinal, y, m, d);
- }
- }
- assert(*m > 0);
- assert(*d > 0);
- }
- /* Fiddle out-of-bounds months and days so that the result makes some kind
- * of sense. The parameters are both inputs and outputs. Returns < 0 on
- * failure, where failure means the adjusted year is out of bounds.
- */
- static int
- normalize_date(int *year, int *month, int *day)
- {
- int result;
- normalize_y_m_d(year, month, day);
- if (MINYEAR <= *year && *year <= MAXYEAR)
- result = 0;
- else {
- PyErr_SetString(PyExc_OverflowError,
- "date value out of range");
- result = -1;
- }
- return result;
- }
- /* Force all the datetime fields into range. The parameters are both
- * inputs and outputs. Returns < 0 on error.
- */
- static int
- normalize_datetime(int *year, int *month, int *day,
- int *hour, int *minute, int *second,
- int *microsecond)
- {
- normalize_pair(second, microsecond, 1000000);
- normalize_pair(minute, second, 60);
- normalize_pair(hour, minute, 60);
- normalize_pair(day, hour, 24);
- return normalize_date(year, month, day);
- }
- /* ---------------------------------------------------------------------------
- * Basic object allocation: tp_alloc implementations. These allocate
- * Python objects of the right size and type, and do the Python object-
- * initialization bit. If there's not enough memory, they return NULL after
- * setting MemoryError. All data members remain uninitialized trash.
- *
- * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
- * member is needed. This is ugly, imprecise, and possibly insecure.
- * tp_basicsize for the time and datetime types is set to the size of the
- * struct that has room for the tzinfo member, so subclasses in Python will
- * allocate enough space for a tzinfo member whether or not one is actually
- * needed. That's the "ugly and imprecise" parts. The "possibly insecure"
- * part is that PyType_GenericAlloc() (which subclasses in Python end up
- * using) just happens today to effectively ignore the nitems argument
- * when tp_itemsize is 0, which it is for these type objects. If that
- * changes, perhaps the callers of tp_alloc slots in this file should
- * be changed to force a 0 nitems argument unless the type being allocated
- * is a base type implemented in this file (so that tp_alloc is time_alloc
- * or datetime_alloc below, which know about the nitems abuse).
- */
- static PyObject *
- time_alloc(PyTypeObject *type, Py_ssize_t aware)
- {
- PyObject *self;
- self = (PyObject *)
- PyObject_MALLOC(aware ?
- sizeof(PyDateTime_Time) :
- sizeof(_PyDateTime_BaseTime));
- if (self == NULL)
- return (PyObject *)PyErr_NoMemory();
- PyObject_INIT(self, type);
- return self;
- }
- static PyObject *
- datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
- {
- PyObject *self;
- self = (PyObject *)
- PyObject_MALLOC(aware ?
- sizeof(PyDateTime_DateTime) :
- sizeof(_PyDateTime_BaseDateTime));
- if (self == NULL)
- return (PyObject *)PyErr_NoMemory();
- PyObject_INIT(self, type);
- return self;
- }
- /* ---------------------------------------------------------------------------
- * Helpers for setting object fields. These work on pointers to the
- * appropriate base class.
- */
- /* For date and datetime. */
- static void
- set_date_fields(PyDateTime_Date *self, int y, int m, int d)
- {
- self->hashcode = -1;
- SET_YEAR(self, y);
- SET_MONTH(self, m);
- SET_DAY(self, d);
- }
- /* ---------------------------------------------------------------------------
- * Create various objects, mostly without range checking.
- */
- /* Create a date instance with no range checking. */
- static PyObject *
- new_date_ex(int year, int month, int day, PyTypeObject *type)
- {
- PyDateTime_Date *self;
- self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
- if (self != NULL)
- set_date_fields(self, year, month, day);
- return (PyObject *) self;
- }
- #define new_date(year, month, day) \
- new_date_ex(year, month, day, &PyDateTime_DateType)
- /* Create a datetime instance with no range checking. */
- static PyObject *
- new_datetime_ex(int year, int month, int day, int hour, int minute,
- int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
- {
- PyDateTime_DateTime *self;
- char aware = tzinfo != Py_None;
- self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
- if (self != NULL) {
- self->hastzinfo = aware;
- set_date_fields((PyDateTime_Date *)self, year, month, day);
- DATE_SET_HOUR(self, hour);
- DATE_SET_MINUTE(self, minute);
- DATE_SET_SECOND(self, second);
- DATE_SET_MICROSECOND(self, usecond);
- if (aware) {
- Py_INCREF(tzinfo);
- self->tzinfo = tzinfo;
- }
- }
- return (PyObject *)self;
- }
- #define new_datetime(y, m, d, hh, mm, ss, us, tzinfo) \
- new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo, \
- &PyDateTime_DateTimeType)
- /* Create a time instance with no range checking. */
- static PyObject *
- new_time_ex(int hour, int minute, int second, int usecond,
- PyObject *tzinfo, PyTypeObject *type)
- {
- PyDateTime_Time *self;
- char aware = tzinfo != Py_None;
- self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
- if (self != NULL) {
- self->hastzinfo = aware;
- self->hashcode = -1;
- TIME_SET_HOUR(self, hour);
- TIME_SET_MINUTE(self, minute);
- TIME_SET_SECOND(self, second);
- TIME_SET_MICROSECOND(self, usecond);
- if (aware) {
- Py_INCREF(tzinfo);
- self->tzinfo = tzinfo;
- }
- }
- return (PyObject *)self;
- }
- #define new_time(hh, mm, ss, us, tzinfo) \
- new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
- /* Create a timedelta instance. Normalize the members iff normalize is
- * true. Passing false is a speed optimization, if you know for sure
- * that seconds and microseconds are already in their proper ranges. In any
- * case, raises OverflowError and returns NULL if the normalized days is out
- * of range).
- */
- static PyObject *
- new_delta_ex(int days, int seconds, int microseconds, int normalize,
- PyTypeObject *type)
- {
- PyDateTime_Delta *self;
- if (normalize)
- normalize_d_s_us(&days, &seconds, µseconds);
- assert(0 <= seconds && seconds < 24*3600);
- assert(0 <= microseconds && microseconds < 1000000);
- if (check_delta_day_range(days) < 0)
- return NULL;
- self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
- if (self != NULL) {
- self->hashcode = -1;
- SET_TD_DAYS(self, days);
- SET_TD_SECONDS(self, seconds);
- SET_TD_MICROSECONDS(self, microseconds);
- }
- return (PyObject *) self;
- }
- #define new_delta(d, s, us, normalize) \
- new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
- /* ---------------------------------------------------------------------------
- * tzinfo helpers.
- */
- /* Ensure that p is None or of a tzinfo subclass. Return 0 if OK; if not
- * raise TypeError and return -1.
- */
- static int
- check_tzinfo_subclass(PyObject *p)
- {
- if (p == Py_None || PyTZInfo_Check(p))
- return 0;
- PyErr_Format(PyExc_TypeError,
- "tzinfo argument must be None or of a tzinfo subclass, "
- "not type '%s'",
- Py_TYPE(p)->tp_name);
- return -1;
- }
- /* Return tzinfo.methname(tzinfoarg), without any checking of results.
- * If tzinfo is None, returns None.
- */
- static PyObject *
- call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
- {
- PyObject *result;
- assert(tzinfo && methname && tzinfoarg);
- assert(check_tzinfo_subclass(tzinfo) >= 0);
- if (tzinfo == Py_None) {
- result = Py_None;
- Py_INCREF(result);
- }
- else
- result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
- return result;
- }
- /* If self has a tzinfo member, return a BORROWED reference to it. Else
- * return NULL, which is NOT AN ERROR. There are no error returns here,
- * and the caller must not decref the result.
- */
- static PyObject *
- get_tzinfo_member(PyObject *self)
- {
- PyObject *tzinfo = NULL;
- if (PyDateTime_Check(self) && HASTZINFO(self))
- tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
- else if (PyTime_Check(self) && HASTZINFO(self))
- tzinfo = ((PyDateTime_Time *)self)->tzinfo;
- return tzinfo;
- }
- /* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
- * result. tzinfo must be an instance of the tzinfo class. If the method
- * returns None, this returns 0 and sets *none to 1. If the method doesn't
- * return None or timedelta, TypeError is raised and this returns -1. If it
- * returnsa timedelta and the value is out of range or isn't a whole number
- * of minutes, ValueError is raised and this returns -1.
- * Else *none is set to 0 and the integer method result is returned.
- */
- static int
- call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
- int *none)
- {
- PyObject *u;
- int result = -1;
- assert(tzinfo != NULL);
- assert(PyTZInfo_Check(tzinfo));
- assert(tzinfoarg != NULL);
- *none = 0;
- u = call_tzinfo_method(tzinfo, name, tzinfoarg);
- if (u == NULL)
- return -1;
- else if (u == Py_None) {
- result = 0;
- *none = 1;
- }
- else if (PyDelta_Check(u)) {
- const int days = GET_TD_DAYS(u);
- if (days < -1 || days > 0)
- result = 24*60; /* trigger ValueError below */
- else {
- /* next line can't overflow because we know days
- * is -1 or 0 now
- */
- int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
- result = divmod(ss, 60, &ss);
- if (ss || GET_TD_MICROSECONDS(u)) {
- PyErr_Format(PyExc_ValueError,
- "tzinfo.%s() must return a "
- "whole number of minutes",
- name);
- result = -1;
- }
- }
- }
- else {
- PyErr_Format(PyExc_TypeError,
- "tzinfo.%s() must return None or "
- "timedelta, not '%s'",
- name, Py_TYPE(u)->tp_name);
- }
- Py_DECREF(u);
- if (result < -1439 || result > 1439) {
- PyErr_Format(PyExc_ValueError,
- "tzinfo.%s() returned %d; must be in "
- "-1439 .. 1439",
- name, result);
- result = -1;
- }
- return result;
- }
- /* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
- * result. tzinfo must be an instance of the tzinfo class. If utcoffset()
- * returns None, call_utcoffset returns 0 and sets *none to 1. If uctoffset()
- * doesn't return None or timedelta, TypeError is raised and this returns -1.
- * If utcoffset() returns an invalid timedelta (out of range, or not a whole
- * # of minutes), ValueError is raised and this returns -1. Else *none is
- * set to 0 and the offset is returned (as int # of minutes east of UTC).
- */
- static int
- call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
- {
- return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
- }
- /* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
- */
- static PyObject *
- offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
- PyObject *result;
- assert(tzinfo && name && tzinfoarg);
- if (tzinfo == Py_None) {
- result = Py_None;
- Py_INCREF(result);
- }
- else {
- int none;
- int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
- &none);
- if (offset < 0 && PyErr_Occurred())
- return NULL;
- if (none) {
- result = Py_None;
- Py_INCREF(result);
- }
- else
- result = new_delta(0, offset * 60, 0, 1);
- }
- return result;
- }
- /* Call tzinfo.dst(tzinfoarg), and extract an integer from the
- * result. tzinfo must be an instance of the tzinfo class. If dst()
- * returns None, call_dst returns 0 and sets *none to 1. If dst()
- & doesn't return None or timedelta, TypeError is raised and this
- * returns -1. If dst() returns an invalid timedelta for a UTC offset,
- * ValueError is raised and this returns -1. Else *none is set to 0 and
- * the offset is returned (as an int # of minutes east of UTC).
- */
- static int
- call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
- {
- return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
- }
- /* Call tzinfo.tzname(tzinfoarg), and return the result. tzinfo must be
- * an instance of the tzinfo class or None. If tzinfo isn't None, and
- * tzname() doesn't return None or a string, TypeError is raised and this
- * returns NULL.
- */
- static PyObject *
- call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
- {
- PyObject *result;
- assert(tzinfo != NULL);
- assert(check_tzinfo_subclass(tzinfo) >= 0);
- assert(tzinfoarg != NULL);
- if (tzinfo == Py_None) {
- result = Py_None;
- Py_INCREF(result);
- }
- else
- result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
- if (result != NULL && result != Py_None && ! PyString_Check(result)) {
- PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
- "return None or a string, not '%s'",
- Py_TYPE(result)->tp_name);
- Py_DECREF(result);
- result = NULL;
- }
- return result;
- }
- typedef enum {
- /* an exception has been set; the caller should pass it on */
- OFFSET_ERROR,
- /* type isn't date, datetime, or time subclass */
- OFFSET_UNKNOWN,
- /* date,
- * datetime with !hastzinfo
- * datetime with None tzinfo,
- * datetime where utcoffset() returns None
- * time with !hastzinfo
- * time with None tzinfo,
- * time where utcoffset() returns None
- */
- OFFSET_NAIVE,
- /* time or datetime where utcoffset() doesn't return None */
- OFFSET_AWARE
- } naivety;
- /* Classify an object as to whether it's naive or offset-aware. See
- * the "naivety" typedef for details. If the type is aware, *offset is set
- * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
- * If the type is offset-naive (or unknown, or error), *offset is set to 0.
- * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
- */
- static naivety
- classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
- {
- int none;
- PyObject *tzinfo;
- assert(tzinfoarg != NULL);
- *offset = 0;
- tzinfo = get_tzinfo_member(op); /* NULL means no tzinfo, not error */
- if (tzinfo == Py_None)
- return OFFSET_NAIVE;
- if (tzinfo == NULL) {
- /* note that a datetime passes the PyDate_Check test */
- return (PyTime_Check(op) || PyDate_Check(op)) ?
- OFFSET_NAIVE : OFFSET_UNKNOWN;
- }
- *offset = call_utcoffset(tzinfo, tzinfoarg, &none);
- if (*offset == -1 && PyErr_Occurred())
- return OFFSET_ERROR;
- return none ? OFFSET_NAIVE : OFFSET_AWARE;
- }
- /* Classify two objects as to whether they're naive or offset-aware.
- * This isn't quite the same as calling classify_utcoffset() twice: for
- * binary operations (comparison and subtraction), we generally want to
- * ignore the tzinfo members if they're identical. This is by design,
- * so that results match "naive" expectations when mixing objects from a
- * single timezone. So in that case, this sets both offsets to 0 and
- * both naiveties to OFFSET_NAIVE.
- * The function returns 0 if everything's OK, and -1 on error.
- */
- static int
- classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
- PyObject *tzinfoarg1,
- PyObject *o2, int *offset2, naivety *n2,
- PyObject *tzinfoarg2)
- {
- if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
- *offset1 = *offset2 = 0;
- *n1 = *n2 = OFFSET_NAIVE;
- }
- else {
- *n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
- if (*n1 == OFFSET_ERROR)
- return -1;
- *n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
- if (*n2 == OFFSET_ERROR)
- return -1;
- }
- return 0;
- }
- /* repr is like "someclass(arg1, arg2)". If tzinfo isn't None,
- * stuff
- * ", tzinfo=" + repr(tzinfo)
- * before the closing ")".
- */
- static PyObject *
- append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
- {
- PyObject *temp;
- assert(PyString_Check(repr));
- assert(tzinfo);
- if (tzinfo == Py_None)
- return repr;
- /* Get rid of the trailing ')'. */
- assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
- temp = PyString_FromStringAndSize(PyString_AsString(repr),
- PyString_Size(repr) - 1);
- Py_DECREF(repr);
- if (temp == NULL)
- return NULL;
- repr = temp;
- /* Append ", tzinfo=". */
- PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
- /* Append repr(tzinfo). */
- PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
- /* Add a closing paren. */
- PyString_ConcatAndDel(&repr, PyString_FromString(")"));
- return repr;
- }
- /* ---------------------------------------------------------------------------
- * String format helpers.
- */
- static PyObject *
- format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
- {
- static const char *DayNames[] = {
- "Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
- };
- static const char *MonthNames[] = {
- "Jan", "Feb", "Mar", "Apr", "May", "Jun",
- "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
- };
- char buffer[128];
- int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
- PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
- DayNames[wday], MonthNames[GET_MONTH(date) - 1],
- GET_DAY(date), hours, minutes, seconds,
- GET_YEAR(date));
- return PyString_FromString(buffer);
- }
- /* Add an hours & minutes UTC offset string to buf. buf has no more than
- * buflen bytes remaining. The UTC offset is gotten by calling
- * tzinfo.uctoffset(tzinfoarg). If that returns None, \0 is stored into
- * *buf, and that's all. Else the returned value is checked for sanity (an
- * integer in range), and if that's OK it's converted to an hours & minutes
- * string of the form
- * sign HH sep MM
- * Returns 0 if everything is OK. If the return value from utcoffset() is
- * bogus, an appropriate exception is set and -1 is returned.
- */
- static int
- format_utcoffset(char *buf, size_t buflen, const char *sep,
- PyObject *tzinfo, PyObject *tzinfoarg)
- {
- int offset;
- int hours;
- int minutes;
- char sign;
- int none;
- assert(buflen >= 1);
- offset = call_utcoffset(tzinfo, tzinfoarg, &none);
- if (offset == -1 && PyErr_Occurred())
- return -1;
- if (none) {
- *buf = '\0';
- return 0;
- }
- sign = '+';
- if (offset < 0) {
- sign = '-';
- offset = - offset;
- }
- hours = divmod(offset, 60, &minutes);
- PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
- return 0;
- }
- static PyObject *
- make_freplacement(PyObject *object)
- {
- char freplacement[64];
- if (PyTime_Check(object))
- sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
- else if (PyDateTime_Check(object))
- sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
- else
- sprintf(freplacement, "%06d", 0);
- return PyString_FromStringAndSize(freplacement, strlen(freplacement));
- }
- /* I sure don't want to reproduce the strftime code from the time module,
- * so this imports the module and calls it. All the hair is due to
- * giving special meanings to the %z, %Z and %f format codes via a
- * preprocessing step on the format string.
- * tzinfoarg is the argument to pass to the object's tzinfo method, if
- * needed.
- */
- static PyObject *
- wrap_strftime(PyObject *object, const char *format, size_t format_len,
- PyObject *timetuple, PyObject *tzinfoarg)
- {
- PyObject *result = NULL; /* guilty until proved innocent */
- PyObject *zreplacement = NULL; /* py string, replacement for %z */
- PyObject *Zreplacement = NULL; /* py string, replacement for %Z */
- PyObject *freplacement = NULL; /* py string, replacement for %f */
- const char *pin; /* pointer to next char in input format */
- char ch; /* next char in input format */
- PyObject *newfmt = NULL; /* py string, the output format */
- char *pnew; /* pointer to available byte in output format */
- size_t totalnew; /* number bytes total in output format buffer,
- exclusive of trailing \0 */
- size_t usednew; /* number bytes used so far in output format buffer */
- const char *ptoappend; /* ptr to string to append to output buffer */
- size_t ntoappend; /* # of bytes to append to output buffer */
- assert(object && format && timetuple);
- /* Give up if the year is before 1900.
- * Python strftime() plays games with the year, and different
- * games depending on whether envar PYTHON2K is set. This makes
- * years before 1900 a nightmare, even if the platform strftime
- * supports them (and not all do).
- * We could get a lot farther here by avoiding Python's strftime
- * wrapper and calling the C strftime() directly, but that isn't
- * an option in the Python implementation of this module.
- */
- {
- long year;
- PyObject *pyyear = PySequence_GetItem(timetuple, 0);
- if (pyyear == NULL) return NULL;
- assert(PyInt_Check(pyyear));
- year = PyInt_AsLong(pyyear);
- Py_DECREF(pyyear);
- if (year < 1900) {
- PyErr_Format(PyExc_ValueError, "year=%ld is before "
- "1900; the datetime strftime() "
- "methods require year >= 1900",
- year);
- return NULL;
- }
- }
- /* Scan the input format, looking for %z/%Z/%f escapes, building
- * a new format. Since computing the replacements for those codes
- * is expensive, don't unless they're actually used.
- */
- if (format_len > INT_MAX - 1) {
- PyErr_NoMemory();
- goto Done;
- }
- totalnew = format_len + 1; /* realistic if no %z/%Z/%f */
- newfmt = PyString_FromStringAndSize(NULL, totalnew);
- if (newfmt == NULL) goto Done;
- pnew = PyString_AsString(newfmt);
- usednew = 0;
- pin = format;
- while ((ch = *pin++) != '\0') {
- if (ch != '%') {
- ptoappend = pin - 1;
- ntoappend = 1;
- }
- else if ((ch = *pin++) == '\0') {
- /* There's a lone trailing %; doesn't make sense. */
- PyErr_SetString(PyExc_ValueError, "strftime format "
- "ends with raw %");
- goto Done;
- }
- /* A % has been seen and ch is the character after it. */
- else if (ch == 'z') {
- if (zreplacement == NULL) {
- /* format utcoffset */
- char buf[100];
- PyObject *tzinfo = get_tzinfo_member(object);
- zreplacement = PyString_FromString("");
- if (zreplacement == NULL) goto Done;
- if (tzinfo != Py_None && tzinfo != NULL) {
- assert(tzinfoarg != NULL);
- if (format_utcoffset(buf,
- sizeof(buf),
- "",
- tzinfo,
- tzinfoarg) < 0)
- goto Done;
- Py_DECREF(zreplacement);
- zreplacement = PyString_FromString(buf);
- if (zreplacement == NULL) goto Done;
- }
- }
- assert(zreplacement != NULL);
- ptoappend = PyString_AS_STRING(zreplacement);
- ntoappend = PyString_GET_SIZE(zreplacement);
- }
- else if (ch == 'Z') {
- /* format tzname */
- if (Zreplacement == NULL) {
- PyObject *tzinfo = get_tzinfo_member(object);
- Zreplacement = PyString_FromString("");
- if (Zreplacement == NULL) goto Done;
- if (tzinfo != Py_None && tzinfo != NULL) {
- PyObject *temp;
- assert(tzinfoarg != NULL);
- temp = call_tzname(tzinfo, tzinfoarg);
- if (temp == NULL) goto Done;
- if (temp != Py_None) {
- assert(PyString_Check(temp));
- /* Since the tzname is getting
- * stuffed into the format, we
- * have to double any % signs
- * so that strftime doesn't
- * treat them as format codes.
- */
- Py_DECREF(Zreplacement);
- Zreplacement = PyObject_CallMethod(
- temp, "replace",
- "ss", "%", "%%");
- Py_DECREF(temp);
- if (Zreplacement == NULL)
- goto Done;
- if (!PyString_Check(Zreplacement)) {
- PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
- goto Done;
- }
- }
- else
- Py_DECREF(temp);
- }
- }
- assert(Zreplacement != NULL);
- ptoappend = PyString_AS_STRING(Zreplacement);
- ntoappend = PyString_GET_SIZE(Zreplacement);
- }
- else if (ch == 'f') {
- /* format microseconds */
- if (freplacement == NULL) {
- freplacement = make_freplacement(object);
- if (freplacement == NULL)
- goto Done;
- }
- assert(freplacement != NULL);
- assert(PyString_Check(freplacement));
- ptoappend = PyString_AS_STRING(freplacement);
- ntoappend = PyString_GET_SIZE(freplacement);
- }
- else {
- /* percent followed by neither z nor Z */
- ptoappend = pin - 2;
- ntoappend = 2;
- }
- /* Append the ntoappend chars starting at ptoappend to
- * the new format.
- */
- assert(ptoappend != NULL);
- assert(ntoappend >= 0);
- if (ntoappend == 0)
- continue;
- while (usednew + ntoappend > totalnew) {
- size_t bigger = totalnew << 1;
- if ((bigger >> 1) != totalnew) { /* overflow */
- PyErr_NoMemory();
- goto Done;
- }
- if (_PyString_Resize(&newfmt, bigger) < 0)
- goto Done;
- totalnew = bigger;
- pnew = PyString_AsString(newfmt) + usednew;
- }
- memcpy(pnew, ptoappend, ntoappend);
- pnew += ntoappend;
- usednew += ntoappend;
- assert(usednew <= totalnew);
- } /* end while() */
- if (_PyString_Resize(&newfmt, usednew) < 0)
- goto Done;
- {
- PyObject *time = PyImport_ImportModuleNoBlock("time");
- if (time == NULL)
- goto Done;
- result = PyObject_CallMethod(time, "strftime", "OO",
- newfmt, timetuple);
- Py_DECREF(time);
- }
- Done:
- Py_XDECREF(freplacement);
- Py_XDECREF(zreplacement);
- Py_XDECREF(Zreplacement);
- Py_XDECREF(newfmt);
- return result;
- }
- static char *
- isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
- {
- int x;
- x = PyOS_snprintf(buffer, bufflen,
- "%04d-%02d-%02d",
- GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
- return buffer + x;
- }
- static void
- isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
- {
- int us = DATE_GET_MICROSECOND(dt);
- PyOS_snprintf(buffer, bufflen,
- "%02d:%02d:%02d", /* 8 characters */
- DATE_GET_HOUR(dt),
- DATE_GET_MINUTE(dt),
- DATE_GET_SECOND(dt));
- if (us)
- PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
- }
- /* ---------------------------------------------------------------------------
- * Wrap functions from the time module. These aren't directly available
- * from C. Perhaps they should be.
- */
- /* Call time.time() and return its result (a Python float). */
- static PyObject *
- time_time(void)
- {
- PyObject *result = NULL;
- PyObject *time = PyImport_ImportModuleNoBlock("time");
- if (time != NULL) {
- result = PyObject_CallMethod(time, "time", "()");
- Py_DECREF(time);
- }
- return result;
- }
- /* Build a time.struct_time. The weekday and day number are automatically
- * computed from the y,m,d args.
- */
- static PyObject *
- build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
- {
- PyObject *time;
- PyObject *result = NULL;
- time = PyImport_ImportModuleNoBlock("time");
- if (time != NULL) {
- result = PyObject_CallMethod(time, "struct_time",
- "((iiiiiiiii))",
- y, m, d,
- hh, mm, ss,
- weekday(y, m, d),
- days_before_month(y, m) + d,
- dstflag);
- Py_DECREF(time);
- }
- return result;
- }
- /* ---------------------------------------------------------------------------
- * Miscellaneous helpers.
- */
- /* For obscure reasons, we need to use tp_richcompare instead of tp_compare.
- * The comparisons here all most naturally compute a cmp()-like result.
- * This little helper turns that into a bool result for rich comparisons.
- */
- static PyObject *
- diff_to_bool(int diff, int op)
- {
- PyObject *result;
- int istrue;
- switch (op) {
- case Py_EQ: istrue = diff == 0; break;
- case Py_NE: istrue = diff != 0; break;
- case Py_LE: istrue = diff <= 0; break;
- case Py_GE: istrue = diff >= 0; break;
- case Py_LT: istrue = diff < 0; break;
- case Py_GT: istrue = diff > 0; break;
- default:
- assert(! "op unknown");
- istrue = 0; /* To shut up compiler */
- }
- result = istrue ? Py_True : Py_False;
- Py_INCREF(result);
- return result;
- }
- /* Raises a "can't compare" TypeError and returns NULL. */
- static PyObject *
- cmperror(PyObject *a, PyObject *b)
- {
- PyErr_Format(PyExc_TypeError,
- "can't compare %s to %s",
- Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
- return NULL;
- }
- /* ---------------------------------------------------------------------------
- * Cached Python objects; these are set by the module init function.
- */
- /* Conversion factors. */
- static PyObject *us_per_us = NULL; /* 1 */
- static PyObject *us_per_ms = NULL; /* 1000 */
- static PyObject *us_per_second = NULL; /* 1000000 */
- static PyObject *us_per_minute = NULL; /* 1e6 * 60 as Python int */
- static PyObject *us_per_hour = NULL; /* 1e6 * 3600 as Python long */
- static PyObject *us_per_day = NULL; /* 1e6 * 3600 * 24 as Python long */
- static PyObject *us_per_week = NULL; /* 1e6*3600*24*7 as Python long */
- static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
- /* ---------------------------------------------------------------------------
- * Class implementations.
- */
- /*
- * PyDateTime_Delta implementation.
- */
- /* Convert a timedelta to a number of us,
- * (24*3600*self.days + self.seconds)*1000000 + self.microseconds
- * as a Python int or long.
- * Doing mixed-radix arithmetic by hand instead is excruciating in C,
- * due to ubiquitous overflow possibilities.
- */
- static PyObject *
- delta_to_microseconds(PyDateTime_Delta *self)
- {
- PyObject *x1 = NULL;
- PyObject *x2 = NULL;
- PyObject *x3 = NULL;
- PyObject *result = NULL;
- x1 = PyInt_FromLong(GET_TD_DAYS(self));
- if (x1 == NULL)
- goto Done;
- x2 = PyNumber_Multiply(x1, seconds_per_day); /* days in seconds */
- if (x2 == NULL)
- goto Done;
- Py_DECREF(x1);
- x1 = NULL;
- /* x2 has days in seconds */
- x1 = PyInt_FromLong(GET_TD_SECONDS(self)); /* seconds */
- if (x1 == NULL)
- goto Done;
- x3 = PyNumber_Add(x1, x2); /* days and seconds in seconds */
- if (x3 == NULL)
- goto Done;
- Py_DECREF(x1);
- Py_DECREF(x2);
- x1 = x2 = NULL;
- /* x3 has days+seconds in seconds */
- x1 = PyNumber_Multiply(x3, us_per_second); /* us */
- if (x1 == NULL)
- goto Done;
- Py_DECREF(x3);
- x3 = NULL;
- /* x1 has days+seconds in us */
- x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
- if (x2 == NULL)
- goto Done;
- result = PyNumber_Add(x1, x2);
- Done:
- Py_XDECREF(x1);
- Py_XDECREF(x2);
- Py_XDECREF(x3);
- return result;
- }
- /* Convert a number of us (as a Python int or long) to a timedelta.
- */
- static PyObject *
- microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
- {
- int us;
- int s;
- int d;
- long temp;
- PyObject *tuple = NULL;
- PyObject *num = NULL;
- PyObject *result = NULL;
- tuple = PyNumber_Divmod(pyus, us_per_second);
- if (tuple == NULL)
- goto Done;
- num = PyTuple_GetItem(tuple, 1); /* us */
- if (num == NULL)
- goto Done;
- temp = PyLong_AsLong(num);
- num = NULL;
- if (temp == -1 && PyErr_Occurred())
- goto Done;
- assert(0 <= temp && temp < 1000000);
- us = (int)temp;
- if (us < 0) {
- /* The divisor was positive, so this must be an error. */
- assert(PyErr_Occurred());
- goto Done;
- }
- num = PyTuple_GetItem(tuple, 0); /* leftover seconds */
- if (num == NULL)
- goto Done;
- Py_INCREF(num);
- Py_DECREF(tuple);
- tuple = PyNumber_Divmod(num, seconds_per_day);
- if (tuple == NULL)
- goto Done;
- Py_DECREF(num);
- num = PyTuple_GetItem(tuple, 1); /* seconds */
- if (num == NULL)
- goto Done;
- temp = PyLong_AsLong(num);
- num = NULL;
- if (temp == -1 && PyErr_Occurred())
- goto Done;
- assert(0 <= temp && temp < 24*3600);
- s = (int)temp;
- if (s < 0) {
- /* The divisor was positive, so this must be an error. */
- assert(PyErr_Occurred());
- goto Done;
- }
- num = PyTuple_GetItem(tuple, 0); /* leftover days */
- if (num == NULL)
- goto Done;
- Py_INCREF(num);
- temp = PyLong_AsLong(num);
- if (temp == -1 && PyErr_Occurred())
- goto Done;
- d = (int)temp;
- if ((long)d != temp) {
- PyErr_SetString(PyExc_OverflowError, "normalized days too "
- "large to fit in a C int");
- goto Done;
- }
- result = new_delta_ex(d, s, us, 0, type);
- Done:
- Py_XDECREF(tuple);
- Py_XDECREF(num);
- return result;
- }
- #define microseconds_to_delta(pymicros) \
- microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
- static PyObject *
- multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
- {
- PyObject *pyus_in;
- PyObject *pyus_out;
- PyObject *result;
- pyus_in = delta_to_microseconds(delta);
- if (pyus_in == NULL)
- return NULL;
- pyus_out = PyNumber_Multiply(pyus_in, intobj);
- Py_DECREF(pyus_in);
- if (pyus_out == NULL)
- return NULL;
- result = microseconds_to_delta(pyus_out);
- Py_DECREF(pyus_out);
- return result;
- }
- static PyObject *
- divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
- {
- PyObject *pyus_in;
- PyObject *pyus_out;
- PyObject *result;
- pyus_in = delta_to_microseconds(delta);
- if (pyus_in == NULL)
- return NULL;
- pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
- Py_DECREF(pyus_in);
- if (pyus_out == NULL)
- return NULL;
- result = microseconds_to_delta(pyus_out);
- Py_DECREF(pyus_out);
- return result;
- }
- static PyObject *
- delta_add(PyObject *left, PyObject *right)
- {
- PyObject *result = Py_NotImplemented;
- if (PyDelta_Check(left) && PyDelta_Check(right)) {
- /* delta + delta */
- /* The C-level additions can't overflow because of the
- * invariant bounds.
- */
- int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
- int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
- int microseconds = GET_TD_MICROSECONDS(left) +
- GET_TD_MICROSECONDS(right);
- result = new_delta(days, seconds, microseconds, 1);
- }
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
- }
- static PyObject *
- delta_negative(PyDateTime_Delta *self)
- {
- return new_delta(-GET_TD_DAYS(self),
- -GET_TD_SECONDS(self),
- -GET_TD_MICROSECONDS(self),
- 1);
- }
- static PyObject *
- delta_positive(PyDateTime_Delta *self)
- {
- /* Could optimize this (by returning self) if this isn't a
- * subclass -- but who uses unary + ? Approximately nobody.
- */
- return new_delta(GET_TD_DAYS(self),
- GET_TD_SECONDS(self),
- GET_TD_MICROSECONDS(self),
- 0);
- }
- static PyObject *
- delta_abs(PyDateTime_Delta *self)
- {
- PyObject *result;
- assert(GET_TD_MICROSECONDS(self) >= 0);
- assert(GET_TD_SECONDS(self) >= 0);
- if (GET_TD_DAYS(self) < 0)
- result = delta_negative(self);
- else
- result = delta_positive(self);
- return result;
- }
- static PyObject *
- delta_subtract(PyObject *left, PyObject *right)
- {
- PyObject *result = Py_NotImplemented;
- if (PyDelta_Check(left) && PyDelta_Check(right)) {
- /* delta - delta */
- PyObject *minus_right = PyNumber_Negative(right);
- if (minus_right) {
- result = delta_add(left, minus_right);
- Py_DECREF(minus_right);
- }
- else
- result = NULL;
- }
- if (result == Py_NotImplemented)
- Py_INCREF(result);
- return result;
- }
- /* This is more natural as a tp_compare, but doesn't work then: for whatever
- * reason, Python's try_3way_compare ignores tp_compare unless
- * PyInstance_Check returns true, but these aren't old-style classes.
- */
- static PyObject *
- delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
- {
- int diff = 42; /* nonsense */
- if (PyDelta_Check(other)) {
- diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
- if (diff == 0)…