PageRenderTime 737ms CodeModel.GetById 141ms app.highlight 411ms RepoModel.GetById 112ms app.codeStats 2ms

/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 files are truncated, but you can click here to view the full file

   1/*  C implementation for the date/time type documented at
   2 *  http://www.zope.org/Members/fdrake/DateTimeWiki/FrontPage
   3 */
   4
   5#define PY_SSIZE_T_CLEAN
   6
   7#include "Python.h"
   8#include "modsupport.h"
   9#include "structmember.h"
  10
  11#include <time.h>
  12
  13#include "timefuncs.h"
  14
  15/* Differentiate between building the core module and building extension
  16 * modules.
  17 */
  18#ifndef Py_BUILD_CORE
  19#define Py_BUILD_CORE
  20#endif
  21#include "datetime.h"
  22#undef Py_BUILD_CORE
  23
  24/* We require that C int be at least 32 bits, and use int virtually
  25 * everywhere.  In just a few cases we use a temp long, where a Python
  26 * API returns a C long.  In such cases, we have to ensure that the
  27 * final result fits in a C int (this can be an issue on 64-bit boxes).
  28 */
  29#if SIZEOF_INT < 4
  30#	error "datetime.c requires that C int have at least 32 bits"
  31#endif
  32
  33#define MINYEAR 1
  34#define MAXYEAR 9999
  35
  36/* Nine decimal digits is easy to communicate, and leaves enough room
  37 * so that two delta days can be added w/o fear of overflowing a signed
  38 * 32-bit int, and with plenty of room left over to absorb any possible
  39 * carries from adding seconds.
  40 */
  41#define MAX_DELTA_DAYS 999999999
  42
  43/* Rename the long macros in datetime.h to more reasonable short names. */
  44#define GET_YEAR		PyDateTime_GET_YEAR
  45#define GET_MONTH		PyDateTime_GET_MONTH
  46#define GET_DAY			PyDateTime_GET_DAY
  47#define DATE_GET_HOUR		PyDateTime_DATE_GET_HOUR
  48#define DATE_GET_MINUTE		PyDateTime_DATE_GET_MINUTE
  49#define DATE_GET_SECOND		PyDateTime_DATE_GET_SECOND
  50#define DATE_GET_MICROSECOND	PyDateTime_DATE_GET_MICROSECOND
  51
  52/* Date accessors for date and datetime. */
  53#define SET_YEAR(o, v)		(((o)->data[0] = ((v) & 0xff00) >> 8), \
  54                                 ((o)->data[1] = ((v) & 0x00ff)))
  55#define SET_MONTH(o, v)		(PyDateTime_GET_MONTH(o) = (v))
  56#define SET_DAY(o, v)		(PyDateTime_GET_DAY(o) = (v))
  57
  58/* Date/Time accessors for datetime. */
  59#define DATE_SET_HOUR(o, v)	(PyDateTime_DATE_GET_HOUR(o) = (v))
  60#define DATE_SET_MINUTE(o, v)	(PyDateTime_DATE_GET_MINUTE(o) = (v))
  61#define DATE_SET_SECOND(o, v)	(PyDateTime_DATE_GET_SECOND(o) = (v))
  62#define DATE_SET_MICROSECOND(o, v)	\
  63	(((o)->data[7] = ((v) & 0xff0000) >> 16), \
  64         ((o)->data[8] = ((v) & 0x00ff00) >> 8), \
  65         ((o)->data[9] = ((v) & 0x0000ff)))
  66
  67/* Time accessors for time. */
  68#define TIME_GET_HOUR		PyDateTime_TIME_GET_HOUR
  69#define TIME_GET_MINUTE		PyDateTime_TIME_GET_MINUTE
  70#define TIME_GET_SECOND		PyDateTime_TIME_GET_SECOND
  71#define TIME_GET_MICROSECOND	PyDateTime_TIME_GET_MICROSECOND
  72#define TIME_SET_HOUR(o, v)	(PyDateTime_TIME_GET_HOUR(o) = (v))
  73#define TIME_SET_MINUTE(o, v)	(PyDateTime_TIME_GET_MINUTE(o) = (v))
  74#define TIME_SET_SECOND(o, v)	(PyDateTime_TIME_GET_SECOND(o) = (v))
  75#define TIME_SET_MICROSECOND(o, v)	\
  76	(((o)->data[3] = ((v) & 0xff0000) >> 16), \
  77         ((o)->data[4] = ((v) & 0x00ff00) >> 8), \
  78         ((o)->data[5] = ((v) & 0x0000ff)))
  79
  80/* Delta accessors for timedelta. */
  81#define GET_TD_DAYS(o)		(((PyDateTime_Delta *)(o))->days)
  82#define GET_TD_SECONDS(o)	(((PyDateTime_Delta *)(o))->seconds)
  83#define GET_TD_MICROSECONDS(o)	(((PyDateTime_Delta *)(o))->microseconds)
  84
  85#define SET_TD_DAYS(o, v)	((o)->days = (v))
  86#define SET_TD_SECONDS(o, v)	((o)->seconds = (v))
  87#define SET_TD_MICROSECONDS(o, v) ((o)->microseconds = (v))
  88
  89/* p is a pointer to a time or a datetime object; HASTZINFO(p) returns
  90 * p->hastzinfo.
  91 */
  92#define HASTZINFO(p)		(((_PyDateTime_BaseTZInfo *)(p))->hastzinfo)
  93
  94/* M is a char or int claiming to be a valid month.  The macro is equivalent
  95 * to the two-sided Python test
  96 *	1 <= M <= 12
  97 */
  98#define MONTH_IS_SANE(M) ((unsigned int)(M) - 1 < 12)
  99
 100/* Forward declarations. */
 101static PyTypeObject PyDateTime_DateType;
 102static PyTypeObject PyDateTime_DateTimeType;
 103static PyTypeObject PyDateTime_DeltaType;
 104static PyTypeObject PyDateTime_TimeType;
 105static PyTypeObject PyDateTime_TZInfoType;
 106
 107/* ---------------------------------------------------------------------------
 108 * Math utilities.
 109 */
 110
 111/* k = i+j overflows iff k differs in sign from both inputs,
 112 * iff k^i has sign bit set and k^j has sign bit set,
 113 * iff (k^i)&(k^j) has sign bit set.
 114 */
 115#define SIGNED_ADD_OVERFLOWED(RESULT, I, J) \
 116	((((RESULT) ^ (I)) & ((RESULT) ^ (J))) < 0)
 117
 118/* Compute Python divmod(x, y), returning the quotient and storing the
 119 * remainder into *r.  The quotient is the floor of x/y, and that's
 120 * the real point of this.  C will probably truncate instead (C99
 121 * requires truncation; C89 left it implementation-defined).
 122 * Simplification:  we *require* that y > 0 here.  That's appropriate
 123 * for all the uses made of it.  This simplifies the code and makes
 124 * the overflow case impossible (divmod(LONG_MIN, -1) is the only
 125 * overflow case).
 126 */
 127static int
 128divmod(int x, int y, int *r)
 129{
 130	int quo;
 131
 132	assert(y > 0);
 133	quo = x / y;
 134	*r = x - quo * y;
 135	if (*r < 0) {
 136		--quo;
 137		*r += y;
 138	}
 139	assert(0 <= *r && *r < y);
 140	return quo;
 141}
 142
 143/* Round a double to the nearest long.  |x| must be small enough to fit
 144 * in a C long; this is not checked.
 145 */
 146static long
 147round_to_long(double x)
 148{
 149	if (x >= 0.0)
 150		x = floor(x + 0.5);
 151	else
 152		x = ceil(x - 0.5);
 153	return (long)x;
 154}
 155
 156/* ---------------------------------------------------------------------------
 157 * General calendrical helper functions
 158 */
 159
 160/* For each month ordinal in 1..12, the number of days in that month,
 161 * and the number of days before that month in the same year.  These
 162 * are correct for non-leap years only.
 163 */
 164static int _days_in_month[] = {
 165	0, /* unused; this vector uses 1-based indexing */
 166	31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31
 167};
 168
 169static int _days_before_month[] = {
 170	0, /* unused; this vector uses 1-based indexing */
 171	0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
 172};
 173
 174/* year -> 1 if leap year, else 0. */
 175static int
 176is_leap(int year)
 177{
 178	/* Cast year to unsigned.  The result is the same either way, but
 179	 * C can generate faster code for unsigned mod than for signed
 180	 * mod (especially for % 4 -- a good compiler should just grab
 181	 * the last 2 bits when the LHS is unsigned).
 182	 */
 183	const unsigned int ayear = (unsigned int)year;
 184	return ayear % 4 == 0 && (ayear % 100 != 0 || ayear % 400 == 0);
 185}
 186
 187/* year, month -> number of days in that month in that year */
 188static int
 189days_in_month(int year, int month)
 190{
 191	assert(month >= 1);
 192	assert(month <= 12);
 193	if (month == 2 && is_leap(year))
 194		return 29;
 195	else
 196		return _days_in_month[month];
 197}
 198
 199/* year, month -> number of days in year preceeding first day of month */
 200static int
 201days_before_month(int year, int month)
 202{
 203	int days;
 204
 205	assert(month >= 1);
 206	assert(month <= 12);
 207	days = _days_before_month[month];
 208	if (month > 2 && is_leap(year))
 209		++days;
 210	return days;
 211}
 212
 213/* year -> number of days before January 1st of year.  Remember that we
 214 * start with year 1, so days_before_year(1) == 0.
 215 */
 216static int
 217days_before_year(int year)
 218{
 219	int y = year - 1;
 220	/* This is incorrect if year <= 0; we really want the floor
 221	 * here.  But so long as MINYEAR is 1, the smallest year this
 222	 * can see is 0 (this can happen in some normalization endcases),
 223	 * so we'll just special-case that.
 224	 */
 225	assert (year >= 0);
 226	if (y >= 0)
 227		return y*365 + y/4 - y/100 + y/400;
 228	else {
 229		assert(y == -1);
 230		return -366;
 231	}
 232}
 233
 234/* Number of days in 4, 100, and 400 year cycles.  That these have
 235 * the correct values is asserted in the module init function.
 236 */
 237#define DI4Y	1461	/* days_before_year(5); days in 4 years */
 238#define DI100Y	36524	/* days_before_year(101); days in 100 years */
 239#define DI400Y	146097	/* days_before_year(401); days in 400 years  */
 240
 241/* ordinal -> year, month, day, considering 01-Jan-0001 as day 1. */
 242static void
 243ord_to_ymd(int ordinal, int *year, int *month, int *day)
 244{
 245	int n, n1, n4, n100, n400, leapyear, preceding;
 246
 247	/* ordinal is a 1-based index, starting at 1-Jan-1.  The pattern of
 248	 * leap years repeats exactly every 400 years.  The basic strategy is
 249	 * to find the closest 400-year boundary at or before ordinal, then
 250	 * work with the offset from that boundary to ordinal.  Life is much
 251	 * clearer if we subtract 1 from ordinal first -- then the values
 252	 * of ordinal at 400-year boundaries are exactly those divisible
 253	 * by DI400Y:
 254	 *
 255	 *    D  M   Y            n              n-1
 256	 *    -- --- ----        ----------     ----------------
 257	 *    31 Dec -400        -DI400Y       -DI400Y -1
 258	 *     1 Jan -399         -DI400Y +1   -DI400Y      400-year boundary
 259	 *    ...
 260	 *    30 Dec  000        -1             -2
 261	 *    31 Dec  000         0             -1
 262	 *     1 Jan  001         1              0          400-year boundary
 263	 *     2 Jan  001         2              1
 264	 *     3 Jan  001         3              2
 265	 *    ...
 266	 *    31 Dec  400         DI400Y        DI400Y -1
 267	 *     1 Jan  401         DI400Y +1     DI400Y      400-year boundary
 268	 */
 269	assert(ordinal >= 1);
 270	--ordinal;
 271	n400 = ordinal / DI400Y;
 272	n = ordinal % DI400Y;
 273	*year = n400 * 400 + 1;
 274
 275	/* Now n is the (non-negative) offset, in days, from January 1 of
 276	 * year, to the desired date.  Now compute how many 100-year cycles
 277	 * precede n.
 278	 * Note that it's possible for n100 to equal 4!  In that case 4 full
 279	 * 100-year cycles precede the desired day, which implies the
 280	 * desired day is December 31 at the end of a 400-year cycle.
 281	 */
 282	n100 = n / DI100Y;
 283	n = n % DI100Y;
 284
 285	/* Now compute how many 4-year cycles precede it. */
 286	n4 = n / DI4Y;
 287	n = n % DI4Y;
 288
 289	/* And now how many single years.  Again n1 can be 4, and again
 290	 * meaning that the desired day is December 31 at the end of the
 291	 * 4-year cycle.
 292	 */
 293	n1 = n / 365;
 294	n = n % 365;
 295
 296	*year += n100 * 100 + n4 * 4 + n1;
 297	if (n1 == 4 || n100 == 4) {
 298		assert(n == 0);
 299		*year -= 1;
 300		*month = 12;
 301		*day = 31;
 302		return;
 303	}
 304
 305	/* Now the year is correct, and n is the offset from January 1.  We
 306	 * find the month via an estimate that's either exact or one too
 307	 * large.
 308	 */
 309	leapyear = n1 == 3 && (n4 != 24 || n100 == 3);
 310	assert(leapyear == is_leap(*year));
 311	*month = (n + 50) >> 5;
 312	preceding = (_days_before_month[*month] + (*month > 2 && leapyear));
 313	if (preceding > n) {
 314		/* estimate is too large */
 315		*month -= 1;
 316		preceding -= days_in_month(*year, *month);
 317	}
 318	n -= preceding;
 319	assert(0 <= n);
 320	assert(n < days_in_month(*year, *month));
 321
 322	*day = n + 1;
 323}
 324
 325/* year, month, day -> ordinal, considering 01-Jan-0001 as day 1. */
 326static int
 327ymd_to_ord(int year, int month, int day)
 328{
 329	return days_before_year(year) + days_before_month(year, month) + day;
 330}
 331
 332/* Day of week, where Monday==0, ..., Sunday==6.  1/1/1 was a Monday. */
 333static int
 334weekday(int year, int month, int day)
 335{
 336	return (ymd_to_ord(year, month, day) + 6) % 7;
 337}
 338
 339/* Ordinal of the Monday starting week 1 of the ISO year.  Week 1 is the
 340 * first calendar week containing a Thursday.
 341 */
 342static int
 343iso_week1_monday(int year)
 344{
 345	int first_day = ymd_to_ord(year, 1, 1);	/* ord of 1/1 */
 346	/* 0 if 1/1 is a Monday, 1 if a Tue, etc. */
 347	int first_weekday = (first_day + 6) % 7;
 348	/* ordinal of closest Monday at or before 1/1 */
 349	int week1_monday  = first_day - first_weekday;
 350
 351	if (first_weekday > 3)	/* if 1/1 was Fri, Sat, Sun */
 352		week1_monday += 7;
 353	return week1_monday;
 354}
 355
 356/* ---------------------------------------------------------------------------
 357 * Range checkers.
 358 */
 359
 360/* Check that -MAX_DELTA_DAYS <= days <= MAX_DELTA_DAYS.  If so, return 0.
 361 * If not, raise OverflowError and return -1.
 362 */
 363static int
 364check_delta_day_range(int days)
 365{
 366	if (-MAX_DELTA_DAYS <= days && days <= MAX_DELTA_DAYS)
 367		return 0;
 368	PyErr_Format(PyExc_OverflowError,
 369		     "days=%d; must have magnitude <= %d",
 370		     days, MAX_DELTA_DAYS);
 371	return -1;
 372}
 373
 374/* Check that date arguments are in range.  Return 0 if they are.  If they
 375 * aren't, raise ValueError and return -1.
 376 */
 377static int
 378check_date_args(int year, int month, int day)
 379{
 380
 381	if (year < MINYEAR || year > MAXYEAR) {
 382		PyErr_SetString(PyExc_ValueError,
 383				"year is out of range");
 384		return -1;
 385	}
 386	if (month < 1 || month > 12) {
 387		PyErr_SetString(PyExc_ValueError,
 388				"month must be in 1..12");
 389		return -1;
 390	}
 391	if (day < 1 || day > days_in_month(year, month)) {
 392		PyErr_SetString(PyExc_ValueError,
 393				"day is out of range for month");
 394		return -1;
 395	}
 396	return 0;
 397}
 398
 399/* Check that time arguments are in range.  Return 0 if they are.  If they
 400 * aren't, raise ValueError and return -1.
 401 */
 402static int
 403check_time_args(int h, int m, int s, int us)
 404{
 405	if (h < 0 || h > 23) {
 406		PyErr_SetString(PyExc_ValueError,
 407				"hour must be in 0..23");
 408		return -1;
 409	}
 410	if (m < 0 || m > 59) {
 411		PyErr_SetString(PyExc_ValueError,
 412				"minute must be in 0..59");
 413		return -1;
 414	}
 415	if (s < 0 || s > 59) {
 416		PyErr_SetString(PyExc_ValueError,
 417				"second must be in 0..59");
 418		return -1;
 419	}
 420	if (us < 0 || us > 999999) {
 421		PyErr_SetString(PyExc_ValueError,
 422				"microsecond must be in 0..999999");
 423		return -1;
 424	}
 425	return 0;
 426}
 427
 428/* ---------------------------------------------------------------------------
 429 * Normalization utilities.
 430 */
 431
 432/* One step of a mixed-radix conversion.  A "hi" unit is equivalent to
 433 * factor "lo" units.  factor must be > 0.  If *lo is less than 0, or
 434 * at least factor, enough of *lo is converted into "hi" units so that
 435 * 0 <= *lo < factor.  The input values must be such that int overflow
 436 * is impossible.
 437 */
 438static void
 439normalize_pair(int *hi, int *lo, int factor)
 440{
 441	assert(factor > 0);
 442	assert(lo != hi);
 443	if (*lo < 0 || *lo >= factor) {
 444		const int num_hi = divmod(*lo, factor, lo);
 445		const int new_hi = *hi + num_hi;
 446		assert(! SIGNED_ADD_OVERFLOWED(new_hi, *hi, num_hi));
 447		*hi = new_hi;
 448	}
 449	assert(0 <= *lo && *lo < factor);
 450}
 451
 452/* Fiddle days (d), seconds (s), and microseconds (us) so that
 453 * 	0 <= *s < 24*3600
 454 * 	0 <= *us < 1000000
 455 * The input values must be such that the internals don't overflow.
 456 * The way this routine is used, we don't get close.
 457 */
 458static void
 459normalize_d_s_us(int *d, int *s, int *us)
 460{
 461	if (*us < 0 || *us >= 1000000) {
 462		normalize_pair(s, us, 1000000);
 463		/* |s| can't be bigger than about
 464		 * |original s| + |original us|/1000000 now.
 465		 */
 466
 467	}
 468	if (*s < 0 || *s >= 24*3600) {
 469		normalize_pair(d, s, 24*3600);
 470		/* |d| can't be bigger than about
 471		 * |original d| +
 472		 * (|original s| + |original us|/1000000) / (24*3600) now.
 473		 */
 474	}
 475	assert(0 <= *s && *s < 24*3600);
 476	assert(0 <= *us && *us < 1000000);
 477}
 478
 479/* Fiddle years (y), months (m), and days (d) so that
 480 * 	1 <= *m <= 12
 481 * 	1 <= *d <= days_in_month(*y, *m)
 482 * The input values must be such that the internals don't overflow.
 483 * The way this routine is used, we don't get close.
 484 */
 485static void
 486normalize_y_m_d(int *y, int *m, int *d)
 487{
 488	int dim;	/* # of days in month */
 489
 490	/* This gets muddy:  the proper range for day can't be determined
 491	 * without knowing the correct month and year, but if day is, e.g.,
 492	 * plus or minus a million, the current month and year values make
 493	 * no sense (and may also be out of bounds themselves).
 494	 * Saying 12 months == 1 year should be non-controversial.
 495	 */
 496	if (*m < 1 || *m > 12) {
 497		--*m;
 498		normalize_pair(y, m, 12);
 499		++*m;
 500		/* |y| can't be bigger than about
 501		 * |original y| + |original m|/12 now.
 502		 */
 503	}
 504	assert(1 <= *m && *m <= 12);
 505
 506	/* Now only day can be out of bounds (year may also be out of bounds
 507	 * for a datetime object, but we don't care about that here).
 508	 * If day is out of bounds, what to do is arguable, but at least the
 509	 * method here is principled and explainable.
 510	 */
 511	dim = days_in_month(*y, *m);
 512	if (*d < 1 || *d > dim) {
 513		/* Move day-1 days from the first of the month.  First try to
 514		 * get off cheap if we're only one day out of range
 515		 * (adjustments for timezone alone can't be worse than that).
 516		 */
 517		if (*d == 0) {
 518			--*m;
 519			if (*m > 0)
 520				*d = days_in_month(*y, *m);
 521			else {
 522				--*y;
 523				*m = 12;
 524				*d = 31;
 525			}
 526		}
 527		else if (*d == dim + 1) {
 528			/* move forward a day */
 529			++*m;
 530			*d = 1;
 531			if (*m > 12) {
 532				*m = 1;
 533				++*y;
 534			}
 535		}
 536		else {
 537			int ordinal = ymd_to_ord(*y, *m, 1) +
 538						  *d - 1;
 539			ord_to_ymd(ordinal, y, m, d);
 540		}
 541	}
 542	assert(*m > 0);
 543	assert(*d > 0);
 544}
 545
 546/* Fiddle out-of-bounds months and days so that the result makes some kind
 547 * of sense.  The parameters are both inputs and outputs.  Returns < 0 on
 548 * failure, where failure means the adjusted year is out of bounds.
 549 */
 550static int
 551normalize_date(int *year, int *month, int *day)
 552{
 553	int result;
 554
 555	normalize_y_m_d(year, month, day);
 556	if (MINYEAR <= *year && *year <= MAXYEAR)
 557		result = 0;
 558	else {
 559		PyErr_SetString(PyExc_OverflowError,
 560				"date value out of range");
 561		result = -1;
 562	}
 563	return result;
 564}
 565
 566/* Force all the datetime fields into range.  The parameters are both
 567 * inputs and outputs.  Returns < 0 on error.
 568 */
 569static int
 570normalize_datetime(int *year, int *month, int *day,
 571                   int *hour, int *minute, int *second,
 572                   int *microsecond)
 573{
 574	normalize_pair(second, microsecond, 1000000);
 575	normalize_pair(minute, second, 60);
 576	normalize_pair(hour, minute, 60);
 577	normalize_pair(day, hour, 24);
 578	return normalize_date(year, month, day);
 579}
 580
 581/* ---------------------------------------------------------------------------
 582 * Basic object allocation:  tp_alloc implementations.  These allocate
 583 * Python objects of the right size and type, and do the Python object-
 584 * initialization bit.  If there's not enough memory, they return NULL after
 585 * setting MemoryError.  All data members remain uninitialized trash.
 586 *
 587 * We abuse the tp_alloc "nitems" argument to communicate whether a tzinfo
 588 * member is needed.  This is ugly, imprecise, and possibly insecure.
 589 * tp_basicsize for the time and datetime types is set to the size of the
 590 * struct that has room for the tzinfo member, so subclasses in Python will
 591 * allocate enough space for a tzinfo member whether or not one is actually
 592 * needed.  That's the "ugly and imprecise" parts.  The "possibly insecure"
 593 * part is that PyType_GenericAlloc() (which subclasses in Python end up
 594 * using) just happens today to effectively ignore the nitems argument
 595 * when tp_itemsize is 0, which it is for these type objects.  If that
 596 * changes, perhaps the callers of tp_alloc slots in this file should
 597 * be changed to force a 0 nitems argument unless the type being allocated
 598 * is a base type implemented in this file (so that tp_alloc is time_alloc
 599 * or datetime_alloc below, which know about the nitems abuse).
 600 */
 601
 602static PyObject *
 603time_alloc(PyTypeObject *type, Py_ssize_t aware)
 604{
 605	PyObject *self;
 606
 607	self = (PyObject *)
 608		PyObject_MALLOC(aware ?
 609				sizeof(PyDateTime_Time) :
 610				sizeof(_PyDateTime_BaseTime));
 611	if (self == NULL)
 612		return (PyObject *)PyErr_NoMemory();
 613	PyObject_INIT(self, type);
 614	return self;
 615}
 616
 617static PyObject *
 618datetime_alloc(PyTypeObject *type, Py_ssize_t aware)
 619{
 620	PyObject *self;
 621
 622	self = (PyObject *)
 623		PyObject_MALLOC(aware ?
 624				sizeof(PyDateTime_DateTime) :
 625				sizeof(_PyDateTime_BaseDateTime));
 626	if (self == NULL)
 627		return (PyObject *)PyErr_NoMemory();
 628	PyObject_INIT(self, type);
 629	return self;
 630}
 631
 632/* ---------------------------------------------------------------------------
 633 * Helpers for setting object fields.  These work on pointers to the
 634 * appropriate base class.
 635 */
 636
 637/* For date and datetime. */
 638static void
 639set_date_fields(PyDateTime_Date *self, int y, int m, int d)
 640{
 641	self->hashcode = -1;
 642	SET_YEAR(self, y);
 643	SET_MONTH(self, m);
 644	SET_DAY(self, d);
 645}
 646
 647/* ---------------------------------------------------------------------------
 648 * Create various objects, mostly without range checking.
 649 */
 650
 651/* Create a date instance with no range checking. */
 652static PyObject *
 653new_date_ex(int year, int month, int day, PyTypeObject *type)
 654{
 655	PyDateTime_Date *self;
 656
 657	self = (PyDateTime_Date *) (type->tp_alloc(type, 0));
 658	if (self != NULL)
 659		set_date_fields(self, year, month, day);
 660	return (PyObject *) self;
 661}
 662
 663#define new_date(year, month, day) \
 664	new_date_ex(year, month, day, &PyDateTime_DateType)
 665
 666/* Create a datetime instance with no range checking. */
 667static PyObject *
 668new_datetime_ex(int year, int month, int day, int hour, int minute,
 669	     int second, int usecond, PyObject *tzinfo, PyTypeObject *type)
 670{
 671	PyDateTime_DateTime *self;
 672	char aware = tzinfo != Py_None;
 673
 674	self = (PyDateTime_DateTime *) (type->tp_alloc(type, aware));
 675	if (self != NULL) {
 676		self->hastzinfo = aware;
 677		set_date_fields((PyDateTime_Date *)self, year, month, day);
 678		DATE_SET_HOUR(self, hour);
 679		DATE_SET_MINUTE(self, minute);
 680		DATE_SET_SECOND(self, second);
 681		DATE_SET_MICROSECOND(self, usecond);
 682		if (aware) {
 683			Py_INCREF(tzinfo);
 684			self->tzinfo = tzinfo;
 685		}
 686	}
 687	return (PyObject *)self;
 688}
 689
 690#define new_datetime(y, m, d, hh, mm, ss, us, tzinfo)		\
 691	new_datetime_ex(y, m, d, hh, mm, ss, us, tzinfo,	\
 692			&PyDateTime_DateTimeType)
 693
 694/* Create a time instance with no range checking. */
 695static PyObject *
 696new_time_ex(int hour, int minute, int second, int usecond,
 697	    PyObject *tzinfo, PyTypeObject *type)
 698{
 699	PyDateTime_Time *self;
 700	char aware = tzinfo != Py_None;
 701
 702	self = (PyDateTime_Time *) (type->tp_alloc(type, aware));
 703	if (self != NULL) {
 704		self->hastzinfo = aware;
 705		self->hashcode = -1;
 706		TIME_SET_HOUR(self, hour);
 707		TIME_SET_MINUTE(self, minute);
 708		TIME_SET_SECOND(self, second);
 709		TIME_SET_MICROSECOND(self, usecond);
 710		if (aware) {
 711			Py_INCREF(tzinfo);
 712			self->tzinfo = tzinfo;
 713		}
 714	}
 715	return (PyObject *)self;
 716}
 717
 718#define new_time(hh, mm, ss, us, tzinfo)		\
 719	new_time_ex(hh, mm, ss, us, tzinfo, &PyDateTime_TimeType)
 720
 721/* Create a timedelta instance.  Normalize the members iff normalize is
 722 * true.  Passing false is a speed optimization, if you know for sure
 723 * that seconds and microseconds are already in their proper ranges.  In any
 724 * case, raises OverflowError and returns NULL if the normalized days is out
 725 * of range).
 726 */
 727static PyObject *
 728new_delta_ex(int days, int seconds, int microseconds, int normalize,
 729	     PyTypeObject *type)
 730{
 731	PyDateTime_Delta *self;
 732
 733	if (normalize)
 734		normalize_d_s_us(&days, &seconds, &microseconds);
 735	assert(0 <= seconds && seconds < 24*3600);
 736	assert(0 <= microseconds && microseconds < 1000000);
 737
 738 	if (check_delta_day_range(days) < 0)
 739 		return NULL;
 740
 741	self = (PyDateTime_Delta *) (type->tp_alloc(type, 0));
 742	if (self != NULL) {
 743		self->hashcode = -1;
 744		SET_TD_DAYS(self, days);
 745		SET_TD_SECONDS(self, seconds);
 746		SET_TD_MICROSECONDS(self, microseconds);
 747	}
 748	return (PyObject *) self;
 749}
 750
 751#define new_delta(d, s, us, normalize)	\
 752	new_delta_ex(d, s, us, normalize, &PyDateTime_DeltaType)
 753
 754/* ---------------------------------------------------------------------------
 755 * tzinfo helpers.
 756 */
 757
 758/* Ensure that p is None or of a tzinfo subclass.  Return 0 if OK; if not
 759 * raise TypeError and return -1.
 760 */
 761static int
 762check_tzinfo_subclass(PyObject *p)
 763{
 764	if (p == Py_None || PyTZInfo_Check(p))
 765		return 0;
 766	PyErr_Format(PyExc_TypeError,
 767		     "tzinfo argument must be None or of a tzinfo subclass, "
 768		     "not type '%s'",
 769		     Py_TYPE(p)->tp_name);
 770	return -1;
 771}
 772
 773/* Return tzinfo.methname(tzinfoarg), without any checking of results.
 774 * If tzinfo is None, returns None.
 775 */
 776static PyObject *
 777call_tzinfo_method(PyObject *tzinfo, char *methname, PyObject *tzinfoarg)
 778{
 779	PyObject *result;
 780
 781	assert(tzinfo && methname && tzinfoarg);
 782	assert(check_tzinfo_subclass(tzinfo) >= 0);
 783	if (tzinfo == Py_None) {
 784		result = Py_None;
 785		Py_INCREF(result);
 786	}
 787	else
 788		result = PyObject_CallMethod(tzinfo, methname, "O", tzinfoarg);
 789	return result;
 790}
 791
 792/* If self has a tzinfo member, return a BORROWED reference to it.  Else
 793 * return NULL, which is NOT AN ERROR.  There are no error returns here,
 794 * and the caller must not decref the result.
 795 */
 796static PyObject *
 797get_tzinfo_member(PyObject *self)
 798{
 799	PyObject *tzinfo = NULL;
 800
 801	if (PyDateTime_Check(self) && HASTZINFO(self))
 802		tzinfo = ((PyDateTime_DateTime *)self)->tzinfo;
 803	else if (PyTime_Check(self) && HASTZINFO(self))
 804		tzinfo = ((PyDateTime_Time *)self)->tzinfo;
 805
 806	return tzinfo;
 807}
 808
 809/* Call getattr(tzinfo, name)(tzinfoarg), and extract an int from the
 810 * result.  tzinfo must be an instance of the tzinfo class.  If the method
 811 * returns None, this returns 0 and sets *none to 1.  If the method doesn't
 812 * return None or timedelta, TypeError is raised and this returns -1.  If it
 813 * returnsa timedelta and the value is out of range or isn't a whole number
 814 * of minutes, ValueError is raised and this returns -1.
 815 * Else *none is set to 0 and the integer method result is returned.
 816 */
 817static int
 818call_utc_tzinfo_method(PyObject *tzinfo, char *name, PyObject *tzinfoarg,
 819		       int *none)
 820{
 821	PyObject *u;
 822	int result = -1;
 823
 824	assert(tzinfo != NULL);
 825	assert(PyTZInfo_Check(tzinfo));
 826	assert(tzinfoarg != NULL);
 827
 828	*none = 0;
 829	u = call_tzinfo_method(tzinfo, name, tzinfoarg);
 830	if (u == NULL)
 831		return -1;
 832
 833	else if (u == Py_None) {
 834		result = 0;
 835		*none = 1;
 836	}
 837	else if (PyDelta_Check(u)) {
 838		const int days = GET_TD_DAYS(u);
 839		if (days < -1 || days > 0)
 840			result = 24*60;	/* trigger ValueError below */
 841		else {
 842			/* next line can't overflow because we know days
 843			 * is -1 or 0 now
 844			 */
 845			int ss = days * 24 * 3600 + GET_TD_SECONDS(u);
 846			result = divmod(ss, 60, &ss);
 847			if (ss || GET_TD_MICROSECONDS(u)) {
 848				PyErr_Format(PyExc_ValueError,
 849					     "tzinfo.%s() must return a "
 850					     "whole number of minutes",
 851					     name);
 852				result = -1;
 853			}
 854		}
 855	}
 856	else {
 857		PyErr_Format(PyExc_TypeError,
 858			     "tzinfo.%s() must return None or "
 859			     "timedelta, not '%s'",
 860			     name, Py_TYPE(u)->tp_name);
 861	}
 862
 863	Py_DECREF(u);
 864	if (result < -1439 || result > 1439) {
 865		PyErr_Format(PyExc_ValueError,
 866			     "tzinfo.%s() returned %d; must be in "
 867			     "-1439 .. 1439",
 868			     name, result);
 869		result = -1;
 870	}
 871	return result;
 872}
 873
 874/* Call tzinfo.utcoffset(tzinfoarg), and extract an integer from the
 875 * result.  tzinfo must be an instance of the tzinfo class.  If utcoffset()
 876 * returns None, call_utcoffset returns 0 and sets *none to 1.  If uctoffset()
 877 * doesn't return None or timedelta, TypeError is raised and this returns -1.
 878 * If utcoffset() returns an invalid timedelta (out of range, or not a whole
 879 * # of minutes), ValueError is raised and this returns -1.  Else *none is
 880 * set to 0 and the offset is returned (as int # of minutes east of UTC).
 881 */
 882static int
 883call_utcoffset(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
 884{
 885	return call_utc_tzinfo_method(tzinfo, "utcoffset", tzinfoarg, none);
 886}
 887
 888/* Call tzinfo.name(tzinfoarg), and return the offset as a timedelta or None.
 889 */
 890static PyObject *
 891offset_as_timedelta(PyObject *tzinfo, char *name, PyObject *tzinfoarg) {
 892	PyObject *result;
 893
 894	assert(tzinfo && name && tzinfoarg);
 895	if (tzinfo == Py_None) {
 896		result = Py_None;
 897		Py_INCREF(result);
 898	}
 899	else {
 900		int none;
 901		int offset = call_utc_tzinfo_method(tzinfo, name, tzinfoarg,
 902						    &none);
 903		if (offset < 0 && PyErr_Occurred())
 904			return NULL;
 905		if (none) {
 906			result = Py_None;
 907			Py_INCREF(result);
 908		}
 909		else
 910			result = new_delta(0, offset * 60, 0, 1);
 911	}
 912	return result;
 913}
 914
 915/* Call tzinfo.dst(tzinfoarg), and extract an integer from the
 916 * result.  tzinfo must be an instance of the tzinfo class.  If dst()
 917 * returns None, call_dst returns 0 and sets *none to 1.  If dst()
 918 & doesn't return None or timedelta, TypeError is raised and this
 919 * returns -1.  If dst() returns an invalid timedelta for a UTC offset,
 920 * ValueError is raised and this returns -1.  Else *none is set to 0 and
 921 * the offset is returned (as an int # of minutes east of UTC).
 922 */
 923static int
 924call_dst(PyObject *tzinfo, PyObject *tzinfoarg, int *none)
 925{
 926	return call_utc_tzinfo_method(tzinfo, "dst", tzinfoarg, none);
 927}
 928
 929/* Call tzinfo.tzname(tzinfoarg), and return the result.  tzinfo must be
 930 * an instance of the tzinfo class or None.  If tzinfo isn't None, and
 931 * tzname() doesn't return None or a string, TypeError is raised and this
 932 * returns NULL.
 933 */
 934static PyObject *
 935call_tzname(PyObject *tzinfo, PyObject *tzinfoarg)
 936{
 937	PyObject *result;
 938
 939	assert(tzinfo != NULL);
 940	assert(check_tzinfo_subclass(tzinfo) >= 0);
 941	assert(tzinfoarg != NULL);
 942
 943	if (tzinfo == Py_None) {
 944		result = Py_None;
 945		Py_INCREF(result);
 946	}
 947	else
 948		result = PyObject_CallMethod(tzinfo, "tzname", "O", tzinfoarg);
 949
 950	if (result != NULL && result != Py_None && ! PyString_Check(result)) {
 951		PyErr_Format(PyExc_TypeError, "tzinfo.tzname() must "
 952			     "return None or a string, not '%s'",
 953			     Py_TYPE(result)->tp_name);
 954		Py_DECREF(result);
 955		result = NULL;
 956	}
 957	return result;
 958}
 959
 960typedef enum {
 961	      /* an exception has been set; the caller should pass it on */
 962	      OFFSET_ERROR,
 963
 964	      /* type isn't date, datetime, or time subclass */
 965	      OFFSET_UNKNOWN,
 966
 967	      /* date,
 968	       * datetime with !hastzinfo
 969	       * datetime with None tzinfo,
 970	       * datetime where utcoffset() returns None
 971	       * time with !hastzinfo
 972	       * time with None tzinfo,
 973	       * time where utcoffset() returns None
 974	       */
 975	      OFFSET_NAIVE,
 976
 977	      /* time or datetime where utcoffset() doesn't return None */
 978	      OFFSET_AWARE
 979} naivety;
 980
 981/* Classify an object as to whether it's naive or offset-aware.  See
 982 * the "naivety" typedef for details.  If the type is aware, *offset is set
 983 * to minutes east of UTC (as returned by the tzinfo.utcoffset() method).
 984 * If the type is offset-naive (or unknown, or error), *offset is set to 0.
 985 * tzinfoarg is the argument to pass to the tzinfo.utcoffset() method.
 986 */
 987static naivety
 988classify_utcoffset(PyObject *op, PyObject *tzinfoarg, int *offset)
 989{
 990	int none;
 991	PyObject *tzinfo;
 992
 993	assert(tzinfoarg != NULL);
 994	*offset = 0;
 995	tzinfo = get_tzinfo_member(op);	/* NULL means no tzinfo, not error */
 996	if (tzinfo == Py_None)
 997		return OFFSET_NAIVE;
 998	if (tzinfo == NULL) {
 999		/* note that a datetime passes the PyDate_Check test */
1000		return (PyTime_Check(op) || PyDate_Check(op)) ?
1001		       OFFSET_NAIVE : OFFSET_UNKNOWN;
1002	}
1003	*offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1004	if (*offset == -1 && PyErr_Occurred())
1005		return OFFSET_ERROR;
1006	return none ? OFFSET_NAIVE : OFFSET_AWARE;
1007}
1008
1009/* Classify two objects as to whether they're naive or offset-aware.
1010 * This isn't quite the same as calling classify_utcoffset() twice:  for
1011 * binary operations (comparison and subtraction), we generally want to
1012 * ignore the tzinfo members if they're identical.  This is by design,
1013 * so that results match "naive" expectations when mixing objects from a
1014 * single timezone.  So in that case, this sets both offsets to 0 and
1015 * both naiveties to OFFSET_NAIVE.
1016 * The function returns 0 if everything's OK, and -1 on error.
1017 */
1018static int
1019classify_two_utcoffsets(PyObject *o1, int *offset1, naivety *n1,
1020			PyObject *tzinfoarg1,
1021			PyObject *o2, int *offset2, naivety *n2,
1022			PyObject *tzinfoarg2)
1023{
1024	if (get_tzinfo_member(o1) == get_tzinfo_member(o2)) {
1025		*offset1 = *offset2 = 0;
1026		*n1 = *n2 = OFFSET_NAIVE;
1027	}
1028	else {
1029		*n1 = classify_utcoffset(o1, tzinfoarg1, offset1);
1030		if (*n1 == OFFSET_ERROR)
1031			return -1;
1032		*n2 = classify_utcoffset(o2, tzinfoarg2, offset2);
1033		if (*n2 == OFFSET_ERROR)
1034			return -1;
1035	}
1036	return 0;
1037}
1038
1039/* repr is like "someclass(arg1, arg2)".  If tzinfo isn't None,
1040 * stuff
1041 *     ", tzinfo=" + repr(tzinfo)
1042 * before the closing ")".
1043 */
1044static PyObject *
1045append_keyword_tzinfo(PyObject *repr, PyObject *tzinfo)
1046{
1047	PyObject *temp;
1048
1049	assert(PyString_Check(repr));
1050	assert(tzinfo);
1051	if (tzinfo == Py_None)
1052		return repr;
1053	/* Get rid of the trailing ')'. */
1054	assert(PyString_AsString(repr)[PyString_Size(repr)-1] == ')');
1055	temp = PyString_FromStringAndSize(PyString_AsString(repr),
1056					  PyString_Size(repr) - 1);
1057	Py_DECREF(repr);
1058	if (temp == NULL)
1059		return NULL;
1060	repr = temp;
1061
1062	/* Append ", tzinfo=". */
1063	PyString_ConcatAndDel(&repr, PyString_FromString(", tzinfo="));
1064
1065	/* Append repr(tzinfo). */
1066	PyString_ConcatAndDel(&repr, PyObject_Repr(tzinfo));
1067
1068	/* Add a closing paren. */
1069	PyString_ConcatAndDel(&repr, PyString_FromString(")"));
1070	return repr;
1071}
1072
1073/* ---------------------------------------------------------------------------
1074 * String format helpers.
1075 */
1076
1077static PyObject *
1078format_ctime(PyDateTime_Date *date, int hours, int minutes, int seconds)
1079{
1080	static const char *DayNames[] = {
1081		"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"
1082	};
1083	static const char *MonthNames[] = {
1084		"Jan", "Feb", "Mar", "Apr", "May", "Jun",
1085		"Jul", "Aug", "Sep", "Oct", "Nov", "Dec"
1086	};
1087
1088	char buffer[128];
1089	int wday = weekday(GET_YEAR(date), GET_MONTH(date), GET_DAY(date));
1090
1091	PyOS_snprintf(buffer, sizeof(buffer), "%s %s %2d %02d:%02d:%02d %04d",
1092		      DayNames[wday], MonthNames[GET_MONTH(date) - 1],
1093		      GET_DAY(date), hours, minutes, seconds,
1094		      GET_YEAR(date));
1095	return PyString_FromString(buffer);
1096}
1097
1098/* Add an hours & minutes UTC offset string to buf.  buf has no more than
1099 * buflen bytes remaining.  The UTC offset is gotten by calling
1100 * tzinfo.uctoffset(tzinfoarg).  If that returns None, \0 is stored into
1101 * *buf, and that's all.  Else the returned value is checked for sanity (an
1102 * integer in range), and if that's OK it's converted to an hours & minutes
1103 * string of the form
1104 *   sign HH sep MM
1105 * Returns 0 if everything is OK.  If the return value from utcoffset() is
1106 * bogus, an appropriate exception is set and -1 is returned.
1107 */
1108static int
1109format_utcoffset(char *buf, size_t buflen, const char *sep,
1110		PyObject *tzinfo, PyObject *tzinfoarg)
1111{
1112	int offset;
1113	int hours;
1114	int minutes;
1115	char sign;
1116	int none;
1117
1118	assert(buflen >= 1);
1119
1120	offset = call_utcoffset(tzinfo, tzinfoarg, &none);
1121	if (offset == -1 && PyErr_Occurred())
1122		return -1;
1123	if (none) {
1124		*buf = '\0';
1125		return 0;
1126	}
1127	sign = '+';
1128	if (offset < 0) {
1129		sign = '-';
1130		offset = - offset;
1131	}
1132	hours = divmod(offset, 60, &minutes);
1133	PyOS_snprintf(buf, buflen, "%c%02d%s%02d", sign, hours, sep, minutes);
1134	return 0;
1135}
1136
1137static PyObject *
1138make_freplacement(PyObject *object)
1139{
1140	char freplacement[64];
1141	if (PyTime_Check(object))
1142	    sprintf(freplacement, "%06d", TIME_GET_MICROSECOND(object));
1143	else if (PyDateTime_Check(object))
1144	    sprintf(freplacement, "%06d", DATE_GET_MICROSECOND(object));
1145	else
1146	    sprintf(freplacement, "%06d", 0);
1147
1148	return PyString_FromStringAndSize(freplacement, strlen(freplacement));
1149}
1150
1151/* I sure don't want to reproduce the strftime code from the time module,
1152 * so this imports the module and calls it.  All the hair is due to
1153 * giving special meanings to the %z, %Z and %f format codes via a
1154 * preprocessing step on the format string.
1155 * tzinfoarg is the argument to pass to the object's tzinfo method, if
1156 * needed.
1157 */
1158static PyObject *
1159wrap_strftime(PyObject *object, const char *format, size_t format_len,
1160		PyObject *timetuple, PyObject *tzinfoarg)
1161{
1162	PyObject *result = NULL;	/* guilty until proved innocent */
1163
1164	PyObject *zreplacement = NULL;	/* py string, replacement for %z */
1165	PyObject *Zreplacement = NULL;	/* py string, replacement for %Z */
1166	PyObject *freplacement = NULL;	/* py string, replacement for %f */
1167
1168	const char *pin;	/* pointer to next char in input format */
1169	char ch;		/* next char in input format */
1170
1171	PyObject *newfmt = NULL;	/* py string, the output format */
1172	char *pnew;	/* pointer to available byte in output format */
1173	size_t totalnew;	/* number bytes total in output format buffer,
1174				   exclusive of trailing \0 */
1175	size_t usednew;	/* number bytes used so far in output format buffer */
1176
1177	const char *ptoappend;	/* ptr to string to append to output buffer */
1178	size_t ntoappend;	/* # of bytes to append to output buffer */
1179
1180	assert(object && format && timetuple);
1181
1182	/* Give up if the year is before 1900.
1183	 * Python strftime() plays games with the year, and different
1184	 * games depending on whether envar PYTHON2K is set.  This makes
1185	 * years before 1900 a nightmare, even if the platform strftime
1186	 * supports them (and not all do).
1187	 * We could get a lot farther here by avoiding Python's strftime
1188	 * wrapper and calling the C strftime() directly, but that isn't
1189	 * an option in the Python implementation of this module.
1190	 */
1191	{
1192		long year;
1193		PyObject *pyyear = PySequence_GetItem(timetuple, 0);
1194		if (pyyear == NULL) return NULL;
1195		assert(PyInt_Check(pyyear));
1196		year = PyInt_AsLong(pyyear);
1197		Py_DECREF(pyyear);
1198		if (year < 1900) {
1199			PyErr_Format(PyExc_ValueError, "year=%ld is before "
1200				     "1900; the datetime strftime() "
1201	                             "methods require year >= 1900",
1202	                             year);
1203	                return NULL;
1204		}
1205	}
1206
1207	/* Scan the input format, looking for %z/%Z/%f escapes, building
1208	 * a new format.  Since computing the replacements for those codes
1209	 * is expensive, don't unless they're actually used.
1210	 */
1211	if (format_len > INT_MAX - 1) {
1212		PyErr_NoMemory();
1213		goto Done;
1214	}
1215
1216	totalnew = format_len + 1;	/* realistic if no %z/%Z/%f */
1217	newfmt = PyString_FromStringAndSize(NULL, totalnew);
1218	if (newfmt == NULL) goto Done;
1219	pnew = PyString_AsString(newfmt);
1220	usednew = 0;
1221
1222	pin = format;
1223	while ((ch = *pin++) != '\0') {
1224		if (ch != '%') {
1225			ptoappend = pin - 1;
1226			ntoappend = 1;
1227		}
1228		else if ((ch = *pin++) == '\0') {
1229			/* There's a lone trailing %; doesn't make sense. */
1230			PyErr_SetString(PyExc_ValueError, "strftime format "
1231					"ends with raw %");
1232			goto Done;
1233		}
1234		/* A % has been seen and ch is the character after it. */
1235		else if (ch == 'z') {
1236			if (zreplacement == NULL) {
1237				/* format utcoffset */
1238				char buf[100];
1239				PyObject *tzinfo = get_tzinfo_member(object);
1240				zreplacement = PyString_FromString("");
1241				if (zreplacement == NULL) goto Done;
1242				if (tzinfo != Py_None && tzinfo != NULL) {
1243					assert(tzinfoarg != NULL);
1244					if (format_utcoffset(buf,
1245							     sizeof(buf),
1246							     "",
1247							     tzinfo,
1248							     tzinfoarg) < 0)
1249						goto Done;
1250					Py_DECREF(zreplacement);
1251					zreplacement = PyString_FromString(buf);
1252					if (zreplacement == NULL) goto Done;
1253				}
1254			}
1255			assert(zreplacement != NULL);
1256			ptoappend = PyString_AS_STRING(zreplacement);
1257			ntoappend = PyString_GET_SIZE(zreplacement);
1258		}
1259		else if (ch == 'Z') {
1260			/* format tzname */
1261			if (Zreplacement == NULL) {
1262				PyObject *tzinfo = get_tzinfo_member(object);
1263				Zreplacement = PyString_FromString("");
1264				if (Zreplacement == NULL) goto Done;
1265				if (tzinfo != Py_None && tzinfo != NULL) {
1266					PyObject *temp;
1267					assert(tzinfoarg != NULL);
1268					temp = call_tzname(tzinfo, tzinfoarg);
1269					if (temp == NULL) goto Done;
1270					if (temp != Py_None) {
1271						assert(PyString_Check(temp));
1272						/* Since the tzname is getting
1273						 * stuffed into the format, we
1274						 * have to double any % signs
1275						 * so that strftime doesn't
1276						 * treat them as format codes.
1277						 */
1278						Py_DECREF(Zreplacement);
1279						Zreplacement = PyObject_CallMethod(
1280							temp, "replace",
1281							"ss", "%", "%%");
1282						Py_DECREF(temp);
1283						if (Zreplacement == NULL)
1284							goto Done;
1285						if (!PyString_Check(Zreplacement)) {
1286							PyErr_SetString(PyExc_TypeError, "tzname.replace() did not return a string");
1287							goto Done;
1288						}
1289					}
1290					else
1291						Py_DECREF(temp);
1292				}
1293			}
1294			assert(Zreplacement != NULL);
1295			ptoappend = PyString_AS_STRING(Zreplacement);
1296			ntoappend = PyString_GET_SIZE(Zreplacement);
1297		}
1298		else if (ch == 'f') {
1299			/* format microseconds */
1300			if (freplacement == NULL) {
1301				freplacement = make_freplacement(object);
1302				if (freplacement == NULL)
1303					goto Done;
1304			}
1305			assert(freplacement != NULL);
1306			assert(PyString_Check(freplacement));
1307			ptoappend = PyString_AS_STRING(freplacement);
1308			ntoappend = PyString_GET_SIZE(freplacement);
1309		}
1310		else {
1311			/* percent followed by neither z nor Z */
1312			ptoappend = pin - 2;
1313			ntoappend = 2;
1314		}
1315
1316 		/* Append the ntoappend chars starting at ptoappend to
1317 		 * the new format.
1318 		 */
1319 		assert(ptoappend != NULL);
1320 		assert(ntoappend >= 0);
1321 		if (ntoappend == 0)
1322 			continue;
1323 		while (usednew + ntoappend > totalnew) {
1324 			size_t bigger = totalnew << 1;
1325 			if ((bigger >> 1) != totalnew) { /* overflow */
1326 				PyErr_NoMemory();
1327 				goto Done;
1328 			}
1329 			if (_PyString_Resize(&newfmt, bigger) < 0)
1330 				goto Done;
1331 			totalnew = bigger;
1332 			pnew = PyString_AsString(newfmt) + usednew;
1333 		}
1334		memcpy(pnew, ptoappend, ntoappend);
1335		pnew += ntoappend;
1336		usednew += ntoappend;
1337		assert(usednew <= totalnew);
1338	}  /* end while() */
1339
1340	if (_PyString_Resize(&newfmt, usednew) < 0)
1341		goto Done;
1342	{
1343		PyObject *time = PyImport_ImportModuleNoBlock("time");
1344		if (time == NULL)
1345			goto Done;
1346		result = PyObject_CallMethod(time, "strftime", "OO",
1347					     newfmt, timetuple);
1348		Py_DECREF(time);
1349    	}
1350 Done:
1351	Py_XDECREF(freplacement);
1352	Py_XDECREF(zreplacement);
1353	Py_XDECREF(Zreplacement);
1354	Py_XDECREF(newfmt);
1355    	return result;
1356}
1357
1358static char *
1359isoformat_date(PyDateTime_Date *dt, char buffer[], int bufflen)
1360{
1361	int x;
1362	x = PyOS_snprintf(buffer, bufflen,
1363			  "%04d-%02d-%02d",
1364			  GET_YEAR(dt), GET_MONTH(dt), GET_DAY(dt));
1365	return buffer + x;
1366}
1367
1368static void
1369isoformat_time(PyDateTime_DateTime *dt, char buffer[], int bufflen)
1370{
1371	int us = DATE_GET_MICROSECOND(dt);
1372
1373	PyOS_snprintf(buffer, bufflen,
1374		      "%02d:%02d:%02d",	/* 8 characters */
1375		      DATE_GET_HOUR(dt),
1376		      DATE_GET_MINUTE(dt),
1377		      DATE_GET_SECOND(dt));
1378	if (us)
1379		PyOS_snprintf(buffer + 8, bufflen - 8, ".%06d", us);
1380}
1381
1382/* ---------------------------------------------------------------------------
1383 * Wrap functions from the time module.  These aren't directly available
1384 * from C.  Perhaps they should be.
1385 */
1386
1387/* Call time.time() and return its result (a Python float). */
1388static PyObject *
1389time_time(void)
1390{
1391	PyObject *result = NULL;
1392	PyObject *time = PyImport_ImportModuleNoBlock("time");
1393
1394	if (time != NULL) {
1395		result = PyObject_CallMethod(time, "time", "()");
1396		Py_DECREF(time);
1397	}
1398	return result;
1399}
1400
1401/* Build a time.struct_time.  The weekday and day number are automatically
1402 * computed from the y,m,d args.
1403 */
1404static PyObject *
1405build_struct_time(int y, int m, int d, int hh, int mm, int ss, int dstflag)
1406{
1407	PyObject *time;
1408	PyObject *result = NULL;
1409
1410	time = PyImport_ImportModuleNoBlock("time");
1411	if (time != NULL) {
1412		result = PyObject_CallMethod(time, "struct_time",
1413					     "((iiiiiiiii))",
1414					     y, m, d,
1415					     hh, mm, ss,
1416				 	     weekday(y, m, d),
1417				 	     days_before_month(y, m) + d,
1418				 	     dstflag);
1419		Py_DECREF(time);
1420	}
1421	return result;
1422}
1423
1424/* ---------------------------------------------------------------------------
1425 * Miscellaneous helpers.
1426 */
1427
1428/* For obscure reasons, we need to use tp_richcompare instead of tp_compare.
1429 * The comparisons here all most naturally compute a cmp()-like result.
1430 * This little helper turns that into a bool result for rich comparisons.
1431 */
1432static PyObject *
1433diff_to_bool(int diff, int op)
1434{
1435	PyObject *result;
1436	int istrue;
1437
1438	switch (op) {
1439		case Py_EQ: istrue = diff == 0; break;
1440		case Py_NE: istrue = diff != 0; break;
1441		case Py_LE: istrue = diff <= 0; break;
1442		case Py_GE: istrue = diff >= 0; break;
1443		case Py_LT: istrue = diff < 0; break;
1444		case Py_GT: istrue = diff > 0; break;
1445		default:
1446			assert(! "op unknown");
1447			istrue = 0; /* To shut up compiler */
1448	}
1449	result = istrue ? Py_True : Py_False;
1450	Py_INCREF(result);
1451	return result;
1452}
1453
1454/* Raises a "can't compare" TypeError and returns NULL. */
1455static PyObject *
1456cmperror(PyObject *a, PyObject *b)
1457{
1458	PyErr_Format(PyExc_TypeError,
1459		     "can't compare %s to %s",
1460		     Py_TYPE(a)->tp_name, Py_TYPE(b)->tp_name);
1461	return NULL;
1462}
1463
1464/* ---------------------------------------------------------------------------
1465 * Cached Python objects; these are set by the module init function.
1466 */
1467
1468/* Conversion factors. */
1469static PyObject *us_per_us = NULL;	/* 1 */
1470static PyObject *us_per_ms = NULL;	/* 1000 */
1471static PyObject *us_per_second = NULL;	/* 1000000 */
1472static PyObject *us_per_minute = NULL;	/* 1e6 * 60 as Python int */
1473static PyObject *us_per_hour = NULL;	/* 1e6 * 3600 as Python long */
1474static PyObject *us_per_day = NULL;	/* 1e6 * 3600 * 24 as Python long */
1475static PyObject *us_per_week = NULL;	/* 1e6*3600*24*7 as Python long */
1476static PyObject *seconds_per_day = NULL; /* 3600*24 as Python int */
1477
1478/* ---------------------------------------------------------------------------
1479 * Class implementations.
1480 */
1481
1482/*
1483 * PyDateTime_Delta implementation.
1484 */
1485
1486/* Convert a timedelta to a number of us,
1487 * 	(24*3600*self.days + self.seconds)*1000000 + self.microseconds
1488 * as a Python int or long.
1489 * Doing mixed-radix arithmetic by hand instead is excruciating in C,
1490 * due to ubiquitous overflow possibilities.
1491 */
1492static PyObject *
1493delta_to_microseconds(PyDateTime_Delta *self)
1494{
1495	PyObject *x1 = NULL;
1496	PyObject *x2 = NULL;
1497	PyObject *x3 = NULL;
1498	PyObject *result = NULL;
1499
1500	x1 = PyInt_FromLong(GET_TD_DAYS(self));
1501	if (x1 == NULL)
1502		goto Done;
1503	x2 = PyNumber_Multiply(x1, seconds_per_day);	/* days in seconds */
1504	if (x2 == NULL)
1505		goto Done;
1506	Py_DECREF(x1);
1507	x1 = NULL;
1508
1509	/* x2 has days in seconds */
1510	x1 = PyInt_FromLong(GET_TD_SECONDS(self));	/* seconds */
1511	if (x1 == NULL)
1512		goto Done;
1513	x3 = PyNumber_Add(x1, x2);	/* days and seconds in seconds */
1514	if (x3 == NULL)
1515		goto Done;
1516	Py_DECREF(x1);
1517	Py_DECREF(x2);
1518	x1 = x2 = NULL;
1519
1520	/* x3 has days+seconds in seconds */
1521	x1 = PyNumber_Multiply(x3, us_per_second);	/* us */
1522	if (x1 == NULL)
1523		goto Done;
1524	Py_DECREF(x3);
1525	x3 = NULL;
1526
1527	/* x1 has days+seconds in us */
1528	x2 = PyInt_FromLong(GET_TD_MICROSECONDS(self));
1529	if (x2 == NULL)
1530		goto Done;
1531	result = PyNumber_Add(x1, x2);
1532
1533Done:
1534	Py_XDECREF(x1);
1535	Py_XDECREF(x2);
1536	Py_XDECREF(x3);
1537	return result;
1538}
1539
1540/* Convert a number of us (as a Python int or long) to a timedelta.
1541 */
1542static PyObject *
1543microseconds_to_delta_ex(PyObject *pyus, PyTypeObject *type)
1544{
1545	int us;
1546	int s;
1547	int d;
1548	long temp;
1549
1550	PyObject *tuple = NULL;
1551	PyObject *num = NULL;
1552	PyObject *result = NULL;
1553
1554	tuple = PyNumber_Divmod(pyus, us_per_second);
1555	if (tuple == NULL)
1556		goto Done;
1557
1558	num = PyTuple_GetItem(tuple, 1);	/* us */
1559	if (num == NULL)
1560		goto Done;
1561	temp = PyLong_AsLong(num);
1562	num = NULL;
1563	if (temp == -1 && PyErr_Occurred())
1564		goto Done;
1565	assert(0 <= temp && temp < 1000000);
1566	us = (int)temp;
1567	if (us < 0) {
1568		/* The divisor was positive, so this must be an error. */
1569		assert(PyErr_Occurred());
1570		goto Done;
1571	}
1572
1573	num = PyTuple_GetItem(tuple, 0);	/* leftover seconds */
1574	if (num == NULL)
1575		goto Done;
1576	Py_INCREF(num);
1577	Py_DECREF(tuple);
1578
1579	tuple = PyNumber_Divmod(num, seconds_per_day);
1580	if (tuple == NULL)
1581		goto Done;
1582	Py_DECREF(num);
1583
1584	num = PyTuple_GetItem(tuple, 1); 	/* seconds */
1585	if (num == NULL)
1586		goto Done;
1587	temp = PyLong_AsLong(num);
1588	num = NULL;
1589	if (temp == -1 && PyErr_Occurred())
1590		goto Done;
1591	assert(0 <= temp && temp < 24*3600);
1592	s = (int)temp;
1593
1594	if (s < 0) {
1595		/* The divisor was positive, so this must be an error. */
1596		assert(PyErr_Occurred());
1597		goto Done;
1598	}
1599
1600	num = PyTuple_GetItem(tuple, 0);	/* leftover days */
1601	if (num == NULL)
1602		goto Done;
1603	Py_INCREF(num);
1604	temp = PyLong_AsLong(num);
1605	if (temp == -1 && PyErr_Occurred())
1606		goto Done;
1607	d = (int)temp;
1608	if ((long)d != temp) {
1609		PyErr_SetString(PyExc_OverflowError, "normalized days too "
1610				"large to fit in a C int");
1611		goto Done;
1612	}
1613	result = new_delta_ex(d, s, us, 0, type);
1614
1615Done:
1616	Py_XDECREF(tuple);
1617	Py_XDECREF(num);
1618	return result;
1619}
1620
1621#define microseconds_to_delta(pymicros)	\
1622	microseconds_to_delta_ex(pymicros, &PyDateTime_DeltaType)
1623
1624static PyObject *
1625multiply_int_timedelta(PyObject *intobj, PyDateTime_Delta *delta)
1626{
1627	PyObject *pyus_in;
1628	PyObject *pyus_out;
1629	PyObject *result;
1630
1631	pyus_in = delta_to_microseconds(delta);
1632	if (pyus_in == NULL)
1633		return NULL;
1634
1635	pyus_out = PyNumber_Multiply(pyus_in, intobj);
1636	Py_DECREF(pyus_in);
1637	if (pyus_out == NULL)
1638		return NULL;
1639
1640	result = microseconds_to_delta(pyus_out);
1641	Py_DECREF(pyus_out);
1642	return result;
1643}
1644
1645static PyObject *
1646divide_timedelta_int(PyDateTime_Delta *delta, PyObject *intobj)
1647{
1648	PyObject *pyus_in;
1649	PyObject *pyus_out;
1650	PyObject *result;
1651
1652	pyus_in = delta_to_microseconds(delta);
1653	if (pyus_in == NULL)
1654		return NULL;
1655
1656	pyus_out = PyNumber_FloorDivide(pyus_in, intobj);
1657	Py_DECREF(pyus_in);
1658	if (pyus_out == NULL)
1659		return NULL;
1660
1661	result = microseconds_to_delta(pyus_out);
1662	Py_DECREF(pyus_out);
1663	return result;
1664}
1665
1666static PyObject *
1667delta_add(PyObject *left, PyObject *right)
1668{
1669	PyObject *result = Py_NotImplemented;
1670
1671	if (PyDelta_Check(left) && PyDelta_Check(right)) {
1672		/* delta + delta */
1673		/* The C-level additions can't overflow because of the
1674		 * invariant bounds.
1675		 */
1676		int days = GET_TD_DAYS(left) + GET_TD_DAYS(right);
1677		int seconds = GET_TD_SECONDS(left) + GET_TD_SECONDS(right);
1678		int microseconds = GET_TD_MICROSECONDS(left) +
1679				   GET_TD_MICROSECONDS(right);
1680		result = new_delta(days, seconds, microseconds, 1);
1681	}
1682
1683	if (result == Py_NotImplemented)
1684		Py_INCREF(result);
1685	return result;
1686}
1687
1688static PyObject *
1689delta_negative(PyDateTime_Delta *self)
1690{
1691	return new_delta(-GET_TD_DAYS(self),
1692			 -GET_TD_SECONDS(self),
1693			 -GET_TD_MICROSECONDS(self),
1694			 1);
1695}
1696
1697static PyObject *
1698delta_positive(PyDateTime_Delta *self)
1699{
1700	/* Could optimize this (by returning self) if this isn't a
1701	 * subclass -- but who uses unary + ?  Approximately nobody.
1702	 */
1703	return new_delta(GET_TD_DAYS(self),
1704			 GET_TD_SECONDS(self),
1705			 GET_TD_MICROSECONDS(self),
1706			 0);
1707}
1708
1709static PyObject *
1710delta_abs(PyDateTime_Delta *self)
1711{
1712	PyObject *result;
1713
1714	assert(GET_TD_MICROSECONDS(self) >= 0);
1715	assert(GET_TD_SECONDS(self) >= 0);
1716
1717	if (GET_TD_DAYS(self) < 0)
1718		result = delta_negative(self);
1719	else
1720		result = delta_positive(self);
1721
1722	return result;
1723}
1724
1725static PyObject *
1726delta_subtract(PyObject *left, PyObject *right)
1727{
1728	PyObject *result = Py_NotImplemented;
1729
1730	if (PyDelta_Check(left) && PyDelta_Check(right)) {
1731	    	/* delta - delta */
1732	    	PyObject *minus_right = PyNumber_Negative(right);
1733	    	if (minus_right) {
1734	    		result = delta_add(left, minus_right);
1735	    		Py_DECREF(minus_right);
1736	    	}
1737	    	else
1738	    		result = NULL;
1739	}
1740
1741	if (result == Py_NotImplemented)
1742		Py_INCREF(result);
1743	return result;
1744}
1745
1746/* This is more natural as a tp_compare, but doesn't work then:  for whatever
1747 * reason, Python's try_3way_compare ignores tp_compare unless
1748 * PyInstance_Check returns true, but these aren't old-style classes.
1749 */
1750static PyObject *
1751delta_richcompare(PyDateTime_Delta *self, PyObject *other, int op)
1752{
1753	int diff = 42;	/* nonsense */
1754
1755	if (PyDelta_Check(other)) {
1756		diff = GET_TD_DAYS(self) - GET_TD_DAYS(other);
1757		if (diff == 0)

Large files files are truncated, but you can click here to view the full file