Ruby  1.9.3p429(2013-05-15revision40747)
strftime.c
Go to the documentation of this file.
1 /* -*- c-file-style: "linux" -*- */
2 
3 /*
4  * strftime.c
5  *
6  * Public-domain implementation of ANSI C library routine.
7  *
8  * It's written in old-style C for maximal portability.
9  * However, since I'm used to prototypes, I've included them too.
10  *
11  * If you want stuff in the System V ascftime routine, add the SYSV_EXT define.
12  * For extensions from SunOS, add SUNOS_EXT.
13  * For stuff needed to implement the P1003.2 date command, add POSIX2_DATE.
14  * For VMS dates, add VMS_EXT.
15  * For a an RFC822 time format, add MAILHEADER_EXT.
16  * For ISO week years, add ISO_DATE_EXT.
17  * For complete POSIX semantics, add POSIX_SEMANTICS.
18  *
19  * The code for %c, %x, and %X now follows the 1003.2 specification for
20  * the POSIX locale.
21  * This version ignores LOCALE information.
22  * It also doesn't worry about multi-byte characters.
23  * So there.
24  *
25  * This file is also shipped with GAWK (GNU Awk), gawk specific bits of
26  * code are included if GAWK is defined.
27  *
28  * Arnold Robbins
29  * January, February, March, 1991
30  * Updated March, April 1992
31  * Updated April, 1993
32  * Updated February, 1994
33  * Updated May, 1994
34  * Updated January, 1995
35  * Updated September, 1995
36  * Updated January, 1996
37  *
38  * Fixes from ado@elsie.nci.nih.gov
39  * February 1991, May 1992
40  * Fixes from Tor Lillqvist tml@tik.vtt.fi
41  * May, 1993
42  * Further fixes from ado@elsie.nci.nih.gov
43  * February 1994
44  * %z code from chip@chinacat.unicom.com
45  * Applied September 1995
46  * %V code fixed (again) and %G, %g added,
47  * January 1996
48  */
49 
50 #include "ruby/ruby.h"
51 #include "timev.h"
52 
53 #ifndef GAWK
54 #include <stdio.h>
55 #include <ctype.h>
56 #include <string.h>
57 #include <time.h>
58 #include <sys/types.h>
59 #include <errno.h>
60 #endif
61 #if defined(TM_IN_SYS_TIME) || !defined(GAWK)
62 #include <sys/types.h>
63 #if HAVE_SYS_TIME_H
64 #include <sys/time.h>
65 #endif
66 #endif
67 #include <math.h>
68 
69 /* defaults: season to taste */
70 #define SYSV_EXT 1 /* stuff in System V ascftime routine */
71 #define SUNOS_EXT 1 /* stuff in SunOS strftime routine */
72 #define POSIX2_DATE 1 /* stuff in Posix 1003.2 date command */
73 #define VMS_EXT 1 /* include %v for VMS date format */
74 #define MAILHEADER_EXT 1 /* add %z for HHMM format */
75 #define ISO_DATE_EXT 1 /* %G and %g for year of ISO week */
76 
77 #if defined(ISO_DATE_EXT)
78 #if ! defined(POSIX2_DATE)
79 #define POSIX2_DATE 1
80 #endif
81 #endif
82 
83 #if defined(POSIX2_DATE)
84 #if ! defined(SYSV_EXT)
85 #define SYSV_EXT 1
86 #endif
87 #if ! defined(SUNOS_EXT)
88 #define SUNOS_EXT 1
89 #endif
90 #endif
91 
92 #if defined(POSIX2_DATE)
93 #define adddecl(stuff) stuff
94 #else
95 #define adddecl(stuff)
96 #endif
97 
98 #undef strchr /* avoid AIX weirdness */
99 
100 #if !defined __STDC__ && !defined _WIN32
101 #define const
102 static int weeknumber();
103 adddecl(static int iso8601wknum();)
104 static int weeknumber_v();
105 adddecl(static int iso8601wknum_v();)
106 #else
107 static int weeknumber(const struct tm *timeptr, int firstweekday);
108 adddecl(static int iso8601wknum(const struct tm *timeptr);)
109 static int weeknumber_v(const struct vtm *vtm, int firstweekday);
110 adddecl(static int iso8601wknum_v(const struct vtm *vtm);)
111 #endif
112 
113 #ifdef STDC_HEADERS
114 #include <stdlib.h>
115 #include <string.h>
116 #else
117 extern void *malloc();
118 extern void *realloc();
119 extern char *getenv();
120 extern char *strchr();
121 #endif
122 
123 #define range(low, item, hi) max((low), min((item), (hi)))
124 
125 #undef min /* just in case */
126 
127 /* min --- return minimum of two numbers */
128 
129 #ifndef __STDC__
130 static inline int
131 min(a, b)
132 int a, b;
133 #else
134 static inline int
135 min(int a, int b)
136 #endif
137 {
138  return (a < b ? a : b);
139 }
140 
141 #undef max /* also, just in case */
142 
143 /* max --- return maximum of two numbers */
144 
145 #ifndef __STDC__
146 static inline int
147 max(a, b)
148 int a, b;
149 #else
150 static inline int
151 max(int a, int b)
152 #endif
153 {
154  return (a > b ? a : b);
155 }
156 
157 #ifdef NO_STRING_LITERAL_CONCATENATION
158 #error No string literal concatenation
159 #endif
160 
161 #define add(x,y) (rb_funcall((x), '+', 1, (y)))
162 #define sub(x,y) (rb_funcall((x), '-', 1, (y)))
163 #define mul(x,y) (rb_funcall((x), '*', 1, (y)))
164 #define quo(x,y) (rb_funcall((x), rb_intern("quo"), 1, (y)))
165 #define div(x,y) (rb_funcall((x), rb_intern("div"), 1, (y)))
166 #define mod(x,y) (rb_funcall((x), '%', 1, (y)))
167 
168 /* strftime --- produce formatted time */
169 
170 static size_t
171 rb_strftime_with_timespec(char *s, size_t maxsize, const char *format, const struct vtm *vtm, VALUE timev, struct timespec *ts, int gmt)
172 {
173  const char *const endp = s + maxsize;
174  const char *const start = s;
175  const char *sp, *tp;
176  auto char tbuf[100];
177  long off;
178  ptrdiff_t i;
179  int w;
180  long y;
181  int precision, flags, colons;
182  char padding;
183  enum {LEFT, CHCASE, LOWER, UPPER, LOCALE_O, LOCALE_E};
184 #define BIT_OF(n) (1U<<(n))
185 #ifdef MAILHEADER_EXT
186  int sign;
187 #endif
188 
189  /* various tables, useful in North America */
190  static const char days_l[][10] = {
191  "Sunday", "Monday", "Tuesday", "Wednesday",
192  "Thursday", "Friday", "Saturday",
193  };
194  static const char months_l[][10] = {
195  "January", "February", "March", "April",
196  "May", "June", "July", "August", "September",
197  "October", "November", "December",
198  };
199  static const char ampm[][3] = { "AM", "PM", };
200 
201  if (s == NULL || format == NULL || vtm == NULL || maxsize == 0)
202  return 0;
203 
204  /* quick check if we even need to bother */
205  if (strchr(format, '%') == NULL && strlen(format) + 1 >= maxsize) {
206  err:
207  errno = ERANGE;
208  return 0;
209  }
210 
211  for (; *format && s < endp - 1; format++) {
212 #define FLAG_FOUND() do { \
213  if (precision > 0 || flags & (BIT_OF(LOCALE_E)|BIT_OF(LOCALE_O))) \
214  goto unknown; \
215  } while (0)
216 #define NEEDS(n) do if (s >= endp || (n) >= endp - s - 1) goto err; while (0)
217 #define FILL_PADDING(i) do { \
218  if (!(flags & BIT_OF(LEFT)) && precision > (i)) { \
219  NEEDS(precision); \
220  memset(s, padding ? padding : ' ', precision - (i)); \
221  s += precision - (i); \
222  } \
223  else { \
224  NEEDS(i); \
225  } \
226 } while (0);
227 #define FMT(def_pad, def_prec, fmt, val) \
228  do { \
229  int l; \
230  if (precision <= 0) precision = (def_prec); \
231  if (flags & BIT_OF(LEFT)) precision = 1; \
232  l = snprintf(s, endp - s, \
233  ((padding == '0' || (!padding && (def_pad) == '0')) ? "%0*"fmt : "%*"fmt), \
234  precision, (val)); \
235  if (l < 0) goto err; \
236  s += l; \
237  } while (0)
238 #define STRFTIME(fmt) \
239  do { \
240  i = rb_strftime_with_timespec(s, endp - s, (fmt), vtm, timev, ts, gmt); \
241  if (!i) return 0; \
242  if (precision > i) {\
243  NEEDS(precision); \
244  memmove(s + precision - i, s, i);\
245  memset(s, padding ? padding : ' ', precision - i); \
246  s += precision; \
247  }\
248  else s += i; \
249  } while (0)
250 #define FMTV(def_pad, def_prec, fmt, val) \
251  do { \
252  VALUE tmp = (val); \
253  if (FIXNUM_P(tmp)) { \
254  FMT((def_pad), (def_prec), "l"fmt, FIX2LONG(tmp)); \
255  } \
256  else { \
257  VALUE args[2], result; \
258  size_t l; \
259  if (precision <= 0) precision = (def_prec); \
260  if (flags & BIT_OF(LEFT)) precision = 1; \
261  args[0] = INT2FIX(precision); \
262  args[1] = (val); \
263  if (padding == '0' || (!padding && (def_pad) == '0')) \
264  result = rb_str_format(2, args, rb_str_new2("%0*"fmt)); \
265  else \
266  result = rb_str_format(2, args, rb_str_new2("%*"fmt)); \
267  l = strlcpy(s, StringValueCStr(result), endp-s); \
268  if ((size_t)(endp-s) <= l) \
269  goto err; \
270  s += l; \
271  } \
272  } while (0)
273 
274  if (*format != '%') {
275  *s++ = *format;
276  continue;
277  }
278  tp = tbuf;
279  sp = format;
280  precision = -1;
281  flags = 0;
282  padding = 0;
283  colons = 0;
284  again:
285  switch (*++format) {
286  case '\0':
287  format--;
288  goto unknown;
289 
290  case '%':
291  FILL_PADDING(1);
292  *s++ = '%';
293  continue;
294 
295  case 'a': /* abbreviated weekday name */
296  if (flags & BIT_OF(CHCASE)) {
297  flags &= ~(BIT_OF(LOWER)|BIT_OF(CHCASE));
298  flags |= BIT_OF(UPPER);
299  }
300  if (vtm->wday < 0 || vtm->wday > 6)
301  i = 1, tp = "?";
302  else
303  i = 3, tp = days_l[vtm->wday];
304  break;
305 
306  case 'A': /* full weekday name */
307  if (flags & BIT_OF(CHCASE)) {
308  flags &= ~(BIT_OF(LOWER)|BIT_OF(CHCASE));
309  flags |= BIT_OF(UPPER);
310  }
311  if (vtm->wday < 0 || vtm->wday > 6)
312  i = 1, tp = "?";
313  else
314  i = strlen(tp = days_l[vtm->wday]);
315  break;
316 
317 #ifdef SYSV_EXT
318  case 'h': /* abbreviated month name */
319 #endif
320  case 'b': /* abbreviated month name */
321  if (flags & BIT_OF(CHCASE)) {
322  flags &= ~(BIT_OF(LOWER)|BIT_OF(CHCASE));
323  flags |= BIT_OF(UPPER);
324  }
325  if (vtm->mon < 1 || vtm->mon > 12)
326  i = 1, tp = "?";
327  else
328  i = 3, tp = months_l[vtm->mon-1];
329  break;
330 
331  case 'B': /* full month name */
332  if (flags & BIT_OF(CHCASE)) {
333  flags &= ~(BIT_OF(LOWER)|BIT_OF(CHCASE));
334  flags |= BIT_OF(UPPER);
335  }
336  if (vtm->mon < 1 || vtm->mon > 12)
337  i = 1, tp = "?";
338  else
339  i = strlen(tp = months_l[vtm->mon-1]);
340  break;
341 
342  case 'c': /* appropriate date and time representation */
343  STRFTIME("%a %b %e %H:%M:%S %Y");
344  continue;
345 
346  case 'd': /* day of the month, 01 - 31 */
347  i = range(1, vtm->mday, 31);
348  FMT('0', 2, "d", (int)i);
349  continue;
350 
351  case 'H': /* hour, 24-hour clock, 00 - 23 */
352  i = range(0, vtm->hour, 23);
353  FMT('0', 2, "d", (int)i);
354  continue;
355 
356  case 'I': /* hour, 12-hour clock, 01 - 12 */
357  i = range(0, vtm->hour, 23);
358  if (i == 0)
359  i = 12;
360  else if (i > 12)
361  i -= 12;
362  FMT('0', 2, "d", (int)i);
363  continue;
364 
365  case 'j': /* day of the year, 001 - 366 */
366  FMT('0', 3, "d", vtm->yday);
367  continue;
368 
369  case 'm': /* month, 01 - 12 */
370  i = range(1, vtm->mon, 12);
371  FMT('0', 2, "d", (int)i);
372  continue;
373 
374  case 'M': /* minute, 00 - 59 */
375  i = range(0, vtm->min, 59);
376  FMT('0', 2, "d", (int)i);
377  continue;
378 
379  case 'p': /* AM or PM based on 12-hour clock */
380  case 'P': /* am or pm based on 12-hour clock */
381  if ((*format == 'p' && (flags & BIT_OF(CHCASE))) ||
382  (*format == 'P' && !(flags & (BIT_OF(CHCASE)|BIT_OF(UPPER))))) {
383  flags &= ~(BIT_OF(UPPER)|BIT_OF(CHCASE));
384  flags |= BIT_OF(LOWER);
385  }
386  i = range(0, vtm->hour, 23);
387  if (i < 12)
388  tp = ampm[0];
389  else
390  tp = ampm[1];
391  i = 2;
392  break;
393 
394  case 's':
395  if (ts) {
396  time_t sec = ts->tv_sec;
397  if (~(time_t)0 <= 0)
398  FMT('0', 1, PRI_TIMET_PREFIX"d", sec);
399  else
400  FMT('0', 1, PRI_TIMET_PREFIX"u", sec);
401  }
402  else {
403  VALUE sec = div(timev, INT2FIX(1));
404  FMTV('0', 1, "d", sec);
405  }
406  continue;
407 
408  case 'S': /* second, 00 - 60 */
409  i = range(0, vtm->sec, 60);
410  FMT('0', 2, "d", (int)i);
411  continue;
412 
413  case 'U': /* week of year, Sunday is first day of week */
414  FMT('0', 2, "d", weeknumber_v(vtm, 0));
415  continue;
416 
417  case 'w': /* weekday, Sunday == 0, 0 - 6 */
418  i = range(0, vtm->wday, 6);
419  FMT('0', 1, "d", (int)i);
420  continue;
421 
422  case 'W': /* week of year, Monday is first day of week */
423  FMT('0', 2, "d", weeknumber_v(vtm, 1));
424  continue;
425 
426  case 'x': /* appropriate date representation */
427  STRFTIME("%m/%d/%y");
428  continue;
429 
430  case 'X': /* appropriate time representation */
431  STRFTIME("%H:%M:%S");
432  continue;
433 
434  case 'y': /* year without a century, 00 - 99 */
435  i = NUM2INT(mod(vtm->year, INT2FIX(100)));
436  FMT('0', 2, "d", (int)i);
437  continue;
438 
439  case 'Y': /* year with century */
440  if (FIXNUM_P(vtm->year)) {
441  long y = FIX2LONG(vtm->year);
442  FMT('0', 0 <= y ? 4 : 5, "ld", y);
443  }
444  else {
445  FMTV('0', 4, "d", vtm->year);
446  }
447  continue;
448 
449 #ifdef MAILHEADER_EXT
450  case 'z': /* time zone offset east of GMT e.g. -0600 */
451  switch (colons) {
452  case 0: /* %z -> +hhmm */
453  precision = precision <= 5 ? 2 : precision-3;
454  NEEDS(precision + 3);
455  break;
456 
457  case 1: /* %:z -> +hh:mm */
458  precision = precision <= 6 ? 2 : precision-4;
459  NEEDS(precision + 4);
460  break;
461 
462  case 2: /* %::z -> +hh:mm:ss */
463  precision = precision <= 9 ? 2 : precision-7;
464  NEEDS(precision + 7);
465  break;
466 
467  default:
468  format--;
469  goto unknown;
470  }
471  if (gmt) {
472  off = 0;
473  }
474  else {
475  off = NUM2LONG(rb_funcall(vtm->utc_offset, rb_intern("round"), 0));
476  }
477  if (off < 0) {
478  off = -off;
479  sign = -1;
480  } else {
481  sign = +1;
482  }
483  i = snprintf(s, endp - s, (padding == ' ' ? "%+*ld" : "%+.*ld"),
484  precision + 1, sign * (off / 3600));
485  if (i < 0) goto err;
486  if (sign < 0 && off < 3600) {
487  *(padding == ' ' ? s + i - 2 : s) = '-';
488  }
489  s += i;
490  off = off % 3600;
491  if (1 <= colons)
492  *s++ = ':';
493  i = snprintf(s, endp - s, "%02d", (int)(off / 60));
494  if (i < 0) goto err;
495  s += i;
496  off = off % 60;
497  if (2 <= colons) {
498  *s++ = ':';
499  i = snprintf(s, endp - s, "%02d", (int)off);
500  if (i < 0) goto err;
501  s += i;
502  }
503  continue;
504 #endif /* MAILHEADER_EXT */
505 
506  case 'Z': /* time zone name or abbreviation */
507  if (flags & BIT_OF(CHCASE)) {
508  flags &= ~(BIT_OF(UPPER)|BIT_OF(CHCASE));
509  flags |= BIT_OF(LOWER);
510  }
511  if (gmt) {
512  i = 3;
513  tp = "UTC";
514  break;
515  }
516  if (vtm->zone == NULL)
517  tp = "";
518  else
519  tp = vtm->zone;
520  i = strlen(tp);
521  break;
522 
523 #ifdef SYSV_EXT
524  case 'n': /* same as \n */
525  FILL_PADDING(1);
526  *s++ = '\n';
527  continue;
528 
529  case 't': /* same as \t */
530  FILL_PADDING(1);
531  *s++ = '\t';
532  continue;
533 
534  case 'D': /* date as %m/%d/%y */
535  STRFTIME("%m/%d/%y");
536  continue;
537 
538  case 'e': /* day of month, blank padded */
539  FMT(' ', 2, "d", range(1, vtm->mday, 31));
540  continue;
541 
542  case 'r': /* time as %I:%M:%S %p */
543  STRFTIME("%I:%M:%S %p");
544  continue;
545 
546  case 'R': /* time as %H:%M */
547  STRFTIME("%H:%M");
548  continue;
549 
550  case 'T': /* time as %H:%M:%S */
551  STRFTIME("%H:%M:%S");
552  continue;
553 #endif
554 
555 #ifdef SUNOS_EXT
556  case 'k': /* hour, 24-hour clock, blank pad */
557  i = range(0, vtm->hour, 23);
558  FMT(' ', 2, "d", (int)i);
559  continue;
560 
561  case 'l': /* hour, 12-hour clock, 1 - 12, blank pad */
562  i = range(0, vtm->hour, 23);
563  if (i == 0)
564  i = 12;
565  else if (i > 12)
566  i -= 12;
567  FMT(' ', 2, "d", (int)i);
568  continue;
569 #endif
570 
571 
572 #ifdef VMS_EXT
573  case 'v': /* date as dd-bbb-YYYY */
574  STRFTIME("%e-%^b-%4Y");
575  continue;
576 #endif
577 
578 
579 #ifdef POSIX2_DATE
580  case 'C':
581  FMTV('0', 2, "d", div(vtm->year, INT2FIX(100)));
582  continue;
583 
584  case 'E':
585  /* POSIX locale extensions, ignored for now */
586  flags |= BIT_OF(LOCALE_E);
587  goto again;
588  case 'O':
589  /* POSIX locale extensions, ignored for now */
590  flags |= BIT_OF(LOCALE_O);
591  goto again;
592 
593  case 'V': /* week of year according ISO 8601 */
594  FMT('0', 2, "d", iso8601wknum_v(vtm));
595  continue;
596 
597  case 'u':
598  /* ISO 8601: Weekday as a decimal number [1 (Monday) - 7] */
599  FMT('0', 1, "d", vtm->wday == 0 ? 7 : vtm->wday);
600  continue;
601 #endif /* POSIX2_DATE */
602 
603 #ifdef ISO_DATE_EXT
604  case 'G':
605  case 'g':
606  /*
607  * Year of ISO week.
608  *
609  * If it's December but the ISO week number is one,
610  * that week is in next year.
611  * If it's January but the ISO week number is 52 or
612  * 53, that week is in last year.
613  * Otherwise, it's this year.
614  */
615  {
616  VALUE yv = vtm->year;
617  w = iso8601wknum_v(vtm);
618  if (vtm->mon == 12 && w == 1)
619  yv = add(yv, INT2FIX(1));
620  else if (vtm->mon == 1 && w >= 52)
621  yv = sub(yv, INT2FIX(1));
622 
623  if (*format == 'G') {
624  if (FIXNUM_P(yv)) {
625  const long y = FIX2LONG(yv);
626  FMT('0', 0 <= y ? 4 : 5, "ld", y);
627  }
628  else {
629  FMTV('0', 4, "d", yv);
630  }
631  }
632  else {
633  yv = mod(yv, INT2FIX(100));
634  y = FIX2LONG(yv);
635  FMT('0', 2, "ld", y);
636  }
637  continue;
638  }
639 
640 #endif /* ISO_DATE_EXT */
641 
642 
643  case 'L':
644  w = 3;
645  goto subsec;
646 
647  case 'N':
648  /*
649  * fractional second digits. default is 9 digits
650  * (nanosecond).
651  *
652  * %3N millisecond (3 digits)
653  * %6N microsecond (6 digits)
654  * %9N nanosecond (9 digits)
655  */
656  w = 9;
657  subsec:
658  if (precision <= 0) {
659  precision = w;
660  }
661  NEEDS(precision);
662 
663  if (ts) {
664  long subsec = ts->tv_nsec;
665  if (9 < precision) {
666  snprintf(s, endp - s, "%09ld", subsec);
667  memset(s+9, '0', precision-9);
668  s += precision;
669  }
670  else {
671  int i;
672  for (i = 0; i < 9-precision; i++)
673  subsec /= 10;
674  snprintf(s, endp - s, "%0*ld", precision, subsec);
675  s += precision;
676  }
677  }
678  else {
679  VALUE subsec = mod(timev, INT2FIX(1));
680  int ww;
681  long n;
682 
683  ww = precision;
684  while (9 <= ww) {
685  subsec = mul(subsec, INT2FIX(1000000000));
686  ww -= 9;
687  }
688  n = 1;
689  for (; 0 < ww; ww--)
690  n *= 10;
691  if (n != 1)
692  subsec = mul(subsec, INT2FIX(n));
693  subsec = div(subsec, INT2FIX(1));
694 
695  if (FIXNUM_P(subsec)) {
696  (void)snprintf(s, endp - s, "%0*ld", precision, FIX2LONG(subsec));
697  s += precision;
698  }
699  else {
700  VALUE args[2], result;
701  args[0] = INT2FIX(precision);
702  args[1] = subsec;
703  result = rb_str_format(2, args, rb_str_new2("%0*d"));
704  (void)strlcpy(s, StringValueCStr(result), endp-s);
705  s += precision;
706  }
707  }
708  continue;
709 
710  case 'F': /* Equivalent to %Y-%m-%d */
711  STRFTIME("%Y-%m-%d");
712  continue;
713 
714  case '-':
715  FLAG_FOUND();
716  flags |= BIT_OF(LEFT);
717  padding = precision = 0;
718  goto again;
719 
720  case '^':
721  FLAG_FOUND();
722  flags |= BIT_OF(UPPER);
723  goto again;
724 
725  case '#':
726  FLAG_FOUND();
727  flags |= BIT_OF(CHCASE);
728  goto again;
729 
730  case '_':
731  FLAG_FOUND();
732  padding = ' ';
733  goto again;
734 
735  case ':':
736  FLAG_FOUND();
737  colons++;
738  goto again;
739 
740  case '0':
741  padding = '0';
742  case '1': case '2': case '3': case '4':
743  case '5': case '6': case '7': case '8': case '9':
744  {
745  char *e;
746  precision = (int)strtoul(format, &e, 10);
747  format = e - 1;
748  goto again;
749  }
750 
751  default:
752  unknown:
753  i = format - sp + 1;
754  tp = sp;
755  precision = -1;
756  flags = 0;
757  padding = 0;
758  colons = 0;
759  break;
760  }
761  if (i) {
762  FILL_PADDING(i);
763  memcpy(s, tp, i);
764  switch (flags & (BIT_OF(UPPER)|BIT_OF(LOWER))) {
765  case BIT_OF(UPPER):
766  do {
767  if (ISLOWER(*s)) *s = TOUPPER(*s);
768  } while (s++, --i);
769  break;
770  case BIT_OF(LOWER):
771  do {
772  if (ISUPPER(*s)) *s = TOLOWER(*s);
773  } while (s++, --i);
774  break;
775  default:
776  s += i;
777  break;
778  }
779  }
780  }
781  if (s >= endp) {
782  goto err;
783  }
784  if (*format == '\0') {
785  *s = '\0';
786  return (s - start);
787  } else
788  return 0;
789 }
790 
791 size_t
792 rb_strftime(char *s, size_t maxsize, const char *format, const struct vtm *vtm, VALUE timev, int gmt)
793 {
794  return rb_strftime_with_timespec(s, maxsize, format, vtm, timev, NULL, gmt);
795 }
796 
797 size_t
798 rb_strftime_timespec(char *s, size_t maxsize, const char *format, const struct vtm *vtm, struct timespec *ts, int gmt)
799 {
800  return rb_strftime_with_timespec(s, maxsize, format, vtm, Qnil, ts, gmt);
801 }
802 
803 /* isleap --- is a year a leap year? */
804 
805 #ifndef __STDC__
806 static int
807 isleap(year)
808 long year;
809 #else
810 static int
811 isleap(long year)
812 #endif
813 {
814  return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
815 }
816 
817 
818 static void
819 vtm2tm_noyear(const struct vtm *vtm, struct tm *result)
820 {
821  struct tm tm;
822 
823  /* for isleap() in iso8601wknum. +100 is -1900 (mod 400). */
824  tm.tm_year = FIX2INT(mod(vtm->year, INT2FIX(400))) + 100;
825 
826  tm.tm_mon = vtm->mon-1;
827  tm.tm_mday = vtm->mday;
828  tm.tm_hour = vtm->hour;
829  tm.tm_min = vtm->min;
830  tm.tm_sec = vtm->sec;
831  tm.tm_wday = vtm->wday;
832  tm.tm_yday = vtm->yday-1;
833  tm.tm_isdst = vtm->isdst;
834 #if defined(HAVE_STRUCT_TM_TM_GMTOFF)
835  tm.tm_gmtoff = NUM2LONG(vtm->utc_offset);
836 #endif
837 #if defined(HAVE_TM_ZONE)
838  tm.tm_zone = (char *)vtm->zone;
839 #endif
840  *result = tm;
841 }
842 
843 #ifdef POSIX2_DATE
844 /* iso8601wknum --- compute week number according to ISO 8601 */
845 
846 #ifndef __STDC__
847 static int
848 iso8601wknum(timeptr)
849 const struct tm *timeptr;
850 #else
851 static int
852 iso8601wknum(const struct tm *timeptr)
853 #endif
854 {
855  /*
856  * From 1003.2:
857  * If the week (Monday to Sunday) containing January 1
858  * has four or more days in the new year, then it is week 1;
859  * otherwise it is the highest numbered week of the previous
860  * year (52 or 53), and the next week is week 1.
861  *
862  * ADR: This means if Jan 1 was Monday through Thursday,
863  * it was week 1, otherwise week 52 or 53.
864  *
865  * XPG4 erroneously included POSIX.2 rationale text in the
866  * main body of the standard. Thus it requires week 53.
867  */
868 
869  int weeknum, jan1day;
870 
871  /* get week number, Monday as first day of the week */
872  weeknum = weeknumber(timeptr, 1);
873 
874  /*
875  * With thanks and tip of the hatlo to tml@tik.vtt.fi
876  *
877  * What day of the week does January 1 fall on?
878  * We know that
879  * (timeptr->tm_yday - jan1.tm_yday) MOD 7 ==
880  * (timeptr->tm_wday - jan1.tm_wday) MOD 7
881  * and that
882  * jan1.tm_yday == 0
883  * and that
884  * timeptr->tm_wday MOD 7 == timeptr->tm_wday
885  * from which it follows that. . .
886  */
887  jan1day = timeptr->tm_wday - (timeptr->tm_yday % 7);
888  if (jan1day < 0)
889  jan1day += 7;
890 
891  /*
892  * If Jan 1 was a Monday through Thursday, it was in
893  * week 1. Otherwise it was last year's highest week, which is
894  * this year's week 0.
895  *
896  * What does that mean?
897  * If Jan 1 was Monday, the week number is exactly right, it can
898  * never be 0.
899  * If it was Tuesday through Thursday, the weeknumber is one
900  * less than it should be, so we add one.
901  * Otherwise, Friday, Saturday or Sunday, the week number is
902  * OK, but if it is 0, it needs to be 52 or 53.
903  */
904  switch (jan1day) {
905  case 1: /* Monday */
906  break;
907  case 2: /* Tuesday */
908  case 3: /* Wednesday */
909  case 4: /* Thursday */
910  weeknum++;
911  break;
912  case 5: /* Friday */
913  case 6: /* Saturday */
914  case 0: /* Sunday */
915  if (weeknum == 0) {
916 #ifdef USE_BROKEN_XPG4
917  /* XPG4 (as of March 1994) says 53 unconditionally */
918  weeknum = 53;
919 #else
920  /* get week number of last week of last year */
921  struct tm dec31ly; /* 12/31 last year */
922  dec31ly = *timeptr;
923  dec31ly.tm_year--;
924  dec31ly.tm_mon = 11;
925  dec31ly.tm_mday = 31;
926  dec31ly.tm_wday = (jan1day == 0) ? 6 : jan1day - 1;
927  dec31ly.tm_yday = 364 + isleap(dec31ly.tm_year + 1900L);
928  weeknum = iso8601wknum(& dec31ly);
929 #endif
930  }
931  break;
932  }
933 
934  if (timeptr->tm_mon == 11) {
935  /*
936  * The last week of the year
937  * can be in week 1 of next year.
938  * Sigh.
939  *
940  * This can only happen if
941  * M T W
942  * 29 30 31
943  * 30 31
944  * 31
945  */
946  int wday, mday;
947 
948  wday = timeptr->tm_wday;
949  mday = timeptr->tm_mday;
950  if ( (wday == 1 && (mday >= 29 && mday <= 31))
951  || (wday == 2 && (mday == 30 || mday == 31))
952  || (wday == 3 && mday == 31))
953  weeknum = 1;
954  }
955 
956  return weeknum;
957 }
958 
959 static int
960 iso8601wknum_v(const struct vtm *vtm)
961 {
962  struct tm tm;
963  vtm2tm_noyear(vtm, &tm);
964  return iso8601wknum(&tm);
965 }
966 
967 #endif
968 
969 /* weeknumber --- figure how many weeks into the year */
970 
971 /* With thanks and tip of the hatlo to ado@elsie.nci.nih.gov */
972 
973 #ifndef __STDC__
974 static int
975 weeknumber(timeptr, firstweekday)
976 const struct tm *timeptr;
977 int firstweekday;
978 #else
979 static int
980 weeknumber(const struct tm *timeptr, int firstweekday)
981 #endif
982 {
983  int wday = timeptr->tm_wday;
984  int ret;
985 
986  if (firstweekday == 1) {
987  if (wday == 0) /* sunday */
988  wday = 6;
989  else
990  wday--;
991  }
992  ret = ((timeptr->tm_yday + 7 - wday) / 7);
993  if (ret < 0)
994  ret = 0;
995  return ret;
996 }
997 
998 static int
999 weeknumber_v(const struct vtm *vtm, int firstweekday)
1000 {
1001  struct tm tm;
1002  vtm2tm_noyear(vtm, &tm);
1003  return weeknumber(&tm, firstweekday);
1004 }
1005 
1006 #if 0
1007 /* ADR --- I'm loathe to mess with ado's code ... */
1008 
1009 Date: Wed, 24 Apr 91 20:54:08 MDT
1010 From: Michal Jaegermann <audfax!emory!vm.ucs.UAlberta.CA!NTOMCZAK>
1011 To: arnold@audiofax.com
1012 
1013 Hi Arnold,
1014 in a process of fixing of strftime() in libraries on Atari ST I grabbed
1015 some pieces of code from your own strftime. When doing that it came
1016 to mind that your weeknumber() function compiles a little bit nicer
1017 in the following form:
1018 /*
1019  * firstweekday is 0 if starting in Sunday, non-zero if in Monday
1020  */
1021 {
1022  return (timeptr->tm_yday - timeptr->tm_wday +
1023  (firstweekday ? (timeptr->tm_wday ? 8 : 1) : 7)) / 7;
1024 }
1025 How nicer it depends on a compiler, of course, but always a tiny bit.
1026 
1027  Cheers,
1028  Michal
1029  ntomczak@vm.ucs.ualberta.ca
1030 #endif
1031 
1032 #ifdef TEST_STRFTIME
1033 
1034 /*
1035  * NAME:
1036  * tst
1037  *
1038  * SYNOPSIS:
1039  * tst
1040  *
1041  * DESCRIPTION:
1042  * "tst" is a test driver for the function "strftime".
1043  *
1044  * OPTIONS:
1045  * None.
1046  *
1047  * AUTHOR:
1048  * Karl Vogel
1049  * Control Data Systems, Inc.
1050  * vogelke@c-17igp.wpafb.af.mil
1051  *
1052  * BUGS:
1053  * None noticed yet.
1054  *
1055  * COMPILE:
1056  * cc -o tst -DTEST_STRFTIME strftime.c
1057  */
1058 
1059 /* ADR: I reformatted this to my liking, and deleted some unneeded code. */
1060 
1061 #ifndef NULL
1062 #include <stdio.h>
1063 #endif
1064 #include <sys/time.h>
1065 #include <string.h>
1066 
1067 #define MAXTIME 132
1068 
1069 /*
1070  * Array of time formats.
1071  */
1072 
1073 static char *array[] =
1074 {
1075  "(%%A) full weekday name, var length (Sunday..Saturday) %A",
1076  "(%%B) full month name, var length (January..December) %B",
1077  "(%%C) Century %C",
1078  "(%%D) date (%%m/%%d/%%y) %D",
1079  "(%%E) Locale extensions (ignored) %E",
1080  "(%%H) hour (24-hour clock, 00..23) %H",
1081  "(%%I) hour (12-hour clock, 01..12) %I",
1082  "(%%M) minute (00..59) %M",
1083  "(%%O) Locale extensions (ignored) %O",
1084  "(%%R) time, 24-hour (%%H:%%M) %R",
1085  "(%%S) second (00..60) %S",
1086  "(%%T) time, 24-hour (%%H:%%M:%%S) %T",
1087  "(%%U) week of year, Sunday as first day of week (00..53) %U",
1088  "(%%V) week of year according to ISO 8601 %V",
1089  "(%%W) week of year, Monday as first day of week (00..53) %W",
1090  "(%%X) appropriate locale time representation (%H:%M:%S) %X",
1091  "(%%Y) year with century (1970...) %Y",
1092  "(%%Z) timezone (EDT), or blank if timezone not determinable %Z",
1093  "(%%a) locale's abbreviated weekday name (Sun..Sat) %a",
1094  "(%%b) locale's abbreviated month name (Jan..Dec) %b",
1095  "(%%c) full date (Sat Nov 4 12:02:33 1989)%n%t%t%t %c",
1096  "(%%d) day of the month (01..31) %d",
1097  "(%%e) day of the month, blank-padded ( 1..31) %e",
1098  "(%%h) should be same as (%%b) %h",
1099  "(%%j) day of the year (001..366) %j",
1100  "(%%k) hour, 24-hour clock, blank pad ( 0..23) %k",
1101  "(%%l) hour, 12-hour clock, blank pad ( 1..12) %l",
1102  "(%%m) month (01..12) %m",
1103  "(%%p) locale's AM or PM based on 12-hour clock %p",
1104  "(%%r) time, 12-hour (same as %%I:%%M:%%S %%p) %r",
1105  "(%%u) ISO 8601: Weekday as decimal number [1 (Monday) - 7] %u",
1106  "(%%v) VMS date (dd-bbb-YYYY) %v",
1107  "(%%w) day of week (0..6, Sunday == 0) %w",
1108  "(%%x) appropriate locale date representation %x",
1109  "(%%y) last two digits of year (00..99) %y",
1110  "(%%z) timezone offset east of GMT as HHMM (e.g. -0500) %z",
1111  (char *) NULL
1112 };
1113 
1114 /* main routine. */
1115 
1116 int
1117 main(argc, argv)
1118 int argc;
1119 char **argv;
1120 {
1121  long time();
1122 
1123  char *next;
1124  char string[MAXTIME];
1125 
1126  int k;
1127  int length;
1128 
1129  struct tm *tm;
1130 
1131  long clock;
1132 
1133  /* Call the function. */
1134 
1135  clock = time((long *) 0);
1136  tm = localtime(&clock);
1137 
1138  for (k = 0; next = array[k]; k++) {
1139  length = strftime(string, MAXTIME, next, tm);
1140  printf("%s\n", string);
1141  }
1142 
1143  exit(0);
1144 }
1145 #endif /* TEST_STRFTIME */
1146