1#include "time_impl.h"
2#include <limits.h>
3
4/* 2000-03-01 (mod 400 year, immediately after feb29 */
5#define LEAPOCH (946684800LL + 86400 * (31 + 29))
6
7#define DAYS_PER_400Y (365 * 400 + 97)
8#define DAYS_PER_100Y (365 * 100 + 24)
9#define DAYS_PER_4Y (365 * 4 + 1)
10
11int __secs_to_tm(long long t, struct tm* tm) {
12    long long days, secs, years;
13    int remdays, remsecs, remyears;
14    int qc_cycles, c_cycles, q_cycles;
15    int months;
16    int wday, yday, leap;
17    static const char days_in_month[] = {31, 30, 31, 30, 31, 31, 30, 31, 30, 31, 31, 29};
18
19    /* Reject time_t values whose year would overflow int */
20    if (t < INT_MIN * 31622400LL || t > INT_MAX * 31622400LL)
21        return -1;
22
23    secs = t - LEAPOCH;
24    days = secs / 86400;
25    remsecs = secs % 86400;
26    if (remsecs < 0) {
27        remsecs += 86400;
28        days--;
29    }
30
31    wday = (3 + days) % 7;
32    if (wday < 0)
33        wday += 7;
34
35    qc_cycles = days / DAYS_PER_400Y;
36    remdays = days % DAYS_PER_400Y;
37    if (remdays < 0) {
38        remdays += DAYS_PER_400Y;
39        qc_cycles--;
40    }
41
42    c_cycles = remdays / DAYS_PER_100Y;
43    if (c_cycles == 4)
44        c_cycles--;
45    remdays -= c_cycles * DAYS_PER_100Y;
46
47    q_cycles = remdays / DAYS_PER_4Y;
48    if (q_cycles == 25)
49        q_cycles--;
50    remdays -= q_cycles * DAYS_PER_4Y;
51
52    remyears = remdays / 365;
53    if (remyears == 4)
54        remyears--;
55    remdays -= remyears * 365;
56
57    leap = !remyears && (q_cycles || !c_cycles);
58    yday = remdays + 31 + 28 + leap;
59    if (yday >= 365 + leap)
60        yday -= 365 + leap;
61
62    years = remyears + 4 * q_cycles + 100 * c_cycles + 400LL * qc_cycles;
63
64    for (months = 0; days_in_month[months] <= remdays; months++)
65        remdays -= days_in_month[months];
66
67    if (years + 100 > INT_MAX || years + 100 < INT_MIN)
68        return -1;
69
70    tm->tm_year = years + 100;
71    tm->tm_mon = months + 2;
72    if (tm->tm_mon >= 12) {
73        tm->tm_mon -= 12;
74        tm->tm_year++;
75    }
76    tm->tm_mday = remdays + 1;
77    tm->tm_wday = wday;
78    tm->tm_yday = yday;
79
80    tm->tm_hour = remsecs / 3600;
81    tm->tm_min = remsecs / 60 % 60;
82    tm->tm_sec = remsecs % 60;
83
84    return 0;
85}
86