| 590 | __slots__ = '_days', '_seconds', '_microseconds', '_hashcode' |
| 591 | |
| 592 | def __new__(cls, days=0, seconds=0, microseconds=0, |
| 593 | milliseconds=0, minutes=0, hours=0, weeks=0): |
| 594 | # Doing this efficiently and accurately in C is going to be difficult |
| 595 | # and error-prone, due to ubiquitous overflow possibilities, and that |
| 596 | # C double doesn't have enough bits of precision to represent |
| 597 | # microseconds over 10K years faithfully. The code here tries to make |
| 598 | # explicit where go-fast assumptions can be relied on, in order to |
| 599 | # guide the C implementation; it's way more convoluted than speed- |
| 600 | # ignoring auto-overflow-to-long idiomatic Python could be. |
| 601 | |
| 602 | # XXX Check that all inputs are ints or floats. |
| 603 | |
| 604 | # Final values, all integer. |
| 605 | # s and us fit in 32-bit signed ints; d isn't bounded. |
| 606 | d = s = us = 0 |
| 607 | |
| 608 | # Normalize everything to days, seconds, microseconds. |
| 609 | days += weeks*7 |
| 610 | seconds += minutes*60 + hours*3600 |
| 611 | microseconds += milliseconds*1000 |
| 612 | |
| 613 | # Get rid of all fractions, and normalize s and us. |
| 614 | # Take a deep breath <wink>. |
| 615 | if isinstance(days, float): |
| 616 | dayfrac, days = _math.modf(days) |
| 617 | daysecondsfrac, daysecondswhole = _math.modf(dayfrac * (24.*3600.)) |
| 618 | assert daysecondswhole == int(daysecondswhole) # can't overflow |
| 619 | s = int(daysecondswhole) |
| 620 | assert days == int(days) |
| 621 | d = int(days) |
| 622 | else: |
| 623 | daysecondsfrac = 0.0 |
| 624 | d = days |
| 625 | assert isinstance(daysecondsfrac, float) |
| 626 | assert abs(daysecondsfrac) <= 1.0 |
| 627 | assert isinstance(d, int) |
| 628 | assert abs(s) <= 24 * 3600 |
| 629 | # days isn't referenced again before redefinition |
| 630 | |
| 631 | if isinstance(seconds, float): |
| 632 | secondsfrac, seconds = _math.modf(seconds) |
| 633 | assert seconds == int(seconds) |
| 634 | seconds = int(seconds) |
| 635 | secondsfrac += daysecondsfrac |
| 636 | assert abs(secondsfrac) <= 2.0 |
| 637 | else: |
| 638 | secondsfrac = daysecondsfrac |
| 639 | # daysecondsfrac isn't referenced again |
| 640 | assert isinstance(secondsfrac, float) |
| 641 | assert abs(secondsfrac) <= 2.0 |
| 642 | |
| 643 | assert isinstance(seconds, int) |
| 644 | days, seconds = divmod(seconds, 24*3600) |
| 645 | d += days |
| 646 | s += int(seconds) # can't overflow |
| 647 | assert isinstance(s, int) |
| 648 | assert abs(s) <= 2 * 24 * 3600 |
| 649 | # seconds isn't referenced again before redefinition |