/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

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