Ruby  2.4.2p198(2017-09-14revision59899)
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
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  } else {
547  sign = +1;
548  }
549  switch (colons) {
550  case 0: /* %z -> +hhmm */
551  precision = precision <= 5 ? 2 : precision-3;
552  NEEDS(precision + 3);
553  break;
554 
555  case 1: /* %:z -> +hh:mm */
556  precision = precision <= 6 ? 2 : precision-4;
557  NEEDS(precision + 4);
558  break;
559 
560  case 2: /* %::z -> +hh:mm:ss */
561  precision = precision <= 9 ? 2 : precision-7;
562  NEEDS(precision + 7);
563  break;
564 
565  case 3: /* %:::z -> +hh[:mm[:ss]] */
566  if (off % 3600 == 0) {
567  precision = precision <= 3 ? 2 : precision-1;
568  NEEDS(precision + 3);
569  }
570  else if (off % 60 == 0) {
571  precision = precision <= 6 ? 2 : precision-4;
572  NEEDS(precision + 4);
573  }
574  else {
575  precision = precision <= 9 ? 2 : precision-7;
576  NEEDS(precision + 9);
577  }
578  break;
579 
580  default:
581  format--;
582  goto unknown;
583  }
584  i = snprintf(s, endp - s, (padding == ' ' ? "%+*ld" : "%+.*ld"),
585  precision + (padding == ' '), sign * (off / 3600));
586  if (i < 0) goto err;
587  if (sign < 0 && off < 3600) {
588  *(padding == ' ' ? s + i - 2 : s) = '-';
589  }
590  s += i;
591  off = off % 3600;
592  if (colons == 3 && off == 0)
593  continue;
594  if (1 <= colons)
595  *s++ = ':';
596  i = snprintf(s, endp - s, "%02d", (int)(off / 60));
597  if (i < 0) goto err;
598  s += i;
599  off = off % 60;
600  if (colons == 3 && off == 0)
601  continue;
602  if (2 <= colons) {
603  *s++ = ':';
604  i = snprintf(s, endp - s, "%02d", (int)off);
605  if (i < 0) goto err;
606  s += i;
607  }
608  continue;
609 #endif /* MAILHEADER_EXT */
610 
611  case 'Z': /* time zone name or abbreviation */
612  if (flags & BIT_OF(CHCASE)) {
613  flags &= ~(BIT_OF(UPPER)|BIT_OF(CHCASE));
614  flags |= BIT_OF(LOWER);
615  }
616  if (gmt) {
617  i = 3;
618  tp = "UTC";
619  break;
620  }
621  if (vtm->zone == NULL) {
622  i = 0;
623  }
624  else {
625  tp = vtm->zone;
626  if (enc) {
627  for (i = 0; i < TBUFSIZE && tp[i]; i++) {
628  if ((unsigned char)tp[i] > 0x7F) {
630  i = strlcpy(tbuf, RSTRING_PTR(str), TBUFSIZE);
631  tp = tbuf;
632  break;
633  }
634  }
635  }
636  else
637  i = strlen(tp);
638  }
639  break;
640 
641 #ifdef SYSV_EXT
642  case 'n': /* same as \n */
643  FILL_PADDING(1);
644  *s++ = '\n';
645  continue;
646 
647  case 't': /* same as \t */
648  FILL_PADDING(1);
649  *s++ = '\t';
650  continue;
651 
652  case 'D': /* date as %m/%d/%y */
653  STRFTIME("%m/%d/%y");
654  continue;
655 
656  case 'e': /* day of month, blank padded */
657  FMT(' ', 2, "d", range(1, vtm->mday, 31));
658  continue;
659 
660  case 'r': /* time as %I:%M:%S %p */
661  STRFTIME("%I:%M:%S %p");
662  continue;
663 
664  case 'R': /* time as %H:%M */
665  STRFTIME("%H:%M");
666  continue;
667 
668  case 'T': /* time as %H:%M:%S */
669  STRFTIME("%H:%M:%S");
670  continue;
671 #endif
672 
673 #ifdef SUNOS_EXT
674  case 'k': /* hour, 24-hour clock, blank pad */
675  i = range(0, vtm->hour, 23);
676  FMT(' ', 2, "d", (int)i);
677  continue;
678 
679  case 'l': /* hour, 12-hour clock, 1 - 12, blank pad */
680  i = range(0, vtm->hour, 23);
681  if (i == 0)
682  i = 12;
683  else if (i > 12)
684  i -= 12;
685  FMT(' ', 2, "d", (int)i);
686  continue;
687 #endif
688 
689 
690 #ifdef VMS_EXT
691  case 'v': /* date as dd-bbb-YYYY */
692  STRFTIME("%e-%^b-%4Y");
693  continue;
694 #endif
695 
696 
697 #ifdef POSIX2_DATE
698  case 'C':
699  FMTV('0', 2, "d", div(vtm->year, INT2FIX(100)));
700  continue;
701 
702  case 'E':
703  /* POSIX locale extensions, ignored for now */
704  if (!format[1] || !strchr("cCxXyY", format[1]))
705  goto unknown;
706  goto again;
707  case 'O':
708  /* POSIX locale extensions, ignored for now */
709  if (!format[1] || !strchr("deHkIlmMSuUVwWy", format[1]))
710  goto unknown;
711  goto again;
712 
713  case 'V': /* week of year according ISO 8601 */
714  FMT('0', 2, "d", iso8601wknum_v(vtm));
715  continue;
716 
717  case 'u':
718  /* ISO 8601: Weekday as a decimal number [1 (Monday) - 7] */
719  FMT('0', 1, "d", vtm->wday == 0 ? 7 : vtm->wday);
720  continue;
721 #endif /* POSIX2_DATE */
722 
723 #ifdef ISO_DATE_EXT
724  case 'G':
725  case 'g':
726  /*
727  * Year of ISO week.
728  *
729  * If it's December but the ISO week number is one,
730  * that week is in next year.
731  * If it's January but the ISO week number is 52 or
732  * 53, that week is in last year.
733  * Otherwise, it's this year.
734  */
735  {
736  VALUE yv = vtm->year;
737  w = iso8601wknum_v(vtm);
738  if (vtm->mon == 12 && w == 1)
739  yv = add(yv, INT2FIX(1));
740  else if (vtm->mon == 1 && w >= 52)
741  yv = sub(yv, INT2FIX(1));
742 
743  if (*format == 'G') {
744  if (FIXNUM_P(yv)) {
745  const long y = FIX2LONG(yv);
746  FMT('0', 0 <= y ? 4 : 5, "ld", y);
747  }
748  else {
749  FMTV('0', 4, "d", yv);
750  }
751  }
752  else {
753  yv = mod(yv, INT2FIX(100));
754  y = FIX2LONG(yv);
755  FMT('0', 2, "ld", y);
756  }
757  continue;
758  }
759 
760 #endif /* ISO_DATE_EXT */
761 
762 
763  case 'L':
764  w = 3;
765  goto subsec;
766 
767  case 'N':
768  /*
769  * fractional second digits. default is 9 digits
770  * (nanosecond).
771  *
772  * %3N millisecond (3 digits)
773  * %6N microsecond (6 digits)
774  * %9N nanosecond (9 digits)
775  */
776  w = 9;
777  subsec:
778  if (precision <= 0) {
779  precision = w;
780  }
781  NEEDS(precision);
782 
783  if (ts) {
784  long subsec = ts->tv_nsec;
785  if (9 < precision) {
786  snprintf(s, endp - s, "%09ld", subsec);
787  memset(s+9, '0', precision-9);
788  s += precision;
789  }
790  else {
791  int i;
792  for (i = 0; i < 9-precision; i++)
793  subsec /= 10;
794  snprintf(s, endp - s, "%0*ld", precision, subsec);
795  s += precision;
796  }
797  }
798  else {
799  VALUE subsec = mod(timev, INT2FIX(1));
800  int ww;
801  long n;
802 
803  ww = precision;
804  while (9 <= ww) {
805  subsec = mul(subsec, INT2FIX(1000000000));
806  ww -= 9;
807  }
808  n = 1;
809  for (; 0 < ww; ww--)
810  n *= 10;
811  if (n != 1)
812  subsec = mul(subsec, INT2FIX(n));
813  subsec = div(subsec, INT2FIX(1));
814 
815  if (FIXNUM_P(subsec)) {
816  (void)snprintf(s, endp - s, "%0*ld", precision, FIX2LONG(subsec));
817  s += precision;
818  }
819  else {
820  VALUE args[2], result;
821  args[0] = INT2FIX(precision);
822  args[1] = subsec;
823  result = rb_str_format(2, args, rb_str_new2("%0*d"));
824  (void)strlcpy(s, StringValueCStr(result), endp-s);
825  s += precision;
826  }
827  }
828  continue;
829 
830  case 'F': /* Equivalent to %Y-%m-%d */
831  STRFTIME("%Y-%m-%d");
832  continue;
833 
834  case '-':
835  FLAG_FOUND();
836  flags |= BIT_OF(LEFT);
837  padding = precision = 0;
838  goto again;
839 
840  case '^':
841  FLAG_FOUND();
842  flags |= BIT_OF(UPPER);
843  goto again;
844 
845  case '#':
846  FLAG_FOUND();
847  flags |= BIT_OF(CHCASE);
848  goto again;
849 
850  case '_':
851  FLAG_FOUND();
852  padding = ' ';
853  goto again;
854 
855  case ':':
856  for (colons = 1; colons <= 3; ++colons) {
857  if (format+colons >= format_end) goto unknown;
858  if (format[colons] == 'z') break;
859  if (format[colons] != ':') goto unknown;
860  }
861  format += colons - 1;
862  goto again;
863 
864  case '0':
865  padding = '0';
866  case '1': case '2': case '3': case '4':
867  case '5': case '6': case '7': case '8': case '9':
868  {
869  size_t n;
870  int ov;
871  unsigned long u = ruby_scan_digits(format, format_end-format, 10, &n, &ov);
872  if (ov || u > INT_MAX) goto unknown;
873  precision = (int)u;
874  format += n - 1;
875  goto again;
876  }
877 
878  default:
879  unknown:
880  i = format - sp + 1;
881  tp = sp;
882  precision = -1;
883  flags = 0;
884  padding = 0;
885  colons = 0;
886  break;
887  }
888  if (i) {
889  FILL_PADDING(i);
890  memcpy(s, tp, i);
891  s = case_conv(s, i, flags);
892  }
893  }
894  if (format != format_end) {
895  return 0;
896  }
897  len = s - start;
898  rb_str_set_len(ftime, len);
899  rb_str_resize(ftime, len);
900  return ftime;
901 }
902 
903 static size_t
904 strftime_size_limit(size_t format_len)
905 {
906  size_t limit = format_len * (1*1024*1024);
907  if (limit < format_len) limit = format_len;
908  else if (limit < 1024) limit = 1024;
909  return limit;
910 }
911 
912 VALUE
913 rb_strftime(const char *format, size_t format_len,
914  rb_encoding *enc, const struct vtm *vtm, VALUE timev, int gmt)
915 {
916  VALUE result = rb_enc_str_new(0, 0, enc);
917  return rb_strftime_with_timespec(result, format, format_len, enc,
918  vtm, timev, NULL, gmt,
919  strftime_size_limit(format_len));
920 }
921 
922 VALUE
923 rb_strftime_timespec(const char *format, size_t format_len,
924  rb_encoding *enc, const struct vtm *vtm, struct timespec *ts, int gmt)
925 {
926  VALUE result = rb_enc_str_new(0, 0, enc);
927  return rb_strftime_with_timespec(result, format, format_len, enc,
928  vtm, Qnil, ts, gmt,
929  strftime_size_limit(format_len));
930 }
931 
932 #if 0
933 VALUE
934 rb_strftime_limit(const char *format, size_t format_len,
935  rb_encoding *enc, const struct vtm *vtm, struct timespec *ts,
936  int gmt, size_t maxsize)
937 {
938  VALUE result = rb_enc_str_new(0, 0, enc);
939  return rb_strftime_with_timespec(result, format, format_len, enc,
940  vtm, Qnil, ts, gmt, maxsize);
941 }
942 #endif
943 
944 /* isleap --- is a year a leap year? */
945 
946 static int
947 isleap(long year)
948 {
949  return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
950 }
951 
952 
953 static void
954 vtm2tm_noyear(const struct vtm *vtm, struct tm *result)
955 {
956  struct tm tm;
957 
958  /* for isleap() in iso8601wknum. +100 is -1900 (mod 400). */
959  tm.tm_year = FIX2INT(mod(vtm->year, INT2FIX(400))) + 100;
960 
961  tm.tm_mon = vtm->mon-1;
962  tm.tm_mday = vtm->mday;
963  tm.tm_hour = vtm->hour;
964  tm.tm_min = vtm->min;
965  tm.tm_sec = vtm->sec;
966  tm.tm_wday = vtm->wday;
967  tm.tm_yday = vtm->yday-1;
968  tm.tm_isdst = vtm->isdst;
969 #if defined(HAVE_STRUCT_TM_TM_GMTOFF)
970  tm.tm_gmtoff = NUM2LONG(vtm->utc_offset);
971 #endif
972 #if defined(HAVE_TM_ZONE)
973  tm.tm_zone = (char *)vtm->zone;
974 #endif
975  *result = tm;
976 }
977 
978 #ifdef POSIX2_DATE
979 /* iso8601wknum --- compute week number according to ISO 8601 */
980 
981 static int
982 iso8601wknum(const struct tm *timeptr)
983 {
984  /*
985  * From 1003.2:
986  * If the week (Monday to Sunday) containing January 1
987  * has four or more days in the new year, then it is week 1;
988  * otherwise it is the highest numbered week of the previous
989  * year (52 or 53), and the next week is week 1.
990  *
991  * ADR: This means if Jan 1 was Monday through Thursday,
992  * it was week 1, otherwise week 52 or 53.
993  *
994  * XPG4 erroneously included POSIX.2 rationale text in the
995  * main body of the standard. Thus it requires week 53.
996  */
997 
998  int weeknum, jan1day;
999 
1000  /* get week number, Monday as first day of the week */
1001  weeknum = weeknumber(timeptr, 1);
1002 
1003  /*
1004  * With thanks and tip of the hatlo to tml@tik.vtt.fi
1005  *
1006  * What day of the week does January 1 fall on?
1007  * We know that
1008  * (timeptr->tm_yday - jan1.tm_yday) MOD 7 ==
1009  * (timeptr->tm_wday - jan1.tm_wday) MOD 7
1010  * and that
1011  * jan1.tm_yday == 0
1012  * and that
1013  * timeptr->tm_wday MOD 7 == timeptr->tm_wday
1014  * from which it follows that. . .
1015  */
1016  jan1day = timeptr->tm_wday - (timeptr->tm_yday % 7);
1017  if (jan1day < 0)
1018  jan1day += 7;
1019 
1020  /*
1021  * If Jan 1 was a Monday through Thursday, it was in
1022  * week 1. Otherwise it was last year's highest week, which is
1023  * this year's week 0.
1024  *
1025  * What does that mean?
1026  * If Jan 1 was Monday, the week number is exactly right, it can
1027  * never be 0.
1028  * If it was Tuesday through Thursday, the weeknumber is one
1029  * less than it should be, so we add one.
1030  * Otherwise, Friday, Saturday or Sunday, the week number is
1031  * OK, but if it is 0, it needs to be 52 or 53.
1032  */
1033  switch (jan1day) {
1034  case 1: /* Monday */
1035  break;
1036  case 2: /* Tuesday */
1037  case 3: /* Wednesday */
1038  case 4: /* Thursday */
1039  weeknum++;
1040  break;
1041  case 5: /* Friday */
1042  case 6: /* Saturday */
1043  case 0: /* Sunday */
1044  if (weeknum == 0) {
1045 #ifdef USE_BROKEN_XPG4
1046  /* XPG4 (as of March 1994) says 53 unconditionally */
1047  weeknum = 53;
1048 #else
1049  /* get week number of last week of last year */
1050  struct tm dec31ly; /* 12/31 last year */
1051  dec31ly = *timeptr;
1052  dec31ly.tm_year--;
1053  dec31ly.tm_mon = 11;
1054  dec31ly.tm_mday = 31;
1055  dec31ly.tm_wday = (jan1day == 0) ? 6 : jan1day - 1;
1056  dec31ly.tm_yday = 364 + isleap(dec31ly.tm_year + 1900L);
1057  weeknum = iso8601wknum(& dec31ly);
1058 #endif
1059  }
1060  break;
1061  }
1062 
1063  if (timeptr->tm_mon == 11) {
1064  /*
1065  * The last week of the year
1066  * can be in week 1 of next year.
1067  * Sigh.
1068  *
1069  * This can only happen if
1070  * M T W
1071  * 29 30 31
1072  * 30 31
1073  * 31
1074  */
1075  int wday, mday;
1076 
1077  wday = timeptr->tm_wday;
1078  mday = timeptr->tm_mday;
1079  if ( (wday == 1 && (mday >= 29 && mday <= 31))
1080  || (wday == 2 && (mday == 30 || mday == 31))
1081  || (wday == 3 && mday == 31))
1082  weeknum = 1;
1083  }
1084 
1085  return weeknum;
1086 }
1087 
1088 static int
1089 iso8601wknum_v(const struct vtm *vtm)
1090 {
1091  struct tm tm;
1092  vtm2tm_noyear(vtm, &tm);
1093  return iso8601wknum(&tm);
1094 }
1095 
1096 #endif
1097 
1098 /* weeknumber --- figure how many weeks into the year */
1099 
1100 /* With thanks and tip of the hatlo to ado@elsie.nci.nih.gov */
1101 
1102 static int
1103 weeknumber(const struct tm *timeptr, int firstweekday)
1104 {
1105  int wday = timeptr->tm_wday;
1106  int ret;
1107 
1108  if (firstweekday == 1) {
1109  if (wday == 0) /* sunday */
1110  wday = 6;
1111  else
1112  wday--;
1113  }
1114  ret = ((timeptr->tm_yday + 7 - wday) / 7);
1115  if (ret < 0)
1116  ret = 0;
1117  return ret;
1118 }
1119 
1120 static int
1121 weeknumber_v(const struct vtm *vtm, int firstweekday)
1122 {
1123  struct tm tm;
1124  vtm2tm_noyear(vtm, &tm);
1125  return weeknumber(&tm, firstweekday);
1126 }
1127 
1128 #if 0
1129 /* ADR --- I'm loathe to mess with ado's code ... */
1130 
1131 Date: Wed, 24 Apr 91 20:54:08 MDT
1132 From: Michal Jaegermann <audfax!emory!vm.ucs.UAlberta.CA!NTOMCZAK>
1133 To: arnold@audiofax.com
1134 
1135 Hi Arnold,
1136 in a process of fixing of strftime() in libraries on Atari ST I grabbed
1137 some pieces of code from your own strftime. When doing that it came
1138 to mind that your weeknumber() function compiles a little bit nicer
1139 in the following form:
1140 /*
1141  * firstweekday is 0 if starting in Sunday, non-zero if in Monday
1142  */
1143 {
1144  return (timeptr->tm_yday - timeptr->tm_wday +
1145  (firstweekday ? (timeptr->tm_wday ? 8 : 1) : 7)) / 7;
1146 }
1147 How nicer it depends on a compiler, of course, but always a tiny bit.
1148 
1149  Cheers,
1150  Michal
1151  ntomczak@vm.ucs.ualberta.ca
1152 #endif
1153 
1154 #ifdef TEST_STRFTIME
1155 
1156 /*
1157  * NAME:
1158  * tst
1159  *
1160  * SYNOPSIS:
1161  * tst
1162  *
1163  * DESCRIPTION:
1164  * "tst" is a test driver for the function "strftime".
1165  *
1166  * OPTIONS:
1167  * None.
1168  *
1169  * AUTHOR:
1170  * Karl Vogel
1171  * Control Data Systems, Inc.
1172  * vogelke@c-17igp.wpafb.af.mil
1173  *
1174  * BUGS:
1175  * None noticed yet.
1176  *
1177  * COMPILE:
1178  * cc -o tst -DTEST_STRFTIME strftime.c
1179  */
1180 
1181 /* ADR: I reformatted this to my liking, and deleted some unneeded code. */
1182 
1183 #ifndef NULL
1184 #include <stdio.h>
1185 #endif
1186 #include <sys/time.h>
1187 #include <string.h>
1188 
1189 #define MAXTIME 132
1190 
1191 /*
1192  * Array of time formats.
1193  */
1194 
1195 static char *array[] =
1196 {
1197  "(%%A) full weekday name, var length (Sunday..Saturday) %A",
1198  "(%%B) full month name, var length (January..December) %B",
1199  "(%%C) Century %C",
1200  "(%%D) date (%%m/%%d/%%y) %D",
1201  "(%%E) Locale extensions (ignored) %E",
1202  "(%%H) hour (24-hour clock, 00..23) %H",
1203  "(%%I) hour (12-hour clock, 01..12) %I",
1204  "(%%M) minute (00..59) %M",
1205  "(%%O) Locale extensions (ignored) %O",
1206  "(%%R) time, 24-hour (%%H:%%M) %R",
1207  "(%%S) second (00..60) %S",
1208  "(%%T) time, 24-hour (%%H:%%M:%%S) %T",
1209  "(%%U) week of year, Sunday as first day of week (00..53) %U",
1210  "(%%V) week of year according to ISO 8601 %V",
1211  "(%%W) week of year, Monday as first day of week (00..53) %W",
1212  "(%%X) appropriate locale time representation (%H:%M:%S) %X",
1213  "(%%Y) year with century (1970...) %Y",
1214  "(%%Z) timezone (EDT), or blank if timezone not determinable %Z",
1215  "(%%a) locale's abbreviated weekday name (Sun..Sat) %a",
1216  "(%%b) locale's abbreviated month name (Jan..Dec) %b",
1217  "(%%c) full date (Sat Nov 4 12:02:33 1989)%n%t%t%t %c",
1218  "(%%d) day of the month (01..31) %d",
1219  "(%%e) day of the month, blank-padded ( 1..31) %e",
1220  "(%%h) should be same as (%%b) %h",
1221  "(%%j) day of the year (001..366) %j",
1222  "(%%k) hour, 24-hour clock, blank pad ( 0..23) %k",
1223  "(%%l) hour, 12-hour clock, blank pad ( 1..12) %l",
1224  "(%%m) month (01..12) %m",
1225  "(%%p) locale's AM or PM based on 12-hour clock %p",
1226  "(%%r) time, 12-hour (same as %%I:%%M:%%S %%p) %r",
1227  "(%%u) ISO 8601: Weekday as decimal number [1 (Monday) - 7] %u",
1228  "(%%v) VMS date (dd-bbb-YYYY) %v",
1229  "(%%w) day of week (0..6, Sunday == 0) %w",
1230  "(%%x) appropriate locale date representation %x",
1231  "(%%y) last two digits of year (00..99) %y",
1232  "(%%z) timezone offset east of GMT as HHMM (e.g. -0500) %z",
1233  (char *) NULL
1234 };
1235 
1236 /* main routine. */
1237 
1238 int
1239 main(int argc, char **argv)
1240 {
1241  long time();
1242 
1243  char *next;
1244  char string[MAXTIME];
1245 
1246  int k;
1247  int length;
1248 
1249  struct tm *tm;
1250 
1251  long clock;
1252 
1253  /* Call the function. */
1254 
1255  clock = time((long *) 0);
1256  tm = localtime(&clock);
1257 
1258  for (k = 0; next = array[k]; k++) {
1259  length = strftime(string, MAXTIME, next, tm);
1260  printf("%s\n", string);
1261  }
1262 
1263  exit(0);
1264 }
1265 #endif /* TEST_STRFTIME */
#define NEEDS(n)
size_t strlen(const char *)
#define NUM2INT(x)
Definition: ruby.h:684
static int max(int a, int b)
Definition: strftime.c:142
static int isleap(long year)
Definition: strftime.c:947
static int iso8601wknum_v(const struct vtm *vtm)
Definition: strftime.c:1089
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:923
#define add(x, y)
Definition: strftime.c:151
VALUE rb_funcall(VALUE, ID, int,...)
Calls a method.
Definition: vm_eval.c:821
void rb_str_set_len(VALUE, long)
Definition: string.c:2545
VALUE rb_strftime(const char *format, size_t format_len, rb_encoding *enc, const struct vtm *vtm, VALUE timev, int gmt)
Definition: strftime.c:913
#define mod(x, y)
Definition: strftime.c:156
int main(void)
Definition: closure_fn0.c:49
#define adddecl(stuff)
Definition: strftime.c:95
static VALUE rb_strftime_with_timespec(VALUE ftime, const char *format, size_t format_len, rb_encoding *enc, const struct vtm *vtm, VALUE timev, struct timespec *ts, int gmt, size_t maxsize)
Definition: strftime.c:228
#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:884
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()
static void buffer_size_check(const char *s, const char *format_end, size_t format_len, rb_encoding *enc)
Definition: strftime.c:182
#define snprintf
Definition: subst.h:6
long tv_nsec
Definition: missing.h:62
#define TOUPPER(c)
Definition: ruby.h:2132
#define div(x, y)
Definition: strftime.c:155
#define range(low, item, hi)
int argc
Definition: ruby.c:183
#define realloc
Definition: ripper.c:117
VALUE rb_Integer(VALUE)
Definition: object.c:2736
#define T_BIGNUM
Definition: ruby.h:501
#define ISUPPER(c)
Definition: ruby.h:2125
#define rb_str_new2
Definition: intern.h:857
int err
Definition: win32.c:135
#define ISLOWER(c)
Definition: ruby.h:2126
VALUE rb_big2str(VALUE x, int base)
Definition: bignum.c:5041
VALUE rb_str_resize(VALUE, long)
Definition: string.c:2562
#define RSTRING_LEN(str)
Definition: ruby.h:978
static int weeknumber()
VALUE rb_str_format(int, const VALUE *, VALUE)
Definition: sprintf.c:461
#define malloc
Definition: ripper.c:116
void rb_str_modify_expand(VALUE, long)
Definition: string.c:1988
rb_encoding * rb_usascii_encoding(void)
Definition: encoding.c:1335
#define Qnil
Definition: ruby.h:438
#define TBUFSIZE
Definition: strftime.c:160
unsigned long VALUE
Definition: ruby.h:85
rb_encoding * rb_locale_encoding(void)
Definition: encoding.c:1370
static VALUE result
Definition: nkf.c:40
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:770
register unsigned int len
Definition: zonetab.h:51
#define StringValueCStr(v)
Definition: ruby.h:571
#define getenv(name)
Definition: win32.c:71
static void vtm2tm_noyear(const struct vtm *vtm, struct tm *result)
Definition: strftime.c:954
#define RSTRING_PTR(str)
Definition: ruby.h:982
#define ECONV_UNDEF_REPLACE
Definition: encoding.h:390
static int weeknumber_v(const struct vtm *vtm, int firstweekday)
Definition: strftime.c:1121
#define sub(x, y)
Definition: strftime.c:152
#define INT2FIX(i)
Definition: ruby.h:232
static char * case_conv(char *s, ptrdiff_t i, int flags)
Definition: strftime.c:194
#define mul(x, y)
Definition: strftime.c:153
static int iso8601wknum(const struct tm *timeptr)
Definition: strftime.c:982
void rb_syserr_fail_str(int e, VALUE mesg)
Definition: error.c:2320
static char * resize_buffer(VALUE ftime, char *s, const char **start, const char **endp, ptrdiff_t n, size_t maxsize)
Definition: strftime.c:164
size_t rb_str_capacity(VALUE str)
Definition: string.c:674
#define FMT(def_pad, def_prec, fmt, val)
#define TOLOWER(c)
Definition: ruby.h:2133
static size_t strftime_size_limit(size_t format_len)
Definition: strftime.c:904
#define STDC_HEADERS
Definition: fficonfig.h:22
VALUE rb_enc_str_new(const char *, long, rb_encoding *)
Definition: string.c:758
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 memcpy(d, s, n)
Definition: ffi_common.h:55
#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
static VALUE format_value(VALUE val, int base)
Definition: strftime.c:215
char ** argv
Definition: ruby.c:184
#define L(x)
Definition: asm.h:125