(__mktime_internal): Adopt the traditional (and
[gnulib.git] / lib / mktime.c
1 /* mktime: convert a `struct tm' to a time_t value
2    Copyright (C) 1993-1998, 1999 Free Software Foundation, Inc.
3    Contributed by Paul Eggert (eggert@twinsun.com).
4
5    NOTE: The canonical source of this file is maintained with the GNU C Library.
6    Bugs can be reported to bug-glibc@prep.ai.mit.edu.
7
8    This program is free software; you can redistribute it and/or modify it
9    under the terms of the GNU General Public License as published by the
10    Free Software Foundation; either version 2, or (at your option) any
11    later version.
12
13    This program is distributed in the hope that it will be useful,
14    but WITHOUT ANY WARRANTY; without even the implied warranty of
15    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16    GNU General Public License for more details.
17
18    You should have received a copy of the GNU General Public License
19    along with this program; if not, write to the Free Software
20    Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
21    USA.  */
22
23 /* Define this to have a standalone program to test this implementation of
24    mktime.  */
25 /* #define DEBUG 1 */
26
27 #ifdef HAVE_CONFIG_H
28 # include <config.h>
29 #endif
30
31 #ifdef _LIBC
32 # define HAVE_LIMITS_H 1
33 # define STDC_HEADERS 1
34 #endif
35
36 /* Assume that leap seconds are possible, unless told otherwise.
37    If the host has a `zic' command with a `-L leapsecondfilename' option,
38    then it supports leap seconds; otherwise it probably doesn't.  */
39 #ifndef LEAP_SECONDS_POSSIBLE
40 # define LEAP_SECONDS_POSSIBLE 1
41 #endif
42
43 #include <sys/types.h>          /* Some systems define `time_t' here.  */
44 #include <time.h>
45
46 #if HAVE_LIMITS_H
47 # include <limits.h>
48 #endif
49
50 #if DEBUG
51 # include <stdio.h>
52 # if STDC_HEADERS
53 #  include <stdlib.h>
54 # endif
55 /* Make it work even if the system's libc has its own mktime routine.  */
56 # define mktime my_mktime
57 #endif /* DEBUG */
58
59 #ifndef __P
60 # if defined __GNUC__ || (defined __STDC__ && __STDC__)
61 #  define __P(args) args
62 # else
63 #  define __P(args) ()
64 # endif  /* GCC.  */
65 #endif  /* Not __P.  */
66
67 #ifndef CHAR_BIT
68 # define CHAR_BIT 8
69 #endif
70
71 /* The extra casts work around common compiler bugs.  */
72 #define TYPE_SIGNED(t) (! ((t) 0 < (t) -1))
73 /* The outer cast is needed to work around a bug in Cray C 5.0.3.0.
74    It is necessary at least when t == time_t.  */
75 #define TYPE_MINIMUM(t) ((t) (TYPE_SIGNED (t) \
76                               ? ~ (t) 0 << (sizeof (t) * CHAR_BIT - 1) : (t) 0))
77 #define TYPE_MAXIMUM(t) ((t) (~ (t) 0 - TYPE_MINIMUM (t)))
78
79 #ifndef INT_MIN
80 # define INT_MIN TYPE_MINIMUM (int)
81 #endif
82 #ifndef INT_MAX
83 # define INT_MAX TYPE_MAXIMUM (int)
84 #endif
85
86 #ifndef TIME_T_MIN
87 # define TIME_T_MIN TYPE_MINIMUM (time_t)
88 #endif
89 #ifndef TIME_T_MAX
90 # define TIME_T_MAX TYPE_MAXIMUM (time_t)
91 #endif
92
93 #define TM_YEAR_BASE 1900
94 #define EPOCH_YEAR 1970
95
96 #ifndef __isleap
97 /* Nonzero if YEAR is a leap year (every 4 years,
98    except every 100th isn't, and every 400th is).  */
99 # define __isleap(year) \
100   ((year) % 4 == 0 && ((year) % 100 != 0 || (year) % 400 == 0))
101 #endif
102
103 /* How many days come before each month (0-12).  */
104 const unsigned short int __mon_yday[2][13] =
105   {
106     /* Normal years.  */
107     { 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334, 365 },
108     /* Leap years.  */
109     { 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335, 366 }
110   };
111
112 static struct tm *ranged_convert __P ((struct tm *(*) __P ((const time_t *,
113                                                             struct tm *)),
114                                        time_t *, struct tm *));
115 static time_t ydhms_tm_diff __P ((int, int, int, int, int, const struct tm *));
116 time_t __mktime_internal __P ((struct tm *,
117                                struct tm *(*) (const time_t *, struct tm *),
118                                time_t *));
119
120
121 #ifdef _LIBC
122 # define my_mktime_localtime_r __localtime_r
123 #else
124 /* If we're a mktime substitute in a GNU program, then prefer
125    localtime to localtime_r, since many localtime_r implementations
126    are buggy.  */
127 static struct tm *my_mktime_localtime_r __P ((const time_t *, struct tm *));
128 static struct tm *
129 my_mktime_localtime_r (const time_t *t, struct tm *tp)
130 {
131   struct tm *l = localtime (t);
132   if (! l)
133     return 0;
134   *tp = *l;
135   return tp;
136 }
137 #endif /* ! _LIBC */
138
139
140 /* Yield the difference between (YEAR-YDAY HOUR:MIN:SEC) and (*TP),
141    measured in seconds, ignoring leap seconds.
142    YEAR uses the same numbering as TM->tm_year.
143    All values are in range, except possibly YEAR.
144    If TP is null, return a nonzero value.
145    If overflow occurs, yield the low order bits of the correct answer.  */
146 static time_t
147 ydhms_tm_diff (int year, int yday, int hour, int min, int sec,
148                const struct tm *tp)
149 {
150   if (!tp)
151     return 1;
152   else
153     {
154       /* Compute intervening leap days correctly even if year is negative.
155          Take care to avoid int overflow.  time_t overflow is OK, since
156          only the low order bits of the correct time_t answer are needed.
157          Don't convert to time_t until after all divisions are done, since
158          time_t might be unsigned.  */
159       int a4 = (year >> 2) + (TM_YEAR_BASE >> 2) - ! (year & 3);
160       int b4 = (tp->tm_year >> 2) + (TM_YEAR_BASE >> 2) - ! (tp->tm_year & 3);
161       int a100 = a4 / 25 - (a4 % 25 < 0);
162       int b100 = b4 / 25 - (b4 % 25 < 0);
163       int a400 = a100 >> 2;
164       int b400 = b100 >> 2;
165       int intervening_leap_days = (a4 - b4) - (a100 - b100) + (a400 - b400);
166       time_t years = year - (time_t) tp->tm_year;
167       time_t days = (365 * years + intervening_leap_days
168                      + (yday - tp->tm_yday));
169       return (60 * (60 * (24 * days + (hour - tp->tm_hour))
170                     + (min - tp->tm_min))
171               + (sec - tp->tm_sec));
172     }
173 }
174
175
176 static time_t localtime_offset;
177
178 /* Convert *TP to a time_t value.  */
179 time_t
180 mktime (struct tm *tp)
181 {
182 #ifdef _LIBC
183   /* POSIX.1 8.1.1 requires that whenever mktime() is called, the
184      time zone names contained in the external variable `tzname' shall
185      be set as if the tzset() function had been called.  */
186   __tzset ();
187 #endif
188
189   return __mktime_internal (tp, my_mktime_localtime_r, &localtime_offset);
190 }
191
192 /* Use CONVERT to convert *T to a broken down time in *TP.
193    If *T is out of range for conversion, adjust it so that
194    it is the nearest in-range value and then convert that.  */
195 static struct tm *
196 ranged_convert (struct tm *(*convert) (const time_t *, struct tm *),
197                 time_t *t, struct tm *tp)
198 {
199   struct tm *r;
200
201   if (! (r = (*convert) (t, tp)) && *t)
202     {
203       time_t bad = *t;
204       time_t ok = 0;
205       struct tm tm;
206
207       /* BAD is a known unconvertible time_t, and OK is a known good one.
208          Use binary search to narrow the range between BAD and OK until
209          they differ by 1.  */
210       while (bad != ok + (bad < 0 ? -1 : 1))
211         {
212           time_t mid = *t = (bad < 0
213                              ? bad + ((ok - bad) >> 1)
214                              : ok + ((bad - ok) >> 1));
215           if ((r = (*convert) (t, tp)))
216             {
217               tm = *r;
218               ok = mid;
219             }
220           else
221             bad = mid;
222         }
223
224       if (!r && ok)
225         {
226           /* The last conversion attempt failed;
227              revert to the most recent successful attempt.  */
228           *t = ok;
229           *tp = tm;
230           r = tp;
231         }
232     }
233
234   return r;
235 }
236
237
238 /* Convert *TP to a time_t value, inverting
239    the monotonic and mostly-unit-linear conversion function CONVERT.
240    Use *OFFSET to keep track of a guess at the offset of the result,
241    compared to what the result would be for UTC without leap seconds.
242    If *OFFSET's guess is correct, only one CONVERT call is needed.  */
243 time_t
244 __mktime_internal (struct tm *tp,
245                    struct tm *(*convert) (const time_t *, struct tm *),
246                    time_t *offset)
247 {
248   time_t t, dt, t0, t1, t2;
249   struct tm tm;
250
251   /* The maximum number of probes (calls to CONVERT) should be enough
252      to handle any combinations of time zone rule changes, solar time,
253      leap seconds, and oscillations around a spring-forward gap.
254      POSIX.1 prohibits leap seconds, but some hosts have them anyway.  */
255   int remaining_probes = 6;
256
257   /* Time requested.  Copy it in case CONVERT modifies *TP; this can
258      occur if TP is localtime's returned value and CONVERT is localtime.  */
259   int sec = tp->tm_sec;
260   int min = tp->tm_min;
261   int hour = tp->tm_hour;
262   int mday = tp->tm_mday;
263   int mon = tp->tm_mon;
264   int year_requested = tp->tm_year;
265   int isdst = tp->tm_isdst;
266
267   /* Ensure that mon is in range, and set year accordingly.  */
268   int mon_remainder = mon % 12;
269   int negative_mon_remainder = mon_remainder < 0;
270   int mon_years = mon / 12 - negative_mon_remainder;
271   int year = year_requested + mon_years;
272
273   /* The other values need not be in range:
274      the remaining code handles minor overflows correctly,
275      assuming int and time_t arithmetic wraps around.
276      Major overflows are caught at the end.  */
277
278   /* Calculate day of year from year, month, and day of month.
279      The result need not be in range.  */
280   int yday = ((__mon_yday[__isleap (year + TM_YEAR_BASE)]
281                [mon_remainder + 12 * negative_mon_remainder])
282               + mday - 1);
283
284   int sec_requested = sec;
285 #if LEAP_SECONDS_POSSIBLE
286   /* Handle out-of-range seconds specially,
287      since ydhms_tm_diff assumes every minute has 60 seconds.  */
288   if (sec < 0)
289     sec = 0;
290   if (59 < sec)
291     sec = 59;
292 #endif
293
294   /* Invert CONVERT by probing.  First assume the same offset as last time.
295      Then repeatedly use the error to improve the guess.  */
296
297   tm.tm_year = EPOCH_YEAR - TM_YEAR_BASE;
298   tm.tm_yday = tm.tm_hour = tm.tm_min = tm.tm_sec = 0;
299   t0 = ydhms_tm_diff (year, yday, hour, min, sec, &tm);
300
301   for (t = t1 = t2 = t0 + *offset;
302        (dt = ydhms_tm_diff (year, yday, hour, min, sec,
303                             ranged_convert (convert, &t, &tm)));
304        t1 = t2, t2 = t, t += dt)
305     if (t == t1 && t != t2
306         && (isdst < 0 || tm.tm_isdst < 0
307             || (isdst != 0) != (tm.tm_isdst != 0)))
308       /* We can't possibly find a match, as we are oscillating
309          between two values.  The requested time probably falls
310          within a spring-forward gap of size DT.  Follow the common
311          practice in this case, which is to return a time that is DT
312          away from the requested time, preferring a time whose
313          tm_isdst differs from the requested value.  In practice,
314          this is more useful than returning -1.  */
315       break;
316     else if (--remaining_probes == 0)
317       return -1;
318
319   /* If we have a match, check whether tm.tm_isdst has the requested
320      value, if any.  */
321   if (dt == 0 && isdst != tm.tm_isdst && 0 <= isdst && 0 <= tm.tm_isdst)
322     {
323       /* tm.tm_isdst has the wrong value.  Look for a neighboring
324          time with the right value, and use its UTC offset.
325          Heuristic: probe the previous three calendar quarters (approximately),
326          looking for the desired isdst.  This isn't perfect,
327          but it's good enough in practice.  */
328       int quarter = 7889238; /* seconds per average 1/4 Gregorian year */
329       int i;
330
331       /* If we're too close to the time_t limit, look in future quarters.  */
332       if (t < TIME_T_MIN + 3 * quarter)
333         quarter = -quarter;
334
335       for (i = 1; i <= 3; i++)
336         {
337           time_t ot = t - i * quarter;
338           struct tm otm;
339           ranged_convert (convert, &ot, &otm);
340           if (otm.tm_isdst == isdst)
341             {
342               /* We found the desired tm_isdst.
343                  Extrapolate back to the desired time.  */
344               t = ot + ydhms_tm_diff (year, yday, hour, min, sec, &otm);
345               ranged_convert (convert, &t, &tm);
346               break;
347             }
348         }
349     }
350
351   *offset = t - t0;
352
353 #if LEAP_SECONDS_POSSIBLE
354   if (sec_requested != tm.tm_sec)
355     {
356       /* Adjust time to reflect the tm_sec requested, not the normalized value.
357          Also, repair any damage from a false match due to a leap second.  */
358       t += sec_requested - sec + (sec == 0 && tm.tm_sec == 60);
359       if (! (*convert) (&t, &tm))
360         return -1;
361     }
362 #endif
363
364   if (TIME_T_MAX / INT_MAX / 366 / 24 / 60 / 60 < 3)
365     {
366       /* time_t isn't large enough to rule out overflows in ydhms_tm_diff,
367          so check for major overflows.  A gross check suffices,
368          since if t has overflowed, it is off by a multiple of
369          TIME_T_MAX - TIME_T_MIN + 1.  So ignore any component of
370          the difference that is bounded by a small value.  */
371
372       double dyear = (double) year_requested + mon_years - tm.tm_year;
373       double dday = 366 * dyear + mday;
374       double dsec = 60 * (60 * (24 * dday + hour) + min) + sec_requested;
375
376       /* On Irix4.0.5 cc, dividing TIME_T_MIN by 3 does not produce
377          correct results, ie., it erroneously gives a positive value
378          of 715827882.  Setting a variable first then doing math on it
379          seems to work.  (ghazi@caip.rutgers.edu) */
380
381       const time_t time_t_max = TIME_T_MAX;
382       const time_t time_t_min = TIME_T_MIN;
383
384       if (time_t_max / 3 - time_t_min / 3 < (dsec < 0 ? - dsec : dsec))
385         return -1;
386     }
387
388   *tp = tm;
389   return t;
390 }
391
392 #ifdef weak_alias
393 weak_alias (mktime, timelocal)
394 #endif
395 \f
396 #if DEBUG
397
398 static int
399 not_equal_tm (a, b)
400      struct tm *a;
401      struct tm *b;
402 {
403   return ((a->tm_sec ^ b->tm_sec)
404           | (a->tm_min ^ b->tm_min)
405           | (a->tm_hour ^ b->tm_hour)
406           | (a->tm_mday ^ b->tm_mday)
407           | (a->tm_mon ^ b->tm_mon)
408           | (a->tm_year ^ b->tm_year)
409           | (a->tm_mday ^ b->tm_mday)
410           | (a->tm_yday ^ b->tm_yday)
411           | (a->tm_isdst ^ b->tm_isdst));
412 }
413
414 static void
415 print_tm (tp)
416      struct tm *tp;
417 {
418   if (tp)
419     printf ("%04d-%02d-%02d %02d:%02d:%02d yday %03d wday %d isdst %d",
420             tp->tm_year + TM_YEAR_BASE, tp->tm_mon + 1, tp->tm_mday,
421             tp->tm_hour, tp->tm_min, tp->tm_sec,
422             tp->tm_yday, tp->tm_wday, tp->tm_isdst);
423   else
424     printf ("0");
425 }
426
427 static int
428 check_result (tk, tmk, tl, lt)
429      time_t tk;
430      struct tm tmk;
431      time_t tl;
432      struct tm *lt;
433 {
434   if (tk != tl || !lt || not_equal_tm (&tmk, lt))
435     {
436       printf ("mktime (");
437       print_tm (&tmk);
438       printf (")\nyields (");
439       print_tm (lt);
440       printf (") == %ld, should be %ld\n", (long) tl, (long) tk);
441       return 1;
442     }
443
444   return 0;
445 }
446
447 int
448 main (argc, argv)
449      int argc;
450      char **argv;
451 {
452   int status = 0;
453   struct tm tm, tmk, tml;
454   struct tm *lt;
455   time_t tk, tl;
456   char trailer;
457
458   if ((argc == 3 || argc == 4)
459       && (sscanf (argv[1], "%d-%d-%d%c",
460                   &tm.tm_year, &tm.tm_mon, &tm.tm_mday, &trailer)
461           == 3)
462       && (sscanf (argv[2], "%d:%d:%d%c",
463                   &tm.tm_hour, &tm.tm_min, &tm.tm_sec, &trailer)
464           == 3))
465     {
466       tm.tm_year -= TM_YEAR_BASE;
467       tm.tm_mon--;
468       tm.tm_isdst = argc == 3 ? -1 : atoi (argv[3]);
469       tmk = tm;
470       tl = mktime (&tmk);
471       lt = localtime (&tl);
472       if (lt)
473         {
474           tml = *lt;
475           lt = &tml;
476         }
477       printf ("mktime returns %ld == ", (long) tl);
478       print_tm (&tmk);
479       printf ("\n");
480       status = check_result (tl, tmk, tl, lt);
481     }
482   else if (argc == 4 || (argc == 5 && strcmp (argv[4], "-") == 0))
483     {
484       time_t from = atol (argv[1]);
485       time_t by = atol (argv[2]);
486       time_t to = atol (argv[3]);
487
488       if (argc == 4)
489         for (tl = from; tl <= to; tl += by)
490           {
491             lt = localtime (&tl);
492             if (lt)
493               {
494                 tmk = tml = *lt;
495                 tk = mktime (&tmk);
496                 status |= check_result (tk, tmk, tl, tml);
497               }
498             else
499               {
500                 printf ("localtime (%ld) yields 0\n", (long) tl);
501                 status = 1;
502               }
503           }
504       else
505         for (tl = from; tl <= to; tl += by)
506           {
507             /* Null benchmark.  */
508             lt = localtime (&tl);
509             if (lt)
510               {
511                 tmk = tml = *lt;
512                 tk = tl;
513                 status |= check_result (tk, tmk, tl, tml);
514               }
515             else
516               {
517                 printf ("localtime (%ld) yields 0\n", (long) tl);
518                 status = 1;
519               }
520           }
521     }
522   else
523     printf ("Usage:\
524 \t%s YYYY-MM-DD HH:MM:SS [ISDST] # Test given time.\n\
525 \t%s FROM BY TO # Test values FROM, FROM+BY, ..., TO.\n\
526 \t%s FROM BY TO - # Do not test those values (for benchmark).\n",
527             argv[0], argv[0], argv[0]);
528
529   return status;
530 }
531
532 #endif /* DEBUG */
533 \f
534 /*
535 Local Variables:
536 compile-command: "gcc -DDEBUG -DHAVE_LIMITS_H -DSTDC_HEADERS -Wall -W -O -g mktime.c -o mktime"
537 End:
538 */