3fe24b67d6373b18eac78f714c71956644d1dd4b
[dragonfly.git] / lib / libc / stdtime / strftime.c
1 /*
2  * @(#)strftime.c       8.3
3  * $NetBSD: strftime.c,v 1.19 2009/01/11 02:46:30 christos Exp $
4  * $DragonFly: src/lib/libc/stdtime/strftime.c,v 1.7 2008/10/19 20:15:58 swildner Exp $
5  */
6
7 /*
8 ** Based on the UCB version with the ID appearing below.
9 ** This is ANSIish only when "multibyte character == plain character".
10 */
11
12 /*
13 ** We don't use these extensions in strftime operation even when
14 ** supported by the local tzcode configuration.  A strictly
15 ** conforming C application may leave them in undefined state.
16 */
17
18 #ifdef _LIBC
19 #undef TM_ZONE
20 #undef TM_GMTOFF
21 #endif
22
23 /*
24 ** Copyright (c) 1989, 1993
25 **      The Regents of the University of California.  All rights reserved.
26 **
27 ** Redistribution and use in source and binary forms, with or without
28 ** modification, are permitted provided that the following conditions
29 ** are met:
30 ** 1. Redistributions of source code must retain the above copyright
31 **    notice, this list of conditions and the following disclaimer.
32 ** 2. Redistributions in binary form must reproduce the above copyright
33 **    notice, this list of conditions and the following disclaimer in the
34 **    documentation and/or other materials provided with the distribution.
35 ** 3. All advertising materials mentioning features or use of this software
36 **    must display the following acknowledgement:
37 **      This product includes software developed by the University of
38 **      California, Berkeley and its contributors.
39 ** 4. Neither the name of the University nor the names of its contributors
40 **    may be used to endorse or promote products derived from this software
41 **    without specific prior written permission.
42 **
43 ** THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND
44 ** ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
45 ** IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
46 ** ARE DISCLAIMED.  IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE
47 ** FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
48 ** DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
49 ** OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
50 ** HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
51 ** LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
52 ** OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
53 ** SUCH DAMAGE.
54 */
55
56 #include <sys/localedef.h>
57 #include <fcntl.h>
58 #include <locale.h>
59 #include <time.h>
60
61 #include "private.h"
62 #include "tzfile.h"
63
64 #define Locale  _CurrentTimeLocale
65
66 static char *   _add(const char *, char *, const char *);
67 static char *   _conv(int, const char *, char *, const char *);
68 static char *   _fmt(const char *, const struct tm *, char *,
69                      const char *, int *);
70 static char *   _yconv(int, int, int, int, char *, const char *);
71
72 #define NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU
73
74 #ifndef YEAR_2000_NAME
75 #define YEAR_2000_NAME  "CHECK_STRFTIME_FORMATS_FOR_TWO_DIGIT_YEARS"
76 #endif /* !defined YEAR_2000_NAME */
77
78 #define IN_NONE 0
79 #define IN_SOME 1
80 #define IN_THIS 2
81 #define IN_ALL  3
82
83 size_t
84 strftime(char * __restrict s, size_t maxsize, const char * __restrict format,
85          const struct tm * __restrict t)
86 {
87         char *  p;
88         int     warn;
89
90         tzset();
91         warn = IN_NONE;
92         p = _fmt(((format == NULL) ? "%c" : format), t, s, s + maxsize, &warn);
93 #ifndef NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU
94         if (warn != IN_NONE && getenv(YEAR_2000_NAME) != NULL) {
95                 fprintf(stderr, "\n");
96                 if (format == NULL)
97                         fprintf(stderr, "NULL strftime format ");
98                 else    fprintf(stderr, "strftime format \"%s\" ",
99                                 format);
100                 fprintf(stderr, "yields only two digits of years in ");
101                 if (warn == IN_SOME)
102                         fprintf(stderr, "some locales");
103                 else if (warn == IN_THIS)
104                         fprintf(stderr, "the current locale");
105                 else    fprintf(stderr, "all locales");
106                 fprintf(stderr, "\n");
107         }
108 #endif /* !defined NO_RUN_TIME_WARNINGS_ABOUT_YEAR_2000_PROBLEMS_THANK_YOU */
109         if (p == s + maxsize)
110                 return 0;
111         *p = '\0';
112         return p - s;
113 }
114
115 static char *
116 _fmt(const char *format, const struct tm * const t, char *pt,
117      const char * const ptlim, int * warnp)
118 {
119         for ( ; *format; ++format) {
120                 if (*format == '%') {
121 label:
122                         switch (*++format) {
123                         case '\0':
124                                 --format;
125                                 break;
126                         case 'A':
127                                 pt = _add((t->tm_wday < 0 ||
128                                         t->tm_wday >= DAYSPERWEEK) ?
129                                         "?" : Locale->day[t->tm_wday],
130                                         pt, ptlim);
131                                 continue;
132                         case 'a':
133                                 pt = _add((t->tm_wday < 0 ||
134                                         t->tm_wday >= DAYSPERWEEK) ?
135                                         "?" : Locale->abday[t->tm_wday],
136                                         pt, ptlim);
137                                 continue;
138                         case 'B':
139                                 pt = _add((t->tm_mon < 0 ||
140                                         t->tm_mon >= MONSPERYEAR) ?
141                                         "?" : Locale->mon[t->tm_mon],
142                                         pt, ptlim);
143                                 continue;
144                         case 'b':
145                         case 'h':
146                                 pt = _add((t->tm_mon < 0 ||
147                                         t->tm_mon >= MONSPERYEAR) ?
148                                         "?" : Locale->abmon[t->tm_mon],
149                                         pt, ptlim);
150                                 continue;
151                         case 'C':
152                                 /*
153                                 ** %C used to do a...
154                                 **      _fmt("%a %b %e %X %Y", t);
155                                 ** ...whereas now POSIX 1003.2 calls for
156                                 ** something completely different.
157                                 ** (ado, 1993-05-24)
158                                 */
159                                 pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 0,
160                                         pt, ptlim);
161                                 continue;
162                         case 'c':
163                                 {
164                                 int warn2 = IN_SOME;
165
166                                 pt = _fmt(Locale->d_t_fmt, t, pt, ptlim, &warn2);
167                                 if (warn2 == IN_ALL)
168                                         warn2 = IN_THIS;
169                                 if (warn2 > *warnp)
170                                         *warnp = warn2;
171                                 }
172                                 continue;
173                         case 'D':
174                                 pt = _fmt("%m/%d/%y", t, pt, ptlim, warnp);
175                                 continue;
176                         case 'd':
177                                 pt = _conv(t->tm_mday, "%02d", pt, ptlim);
178                                 continue;
179                         case 'E':
180                         case 'O':
181                                 /*
182                                 ** C99 locale modifiers.
183                                 ** The sequences
184                                 **      %Ec %EC %Ex %EX %Ey %EY
185                                 **      %Od %oe %OH %OI %Om %OM
186                                 **      %OS %Ou %OU %OV %Ow %OW %Oy
187                                 ** are supposed to provide alternate
188                                 ** representations.
189                                 */
190                                 goto label;
191                         case 'e':
192                                 pt = _conv(t->tm_mday, "%2d", pt, ptlim);
193                                 continue;
194                         case 'F':
195                                 pt = _fmt("%Y-%m-%d", t, pt, ptlim, warnp);
196                                 continue;
197                         case 'H':
198                                 pt = _conv(t->tm_hour, "%02d", pt, ptlim);
199                                 continue;
200                         case 'I':
201                                 pt = _conv((t->tm_hour % 12) ?
202                                         (t->tm_hour % 12) : 12,
203                                         "%02d", pt, ptlim);
204                                 continue;
205                         case 'j':
206                                 pt = _conv(t->tm_yday + 1, "%03d", pt, ptlim);
207                                 continue;
208                         case 'k':
209                                 /*
210                                 ** This used to be...
211                                 **      _conv(t->tm_hour % 12 ?
212                                 **              t->tm_hour % 12 : 12, 2, ' ');
213                                 ** ...and has been changed to the below to
214                                 ** match SunOS 4.1.1 and Arnold Robbins'
215                                 ** strftime version 3.0. That is, "%k" and
216                                 ** "%l" have been swapped.
217                                 ** (ado, 1993-05-24)
218                                 */
219                                 pt = _conv(t->tm_hour, "%2d", pt, ptlim);
220                                 continue;
221 #ifdef KITCHEN_SINK
222                         case 'K':
223                                 /*
224                                 ** After all this time, still unclaimed!
225                                 */
226                                 pt = _add("kitchen sink", pt, ptlim);
227                                 continue;
228 #endif /* defined KITCHEN_SINK */
229                         case 'l':
230                                 /*
231                                 ** This used to be...
232                                 **      _conv(t->tm_hour, 2, ' ');
233                                 ** ...and has been changed to the below to
234                                 ** match SunOS 4.1.1 and Arnold Robbin's
235                                 ** strftime version 3.0. That is, "%k" and
236                                 ** "%l" have been swapped.
237                                 ** (ado, 1993-05-24)
238                                 */
239                                 pt = _conv((t->tm_hour % 12) ?
240                                         (t->tm_hour % 12) : 12,
241                                         "%2d", pt, ptlim);
242                                 continue;
243                         case 'M':
244                                 pt = _conv(t->tm_min, "%02d", pt, ptlim);
245                                 continue;
246                         case 'm':
247                                 pt = _conv(t->tm_mon + 1, "%02d", pt, ptlim);
248                                 continue;
249                         case 'n':
250                                 pt = _add("\n", pt, ptlim);
251                                 continue;
252                         case 'p':
253                                 pt = _add((t->tm_hour >= (HOURSPERDAY / 2)) ?
254                                         Locale->am_pm[1] :
255                                         Locale->am_pm[0],
256                                         pt, ptlim);
257                                 continue;
258                         case 'R':
259                                 pt = _fmt("%H:%M", t, pt, ptlim, warnp);
260                                 continue;
261                         case 'r':
262                                 pt = _fmt(Locale->t_fmt_ampm, t, pt, ptlim,
263                                         warnp);
264                                 continue;
265                         case 'S':
266                                 pt = _conv(t->tm_sec, "%02d", pt, ptlim);
267                                 continue;
268                         case 's':
269                                 {
270                                         struct tm       tm;
271                                         char            buf[INT_STRLEN_MAXIMUM(
272                                                                 time_t) + 1];
273                                         time_t          mkt;
274
275                                         tm = *t;
276                                         mkt = mktime(&tm);
277                                         /* CONSTCOND */
278                                         if (TYPE_SIGNED(time_t))
279                                                 snprintf(buf, sizeof(buf),
280                                                     "%ld", (long) mkt);
281                                         else    snprintf(buf, sizeof(buf),
282                                                     "%lu", (unsigned long)
283                                                     mkt);
284                                         pt = _add(buf, pt, ptlim);
285                                 }
286                                 continue;
287                         case 'T':
288                                 pt = _fmt("%H:%M:%S", t, pt, ptlim, warnp);
289                                 continue;
290                         case 't':
291                                 pt = _add("\t", pt, ptlim);
292                                 continue;
293                         case 'U':
294                                 pt = _conv((t->tm_yday + DAYSPERWEEK -
295                                         t->tm_wday) / DAYSPERWEEK,
296                                         "%02d", pt, ptlim);
297                                 continue;
298                         case 'u':
299                                 /*
300                                 ** From Arnold Robbins' strftime version 3.0:
301                                 ** "ISO 8601: Weekday as a decimal number
302                                 ** [1 (Monday) - 7]"
303                                 ** (ado, 1993-05-24)
304                                 */
305                                 pt = _conv((t->tm_wday == 0) ?
306                                         DAYSPERWEEK : t->tm_wday,
307                                         "%d", pt, ptlim);
308                                 continue;
309                         case 'V':       /* ISO 8601 week number */
310                         case 'G':       /* ISO 8601 year (four digits) */
311                         case 'g':       /* ISO 8601 year (two digits) */
312 /*
313 ** From Arnold Robbins' strftime version 3.0: "the week number of the
314 ** year (the first Monday as the first day of week 1) as a decimal number
315 ** (01-53)."
316 ** (ado, 1993-05-24)
317 **
318 ** From "http://www.ft.uni-erlangen.de/~mskuhn/iso-time.html" by Markus Kuhn:
319 ** "Week 01 of a year is per definition the first week which has the
320 ** Thursday in this year, which is equivalent to the week which contains
321 ** the fourth day of January. In other words, the first week of a new year
322 ** is the week which has the majority of its days in the new year. Week 01
323 ** might also contain days from the previous year and the week before week
324 ** 01 of a year is the last week (52 or 53) of the previous year even if
325 ** it contains days from the new year. A week starts with Monday (day 1)
326 ** and ends with Sunday (day 7). For example, the first week of the year
327 ** 1997 lasts from 1996-12-30 to 1997-01-05..."
328 ** (ado, 1996-01-02)
329 */
330                                 {
331                                         int     year;
332                                         int     base;
333                                         int     yday;
334                                         int     wday;
335                                         int     w;
336
337                                         year = t->tm_year;
338                                         base = TM_YEAR_BASE;
339                                         yday = t->tm_yday;
340                                         wday = t->tm_wday;
341                                         for ( ; ; ) {
342                                                 int     len;
343                                                 int     bot;
344                                                 int     top;
345
346                                                 len = isleap_sum(year, base) ?
347                                                         DAYSPERLYEAR :
348                                                         DAYSPERNYEAR;
349                                                 /*
350                                                 ** What yday (-3 ... 3) does
351                                                 ** the ISO year begin on?
352                                                 */
353                                                 bot = ((yday + 11 - wday) %
354                                                         DAYSPERWEEK) - 3;
355                                                 /*
356                                                 ** What yday does the NEXT
357                                                 ** ISO year begin on?
358                                                 */
359                                                 top = bot -
360                                                         (len % DAYSPERWEEK);
361                                                 if (top < -3)
362                                                         top += DAYSPERWEEK;
363                                                 top += len;
364                                                 if (yday >= top) {
365                                                         ++base;
366                                                         w = 1;
367                                                         break;
368                                                 }
369                                                 if (yday >= bot) {
370                                                         w = 1 + ((yday - bot) /
371                                                                 DAYSPERWEEK);
372                                                         break;
373                                                 }
374                                                 --base;
375                                                 yday += isleap_sum(year, base) ?
376                                                         DAYSPERLYEAR :
377                                                         DAYSPERNYEAR;
378                                         }
379 #ifdef XPG4_1994_04_09
380                                         if ((w == 52 &&
381                                                 t->tm_mon == TM_JANUARY) ||
382                                                 (w == 1 &&
383                                                 t->tm_mon == TM_DECEMBER))
384                                                         w = 53;
385 #endif /* defined XPG4_1994_04_09 */
386                                         if (*format == 'V')
387                                                 pt = _conv(w, "%02d",
388                                                         pt, ptlim);
389                                         else if (*format == 'g') {
390                                                 *warnp = IN_ALL;
391                                                 pt = _yconv(year, base, 0, 1,
392                                                         pt, ptlim);
393                                         } else  pt = _yconv(year, base, 1, 1,
394                                                         pt, ptlim);
395                                 }
396                                 continue;
397                         case 'v':
398                                 /*
399                                 ** From Arnold Robbins' strftime version 3.0:
400                                 ** "date as dd-bbb-YYYY"
401                                 ** (ado, 1993-05-24)
402                                 */
403                                 pt = _fmt("%e-%b-%Y", t, pt, ptlim, warnp);
404                                 continue;
405                         case 'W':
406                                 pt = _conv((t->tm_yday + DAYSPERWEEK -
407                                         (t->tm_wday ?
408                                         (t->tm_wday - 1) :
409                                         (DAYSPERWEEK - 1))) / DAYSPERWEEK,
410                                         "%02d", pt, ptlim);
411                                 continue;
412                         case 'w':
413                                 pt = _conv(t->tm_wday, "%d", pt, ptlim);
414                                 continue;
415                         case 'X':
416                                 pt = _fmt(Locale->t_fmt, t, pt, ptlim, warnp);
417                                 continue;
418                         case 'x':
419                                 {
420                                 int     warn2 = IN_SOME;
421
422                                 pt = _fmt(Locale->d_fmt, t, pt, ptlim, &warn2);
423                                 if (warn2 == IN_ALL)
424                                         warn2 = IN_THIS;
425                                 if (warn2 > *warnp)
426                                         *warnp = warn2;
427                                 }
428                                 continue;
429                         case 'y':
430                                 *warnp = IN_ALL;
431                                 pt = _yconv(t->tm_year, TM_YEAR_BASE, 0, 1,
432                                         pt, ptlim);
433                                 continue;
434                         case 'Y':
435                                 pt = _yconv(t->tm_year, TM_YEAR_BASE, 1, 1,
436                                         pt, ptlim);
437                                 continue;
438                         case 'Z':
439 #ifdef TM_ZONE
440                                 if (t->TM_ZONE != NULL)
441                                         pt = _add(t->TM_ZONE, pt, ptlim);
442                                 else
443 #endif /* defined TM_ZONE */
444                                 if (t->tm_isdst >= 0)
445                                         pt = _add(tzname[t->tm_isdst != 0],
446                                                 pt, ptlim);
447                                 /*
448                                 ** C99 says that %Z must be replaced by the
449                                 ** empty string if the time zone is not
450                                 ** determinable.
451                                 */
452                                 continue;
453                         case 'z':
454                                 {
455                                 int             diff;
456                                 char const *    sign;
457
458                                 if (t->tm_isdst < 0)
459                                         continue;
460 #ifdef TM_GMTOFF
461                                 diff = (int)t->TM_GMTOFF;
462 #else /* !defined TM_GMTOFF */
463                                 /*
464                                 ** C99 says that the UTC offset must
465                                 ** be computed by looking only at
466                                 ** tm_isdst. This requirement is
467                                 ** incorrect, since it means the code
468                                 ** must rely on magic (in this case
469                                 ** altzone and timezone), and the
470                                 ** magic might not have the correct
471                                 ** offset. Doing things correctly is
472                                 ** tricky and requires disobeying C99;
473                                 ** see GNU C strftime for details.
474                                 ** For now, punt and conform to the
475                                 ** standard, even though it's incorrect.
476                                 **
477                                 ** C99 says that %z must be replaced by the
478                                 ** empty string if the time zone is not
479                                 ** determinable, so output nothing if the
480                                 ** appropriate variables are not available.
481                                 */
482                                 {
483                                         struct tm tmp;
484                                         time_t lct, gct;
485
486                                         /*
487                                         ** Get calendar time from t
488                                         ** being treated as local.
489                                         */
490                                         tmp = *t; /* mktime discards const */
491                                         lct = mktime(&tmp);
492
493                                         if (lct == (time_t)-1)
494                                                 continue;
495
496                                         /*
497                                         ** Get calendar time from t
498                                         ** being treated as GMT.
499                                         **/
500                                         tmp = *t; /* mktime discards const */
501                                         gct = timegm(&tmp);
502
503                                         if (gct == (time_t)-1)
504                                                 continue;
505
506                                         /* LINTED difference will fit int */
507                                         diff = (intmax_t)gct - (intmax_t)lct;
508                                 }
509 #endif /* !defined TM_GMTOFF */
510                                 if (diff < 0) {
511                                         sign = "-";
512                                         diff = -diff;
513                                 } else  sign = "+";
514                                 pt = _add(sign, pt, ptlim);
515                                 diff /= SECSPERMIN;
516                                 diff = (diff / MINSPERHOUR) * 100 +
517                                         (diff % MINSPERHOUR);
518                                 pt = _conv(diff, "%04d", pt, ptlim);
519                                 }
520                                 continue;
521                         case '+':
522                                 pt = _fmt(Locale->d_t_fmt, t, pt, ptlim,
523                                         warnp);
524                                 continue;
525                         case '%':
526                         /*
527                         ** X311J/88-090 (4.12.3.5): if conversion char is
528                         ** undefined, behavior is undefined. Print out the
529                         ** character itself as printf(3) also does.
530                         */
531                         default:
532                                 break;
533                         }
534                 }
535                 if (pt == ptlim)
536                         break;
537                 *pt++ = *format;
538         }
539         return pt;
540 }
541
542 static char *
543 _conv(const int n, const char * const format, char * const pt,
544       const char * const ptlim)
545 {
546         char    buf[INT_STRLEN_MAXIMUM(int) + 1];
547
548         snprintf(buf, sizeof(buf), format, n);
549         return _add(buf, pt, ptlim);
550 }
551
552 static char *
553 _add(const char *str, char *pt, const char * const ptlim)
554 {
555         while (pt < ptlim && (*pt = *str++) != '\0')
556                 ++pt;
557         return pt;
558 }
559
560 /*
561 ** POSIX and the C Standard are unclear or inconsistent about
562 ** what %C and %y do if the year is negative or exceeds 9999.
563 ** Use the convention that %C concatenated with %y yields the
564 ** same output as %Y, and that %Y contains at least 4 bytes,
565 ** with more only if necessary.
566 */
567
568 static char *
569 _yconv(const int a, const int b, const int convert_top, const int convert_yy,
570        char *pt, const char * const ptlim)
571 {
572         int     lead;
573         int     trail;
574
575 #define DIVISOR 100
576         trail = a % DIVISOR + b % DIVISOR;
577         lead = a / DIVISOR + b / DIVISOR + trail / DIVISOR;
578         trail %= DIVISOR;
579         if (trail < 0 && lead > 0) {
580                 trail += DIVISOR;
581                 --lead;
582         } else if (lead < 0 && trail > 0) {
583                 trail -= DIVISOR;
584                 ++lead;
585         }
586         if (convert_top) {
587                 if (lead == 0 && trail < 0)
588                         pt = _add("-0", pt, ptlim);
589                 else    pt = _conv(lead, "%02d", pt, ptlim);
590         }
591         if (convert_yy)
592                 pt = _conv(((trail < 0) ? -trail : trail), "%02d", pt, ptlim);
593         return pt;
594 }