Ruby 2.1.5p273(2014-11-13revision48405)

- Main Page
- Modules
- Data Structures
- Files

- File List
- Globals

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