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