1 /* <!-- copyright */
2 /*
3 * libmetalink
4 *
5 * Copyright (c) 2012 Tatsuhiro Tsujikawa
6 *
7 * Permission is hereby granted, free of charge, to any person obtaining a copy
8 * of this software and associated documentation files (the "Software"), to deal
9 * in the Software without restriction, including without limitation the rights
10 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
11 * copies of the Software, and to permit persons to whom the Software is
12 * furnished to do so, subject to the following conditions:
13 *
14 * The above copyright notice and this permission notice shall be included in
15 * all copies or substantial portions of the Software.
16 *
17 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
18 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
19 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
20 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
21 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
22 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
23 * THE SOFTWARE.
24 */
25 /* copyright --> */
26 #include "timegm.h"
27
28 #ifndef HAVE_TIMEGM
29
30 #include <stdint.h>
31
32 #ifndef INT32_MIN
33 #define INT32_MIN ((int32_t)(1u << 31))
34 #endif /* INT32_MIN */
35
36 /* Counter the number of leap year in the range [0, y). The |y| is the
37 year, including century (e.g., 2012) */
count_leap_year(int y)38 static int count_leap_year(int y)
39 {
40 y -= 1;
41 return y/4-y/100+y/400;
42 }
43
44 /* Returns nonzero if the |y| is the leap year. The |y| is the year,
45 including century (e.g., 2012) */
is_leap_year(int y)46 static int is_leap_year(int y)
47 {
48 return y%4 == 0 && (y%100 != 0 || y%400 == 0);
49 }
50
51 /* The number of days before ith month begins */
52 static int daysum[] = {
53 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334
54 };
55
56 /* Based on the algorithm of Python 2.7 calendar.timegm. */
timegm(struct tm * tm)57 time_t timegm(struct tm *tm)
58 {
59 int days;
60 int num_leap_year;
61 int64_t t;
62 if(tm->tm_mon > 11) {
63 return -1;
64 }
65 num_leap_year = count_leap_year(tm->tm_year + 1900) - count_leap_year(1970);
66 days = (tm->tm_year - 70) * 365 +
67 num_leap_year + daysum[tm->tm_mon] + tm->tm_mday-1;
68 if(tm->tm_mon >= 2 && is_leap_year(tm->tm_year + 1900)) {
69 ++days;
70 }
71 t = ((int64_t)days * 24 + tm->tm_hour) * 3600 + tm->tm_min * 60 + tm->tm_sec;
72 if(sizeof(time_t) == 4) {
73 if(t < INT32_MIN || t > INT32_MAX) {
74 return -1;
75 }
76 }
77 return t;
78 }
79
80 #endif /* !HAVE_TIMEGM */
81