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