Ruby 4.0.9p0 (2026-10-23 revision 3e93b23afcec3433f6aecc34b5d832799d754238)
strftime.c
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/internal/config.h"
51
52#ifndef GAWK
53#include <stdio.h>
54#include <ctype.h>
55#include <string.h>
56#include <time.h>
57#include <sys/types.h>
58#include <errno.h>
59#endif
60#if defined(TM_IN_SYS_TIME) || !defined(GAWK)
61#include <sys/types.h>
62#ifdef HAVE_SYS_TIME_H
63#include <sys/time.h>
64#endif
65#endif
66#include <math.h>
67
68#include "internal.h"
69#include "internal/encoding.h"
70#include "internal/string.h"
71#include "internal/vm.h"
72#include "ruby/encoding.h"
73#include "ruby/ruby.h"
74#include "ruby/util.h"
75#include "timev.h"
76
77/* defaults: season to taste */
78#define SYSV_EXT 1 /* stuff in System V ascftime routine */
79#define SUNOS_EXT 1 /* stuff in SunOS strftime routine */
80#define POSIX2_DATE 1 /* stuff in Posix 1003.2 date command */
81#define VMS_EXT 1 /* include %v for VMS date format */
82#define MAILHEADER_EXT 1 /* add %z for HHMM format */
83#define ISO_DATE_EXT 1 /* %G and %g for year of ISO week */
84
85#if defined(ISO_DATE_EXT)
86#if ! defined(POSIX2_DATE)
87#define POSIX2_DATE 1
88#endif
89#endif
90
91#if defined(POSIX2_DATE)
92#if ! defined(SYSV_EXT)
93#define SYSV_EXT 1
94#endif
95#if ! defined(SUNOS_EXT)
96#define SUNOS_EXT 1
97#endif
98#endif
99
100#if defined(POSIX2_DATE)
101#define adddecl(stuff) stuff
102#else
103#define adddecl(stuff)
104#endif
105
106#undef strchr /* avoid AIX weirdness */
107
108#if !defined __STDC__ && !defined _WIN32
109#define const /**/
110static int weeknumber();
111adddecl(static int iso8601wknum();)
112static int weeknumber_v();
113adddecl(static int iso8601wknum_v();)
114#else
115static int weeknumber(const struct tm *timeptr, int firstweekday);
116adddecl(static int iso8601wknum(const struct tm *timeptr);)
117static int weeknumber_v(const struct vtm *vtm, int firstweekday);
118adddecl(static int iso8601wknum_v(const struct vtm *vtm);)
119#endif
120
121#ifdef STDC_HEADERS
122#include <stdlib.h>
123#include <string.h>
124#else
125extern void *malloc();
126extern void *realloc();
127extern char *getenv();
128extern char *strchr();
129#endif
130
131#define range(low, item, hi) max((low), min((item), (hi)))
132
133#undef min /* just in case */
134
135/* min --- return minimum of two numbers */
136
137static inline int
138min(int a, int b)
139{
140 return (a < b ? a : b);
141}
142
143#undef max /* also, just in case */
144
145/* max --- return maximum of two numbers */
146
147static inline int
148max(int a, int b)
149{
150 return (a > b ? a : b);
151}
152
153#ifdef NO_STRING_LITERAL_CONCATENATION
154#error No string literal concatenation
155#endif
156
157#define add(x,y) (rb_funcall((x), '+', 1, (y)))
158#define sub(x,y) (rb_funcall((x), '-', 1, (y)))
159#define mul(x,y) (rb_funcall((x), '*', 1, (y)))
160#define quo(x,y) (rb_funcall((x), rb_intern("quo"), 1, (y)))
161#define div(x,y) (rb_funcall((x), rb_intern("div"), 1, (y)))
162#define mod(x,y) (rb_funcall((x), '%', 1, (y)))
163
164/* strftime --- produce formatted time */
165
166enum {LEFT, CHCASE, LOWER, UPPER};
167#define BIT_OF(n) (1U<<(n))
168
169static char *
170resize_buffer(VALUE ftime, char *s, const char **start, const char **endp,
171 ptrdiff_t n, size_t maxsize)
172{
173 size_t len = s - *start;
174 size_t need = len + n * 2;
175 size_t nlen = rb_str_capacity(ftime);
176 while (nlen < need) nlen <<= 1;
177
178 if (nlen < len || nlen > maxsize) {
179 return 0;
180 }
181 rb_str_set_len(ftime, len);
182 rb_str_modify_expand(ftime, nlen-len);
183 s = RSTRING_PTR(ftime);
184 *endp = s + nlen;
185 *start = s;
186 return s += len;
187}
188
189static void
190buffer_size_check(const char *s,
191 const char *format_end, size_t format_len,
192 rb_encoding *enc)
193{
194 if (!s) {
195 const char *format = format_end-format_len;
196 VALUE fmt = rb_enc_str_new(format, format_len, enc);
197 rb_syserr_fail_str(ERANGE, fmt);
198 }
199}
200
201static char *
202case_conv(char *s, ptrdiff_t i, int flags)
203{
204 switch (flags & (BIT_OF(UPPER)|BIT_OF(LOWER))) {
205 case BIT_OF(UPPER):
206 do {
207 if (ISLOWER(*s)) *s = TOUPPER(*s);
208 } while (s++, --i);
209 break;
210 case BIT_OF(LOWER):
211 do {
212 if (ISUPPER(*s)) *s = TOLOWER(*s);
213 } while (s++, --i);
214 break;
215 default:
216 s += i;
217 break;
218 }
219 return s;
220}
221
222static VALUE
223format_value(VALUE val, int base)
224{
225 if (!RB_BIGNUM_TYPE_P(val))
226 val = rb_Integer(val);
227 return rb_big2str(val, base);
228}
229
230/*
231 * enc is the encoding of the format and the initial result string. It is also
232 * used as the target encoding when a timezone name is incompatible with the
233 * result string.
234 */
235static VALUE
236rb_strftime_with_timespec(VALUE ftime, const char *format, size_t format_len,
237 rb_encoding *enc, VALUE time, const struct vtm *vtm,
238 VALUE timev, struct timespec *ts, int gmt, size_t maxsize)
239{
240 size_t len = RSTRING_LEN(ftime);
241 char *s = RSTRING_PTR(ftime);
242 const char *start = s;
243 const char *endp = start + rb_str_capacity(ftime);
244 const char *const format_end = format + format_len;
245 const char *sp, *tp;
246#define TBUFSIZE 100
247 auto char tbuf[TBUFSIZE];
248 long off;
249 ptrdiff_t i;
250 int w;
251 long y;
252 int precision, flags, colons;
253 char padding;
254#ifdef MAILHEADER_EXT
255 int sign;
256#endif
257 VALUE zone = Qnil;
258
259 /* various tables, useful in North America */
260 static const char days_l[][10] = {
261 "Sunday", "Monday", "Tuesday", "Wednesday",
262 "Thursday", "Friday", "Saturday",
263 };
264 static const char months_l[][10] = {
265 "January", "February", "March", "April",
266 "May", "June", "July", "August", "September",
267 "October", "November", "December",
268 };
269 static const char ampm[][3] = { "AM", "PM", };
270
271 if (format == NULL || format_len == 0 || vtm == NULL) {
272 goto err;
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 REINIT() (endp = (start = s = RSTRING_PTR(ftime)) + rb_str_capacity(ftime), \
288 s += len = RSTRING_LEN(ftime))
289#define FILL_PADDING(i) do { \
290 if (!(flags & BIT_OF(LEFT)) && precision > (i)) { \
291 NEEDS(precision); \
292 memset(s, padding ? padding : ' ', precision - (i)); \
293 s += precision - (i); \
294 } \
295 else { \
296 NEEDS(i); \
297 } \
298} while (0);
299#define FMT_PADDING(fmt, def_pad) \
300 (&"%*"fmt"\0""%0*"fmt[\
301 (padding == '0' || (!padding && (def_pad) == '0')) ? \
302 rb_strlen_lit("%*"fmt)+1 : 0])
303#define FMT_PRECISION(def_prec) \
304 ((flags & BIT_OF(LEFT)) ? (1) : \
305 (precision <= 0) ? (def_prec) : (precision))
306#define FMT(def_pad, def_prec, fmt, val) \
307 do { \
308 precision = FMT_PRECISION(def_prec); \
309 len = s - start; \
310 NEEDS(precision); \
311 rb_str_set_len(ftime, len); \
312 rb_str_catf(ftime, FMT_PADDING(fmt, def_pad), \
313 precision, (val)); \
314 REINIT(); \
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 REINIT(); \
356 } \
357 } while (0)
358
359 tp = memchr(format, '%', format_end - format);
360 if (!tp) tp = format_end;
361 NEEDS(tp - format);
362 memcpy(s, format, tp - format);
363 s += tp - format;
364 format = tp;
365 if (format == format_end) break;
366
367 tp = tbuf;
368 sp = format;
369 precision = -1;
370 flags = 0;
371 padding = 0;
372 colons = 0;
373 again:
374 if (++format >= format_end) goto unknown;
375 switch (*format) {
376 case '%':
377 FILL_PADDING(1);
378 *s++ = '%';
379 continue;
380
381 case 'a': /* abbreviated weekday name */
382 if (flags & BIT_OF(CHCASE)) {
383 flags &= ~(BIT_OF(LOWER)|BIT_OF(CHCASE));
384 flags |= BIT_OF(UPPER);
385 }
386 if (vtm->wday > 6)
387 i = 1, tp = "?";
388 else
389 i = 3, tp = days_l[vtm->wday];
390 break;
391
392 case 'A': /* full weekday name */
393 if (flags & BIT_OF(CHCASE)) {
394 flags &= ~(BIT_OF(LOWER)|BIT_OF(CHCASE));
395 flags |= BIT_OF(UPPER);
396 }
397 if (vtm->wday > 6)
398 i = 1, tp = "?";
399 else
400 i = strlen(tp = days_l[vtm->wday]);
401 break;
402
403#ifdef SYSV_EXT
404 case 'h': /* abbreviated month name */
405#endif
406 case 'b': /* abbreviated month name */
407 if (flags & BIT_OF(CHCASE)) {
408 flags &= ~(BIT_OF(LOWER)|BIT_OF(CHCASE));
409 flags |= BIT_OF(UPPER);
410 }
411 if (vtm->mon < 1 || vtm->mon > 12)
412 i = 1, tp = "?";
413 else
414 i = 3, tp = months_l[vtm->mon-1];
415 break;
416
417 case 'B': /* full month name */
418 if (flags & BIT_OF(CHCASE)) {
419 flags &= ~(BIT_OF(LOWER)|BIT_OF(CHCASE));
420 flags |= BIT_OF(UPPER);
421 }
422 if (vtm->mon < 1 || vtm->mon > 12)
423 i = 1, tp = "?";
424 else
425 i = strlen(tp = months_l[vtm->mon-1]);
426 break;
427
428 case 'c': /* appropriate date and time representation */
429 STRFTIME("%a %b %e %H:%M:%S %Y");
430 continue;
431
432 case 'd': /* day of the month, 01 - 31 */
433 i = range(1, vtm->mday, 31);
434 FMT('0', 2, "d", (int)i);
435 continue;
436
437 case 'H': /* hour, 24-hour clock, 00 - 23 */
438 i = range(0, vtm->hour, 23);
439 FMT('0', 2, "d", (int)i);
440 continue;
441
442 case 'I': /* hour, 12-hour clock, 01 - 12 */
443 i = range(0, vtm->hour, 23);
444 if (i == 0)
445 i = 12;
446 else if (i > 12)
447 i -= 12;
448 FMT('0', 2, "d", (int)i);
449 continue;
450
451 case 'j': /* day of the year, 001 - 366 */
452 i = range(1, vtm->yday, 366);
453 FMT('0', 3, "d", (int)i);
454 continue;
455
456 case 'm': /* month, 01 - 12 */
457 i = range(1, vtm->mon, 12);
458 FMT('0', 2, "d", (int)i);
459 continue;
460
461 case 'M': /* minute, 00 - 59 */
462 i = range(0, vtm->min, 59);
463 FMT('0', 2, "d", (int)i);
464 continue;
465
466 case 'p': /* AM or PM based on 12-hour clock */
467 case 'P': /* am or pm based on 12-hour clock */
468 if ((*format == 'p' && (flags & BIT_OF(CHCASE))) ||
469 (*format == 'P' && !(flags & (BIT_OF(CHCASE)|BIT_OF(UPPER))))) {
470 flags &= ~(BIT_OF(UPPER)|BIT_OF(CHCASE));
471 flags |= BIT_OF(LOWER);
472 }
473 i = range(0, vtm->hour, 23);
474 if (i < 12)
475 tp = ampm[0];
476 else
477 tp = ampm[1];
478 i = 2;
479 break;
480
481 case 's':
482 if (ts) {
483 time_t sec = ts->tv_sec;
484 if (~(time_t)0 <= 0)
485 FMT('0', 1, PRI_TIMET_PREFIX"d", sec);
486 else
487 FMT('0', 1, PRI_TIMET_PREFIX"u", sec);
488 }
489 else {
490 VALUE sec = div(timev, INT2FIX(1));
491 FMTV('0', 1, "d", sec);
492 }
493 continue;
494
495 case 'S': /* second, 00 - 60 */
496 i = range(0, vtm->sec, 60);
497 FMT('0', 2, "d", (int)i);
498 continue;
499
500 case 'U': /* week of year, Sunday is first day of week */
501 FMT('0', 2, "d", weeknumber_v(vtm, 0));
502 continue;
503
504 case 'w': /* weekday, Sunday == 0, 0 - 6 */
505 i = range(0, vtm->wday, 6);
506 FMT('0', 1, "d", (int)i);
507 continue;
508
509 case 'W': /* week of year, Monday is first day of week */
510 FMT('0', 2, "d", weeknumber_v(vtm, 1));
511 continue;
512
513 case 'x': /* appropriate date representation */
514 STRFTIME("%m/%d/%y");
515 continue;
516
517 case 'X': /* appropriate time representation */
518 STRFTIME("%H:%M:%S");
519 continue;
520
521 case 'y': /* year without a century, 00 - 99 */
522 i = NUM2INT(mod(vtm->year, INT2FIX(100)));
523 FMT('0', 2, "d", (int)i);
524 continue;
525
526 case 'Y': /* year with century */
527 if (FIXNUM_P(vtm->year)) {
528 long y = FIX2LONG(vtm->year);
529 FMT('0', 0 <= y ? 4 : 5, "ld", y);
530 }
531 else {
532 FMTV('0', 4, "d", vtm->year);
533 }
534 continue;
535
536#ifdef MAILHEADER_EXT
537 case 'z': /* time zone offset east of GMT e.g. -0600 */
538 if (gmt) {
539 off = 0;
540 }
541 else {
542 off = NUM2LONG(rb_funcall(vtm->utc_offset, rb_intern("round"), 0));
543 }
544 if (off < 0 || (gmt && (flags & BIT_OF(LEFT)))) {
545 off = -off;
546 sign = -1;
547 }
548 else {
549 sign = +1;
550 }
551 switch (colons) {
552 case 0: /* %z -> +hhmm */
553 precision = precision <= 5 ? 2 : precision-3;
554 NEEDS(precision + 3);
555 break;
556
557 case 1: /* %:z -> +hh:mm */
558 precision = precision <= 6 ? 2 : precision-4;
559 NEEDS(precision + 4);
560 break;
561
562 case 2: /* %::z -> +hh:mm:ss */
563 precision = precision <= 9 ? 2 : precision-7;
564 NEEDS(precision + 7);
565 break;
566
567 case 3: /* %:::z -> +hh[:mm[:ss]] */
568 if (off % 3600 == 0) {
569 precision = precision <= 3 ? 2 : precision-1;
570 NEEDS(precision + 3);
571 }
572 else if (off % 60 == 0) {
573 precision = precision <= 6 ? 2 : precision-4;
574 NEEDS(precision + 4);
575 }
576 else {
577 precision = precision <= 9 ? 2 : precision-7;
578 NEEDS(precision + 9);
579 }
580 break;
581
582 default:
583 format--;
584 goto unknown;
585 }
586 i = snprintf(s, endp - s, (padding == ' ' ? "%+*ld" : "%+.*ld"),
587 precision + (padding == ' '), sign * (off / 3600));
588 if (i < 0) goto err;
589 if (sign < 0 && off < 3600) {
590 *(padding == ' ' ? s + i - 2 : s) = '-';
591 }
592 s += i;
593 off = off % 3600;
594 if (colons == 3 && off == 0)
595 continue;
596 if (1 <= colons)
597 *s++ = ':';
598 i = snprintf(s, endp - s, "%02d", (int)(off / 60));
599 if (i < 0) goto err;
600 s += i;
601 off = off % 60;
602 if (colons == 3 && off == 0)
603 continue;
604 if (2 <= colons) {
605 *s++ = ':';
606 i = snprintf(s, endp - s, "%02d", (int)off);
607 if (i < 0) goto err;
608 s += i;
609 }
610 continue;
611#endif /* MAILHEADER_EXT */
612
613 case 'Z': /* time zone name or abbreviation */
614 if (flags & BIT_OF(CHCASE)) {
615 flags &= ~(BIT_OF(UPPER)|BIT_OF(CHCASE));
616 flags |= BIT_OF(LOWER);
617 }
618 if (gmt) {
619 i = 3;
620 tp = "UTC";
621 break;
622 }
623 if (NIL_P(vtm->zone)) {
624 i = 0;
625 }
626 else {
627 rb_str_set_len(ftime, s - start); /* before rb_enc_compatible */
628
629 if (NIL_P(zone)) {
630 zone = rb_time_zone_abbreviation(vtm->zone, time);
631 REINIT();
632 }
633
634 if (enc) {
635 rb_encoding *compat = rb_enc_compatible(ftime, zone);
636 if (compat && rb_enc_asciicompat(compat)) {
637 rb_enc_associate(ftime, compat);
638 }
639 else {
641 }
642 }
643 tp = RSTRING_PTR(zone);
644 i = RSTRING_LEN(zone);
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) {
897 FILL_PADDING(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
910err:
911 RB_GC_GUARD(zone);
912 return 0;
913}
914
915static size_t
916strftime_size_limit(size_t format_len)
917{
918 size_t limit = format_len * (1*1024*1024);
919 if (limit < format_len) limit = format_len;
920 else if (limit < 1024) limit = 1024;
921 return limit;
922}
923
924static VALUE
925create_buffer(rb_encoding *enc)
926{
927 VALUE result = rb_obj_hide(rb_enc_str_new(0, 0, enc));
928 ENC_CODERANGE_CLEAR(result);
929 return result;
930}
931
932VALUE
933rb_strftime(const char *format, size_t format_len, rb_encoding *enc,
934 VALUE time, const struct vtm *vtm, VALUE timev, int gmt)
935{
936 VALUE buff = create_buffer(enc);
937 buff = rb_strftime_with_timespec(buff, format, format_len, enc,
938 time, vtm, timev, NULL, gmt,
939 strftime_size_limit(format_len));
940 return rb_obj_reveal(buff, rb_cString);
941}
942
943VALUE
944rb_strftime_timespec(const char *format, size_t format_len, rb_encoding *enc,
945 VALUE time, const struct vtm *vtm, struct timespec *ts, int gmt)
946{
947 VALUE buff = create_buffer(enc);
948 buff = rb_strftime_with_timespec(buff, format, format_len, enc,
949 time, vtm, Qnil, ts, gmt,
950 strftime_size_limit(format_len));
951 return rb_obj_reveal(buff, rb_cString);
952}
953
954#if 0
955VALUE
956rb_strftime_limit(const char *format, size_t format_len, rb_encoding *enc,
957 VALUE time, const struct vtm *vtm, struct timespec *ts,
958 int gmt, size_t maxsize)
959{
960 VALUE buff = create_buffer(enc);
961 buff = rb_strftime_with_timespec(buff, format, format_len, enc,
962 time, vtm, Qnil, ts, gmt, maxsize);
963 return rb_obj_reveal(buff, rb_cString);
964}
965#endif
966
967/* isleap --- is a year a leap year? */
968
969static int
970isleap(long year)
971{
972 return ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0);
973}
974
975
976static void
977vtm2tm_noyear(const struct vtm *vtm, struct tm *result)
978{
979 struct tm tm;
980
981 /* for isleap() in iso8601wknum. +100 is -1900 (mod 400). */
982 tm.tm_year = FIX2INT(mod(vtm->year, INT2FIX(400))) + 100;
983
984 tm.tm_mon = vtm->mon-1;
985 tm.tm_mday = vtm->mday;
986 tm.tm_hour = vtm->hour;
987 tm.tm_min = vtm->min;
988 tm.tm_sec = vtm->sec;
989 tm.tm_wday = vtm->wday;
990 tm.tm_yday = vtm->yday-1;
991 tm.tm_isdst = vtm->isdst;
992#if defined(HAVE_STRUCT_TM_TM_GMTOFF)
993 tm.tm_gmtoff = 0;
994#endif
995#if defined(HAVE_TM_ZONE)
996 tm.tm_zone = NULL;
997#endif
998 *result = tm;
999}
1000
1001#ifdef POSIX2_DATE
1002/* iso8601wknum --- compute week number according to ISO 8601 */
1003
1004static int
1005iso8601wknum(const struct tm *timeptr)
1006{
1007 /*
1008 * From 1003.2:
1009 * If the week (Monday to Sunday) containing January 1
1010 * has four or more days in the new year, then it is week 1;
1011 * otherwise it is the highest numbered week of the previous
1012 * year (52 or 53), and the next week is week 1.
1013 *
1014 * ADR: This means if Jan 1 was Monday through Thursday,
1015 * it was week 1, otherwise week 52 or 53.
1016 *
1017 * XPG4 erroneously included POSIX.2 rationale text in the
1018 * main body of the standard. Thus it requires week 53.
1019 */
1020
1021 int weeknum, jan1day;
1022
1023 /* get week number, Monday as first day of the week */
1024 weeknum = weeknumber(timeptr, 1);
1025
1026 /*
1027 * With thanks and tip of the hatlo to tml@tik.vtt.fi
1028 *
1029 * What day of the week does January 1 fall on?
1030 * We know that
1031 * (timeptr->tm_yday - jan1.tm_yday) MOD 7 ==
1032 * (timeptr->tm_wday - jan1.tm_wday) MOD 7
1033 * and that
1034 * jan1.tm_yday == 0
1035 * and that
1036 * timeptr->tm_wday MOD 7 == timeptr->tm_wday
1037 * from which it follows that. . .
1038 */
1039 jan1day = timeptr->tm_wday - (timeptr->tm_yday % 7);
1040 if (jan1day < 0)
1041 jan1day += 7;
1042
1043 /*
1044 * If Jan 1 was a Monday through Thursday, it was in
1045 * week 1. Otherwise it was last year's highest week, which is
1046 * this year's week 0.
1047 *
1048 * What does that mean?
1049 * If Jan 1 was Monday, the week number is exactly right, it can
1050 * never be 0.
1051 * If it was Tuesday through Thursday, the weeknumber is one
1052 * less than it should be, so we add one.
1053 * Otherwise, Friday, Saturday or Sunday, the week number is
1054 * OK, but if it is 0, it needs to be 52 or 53.
1055 */
1056 switch (jan1day) {
1057 case 1: /* Monday */
1058 break;
1059 case 2: /* Tuesday */
1060 case 3: /* Wednesday */
1061 case 4: /* Thursday */
1062 weeknum++;
1063 break;
1064 case 5: /* Friday */
1065 case 6: /* Saturday */
1066 case 0: /* Sunday */
1067 if (weeknum == 0) {
1068#ifdef USE_BROKEN_XPG4
1069 /* XPG4 (as of March 1994) says 53 unconditionally */
1070 weeknum = 53;
1071#else
1072 /* get week number of last week of last year */
1073 struct tm dec31ly; /* 12/31 last year */
1074 dec31ly = *timeptr;
1075 dec31ly.tm_year--;
1076 dec31ly.tm_mon = 11;
1077 dec31ly.tm_mday = 31;
1078 dec31ly.tm_wday = (jan1day == 0) ? 6 : jan1day - 1;
1079 dec31ly.tm_yday = 364 + isleap(dec31ly.tm_year + 1900L);
1080 weeknum = iso8601wknum(& dec31ly);
1081#endif
1082 }
1083 break;
1084 }
1085
1086 if (timeptr->tm_mon == 11) {
1087 /*
1088 * The last week of the year
1089 * can be in week 1 of next year.
1090 * Sigh.
1091 *
1092 * This can only happen if
1093 * M T W
1094 * 29 30 31
1095 * 30 31
1096 * 31
1097 */
1098 int wday, mday;
1099
1100 wday = timeptr->tm_wday;
1101 mday = timeptr->tm_mday;
1102 if ( (wday == 1 && (mday >= 29 && mday <= 31))
1103 || (wday == 2 && (mday == 30 || mday == 31))
1104 || (wday == 3 && mday == 31))
1105 weeknum = 1;
1106 }
1107
1108 return weeknum;
1109}
1110
1111static int
1112iso8601wknum_v(const struct vtm *vtm)
1113{
1114 struct tm tm;
1115 vtm2tm_noyear(vtm, &tm);
1116 return iso8601wknum(&tm);
1117}
1118
1119#endif
1120
1121/* weeknumber --- figure how many weeks into the year */
1122
1123/* With thanks and tip of the hatlo to ado@elsie.nci.nih.gov */
1124
1125static int
1126weeknumber(const struct tm *timeptr, int firstweekday)
1127{
1128 int wday = timeptr->tm_wday;
1129 int ret;
1130
1131 if (firstweekday == 1) {
1132 if (wday == 0) /* sunday */
1133 wday = 6;
1134 else
1135 wday--;
1136 }
1137 ret = ((timeptr->tm_yday + 7 - wday) / 7);
1138 if (ret < 0)
1139 ret = 0;
1140 return ret;
1141}
1142
1143static int
1144weeknumber_v(const struct vtm *vtm, int firstweekday)
1145{
1146 struct tm tm;
1147 vtm2tm_noyear(vtm, &tm);
1148 return weeknumber(&tm, firstweekday);
1149}
1150
1151#if 0
1152/* ADR --- I'm loathe to mess with ado's code ... */
1153
1154Date: Wed, 24 Apr 91 20:54:08 MDT
1155From: Michal Jaegermann <audfax!emory!vm.ucs.UAlberta.CA!NTOMCZAK>
1156To: arnold@audiofax.com
1157
1158Hi Arnold,
1159in a process of fixing of strftime() in libraries on Atari ST I grabbed
1160some pieces of code from your own strftime. When doing that it came
1161to mind that your weeknumber() function compiles a little bit nicer
1162in the following form:
1163/*
1164 * firstweekday is 0 if starting in Sunday, non-zero if in Monday
1165 */
1166{
1167 return (timeptr->tm_yday - timeptr->tm_wday +
1168 (firstweekday ? (timeptr->tm_wday ? 8 : 1) : 7)) / 7;
1169}
1170How nicer it depends on a compiler, of course, but always a tiny bit.
1171
1172 Cheers,
1173 Michal
1174 ntomczak@vm.ucs.ualberta.ca
1175#endif
1176
1177#ifdef TEST_STRFTIME
1178
1179/*
1180 * NAME:
1181 * tst
1182 *
1183 * SYNOPSIS:
1184 * tst
1185 *
1186 * DESCRIPTION:
1187 * "tst" is a test driver for the function "strftime".
1188 *
1189 * OPTIONS:
1190 * None.
1191 *
1192 * AUTHOR:
1193 * Karl Vogel
1194 * Control Data Systems, Inc.
1195 * vogelke@c-17igp.wpafb.af.mil
1196 *
1197 * BUGS:
1198 * None noticed yet.
1199 *
1200 * COMPILE:
1201 * cc -o tst -DTEST_STRFTIME strftime.c
1202 */
1203
1204/* ADR: I reformatted this to my liking, and deleted some unneeded code. */
1205
1206#ifndef NULL
1207#include <stdio.h>
1208#endif
1209#include <sys/time.h>
1210#include <string.h>
1211
1212#define MAXTIME 132
1213
1214/*
1215 * Array of time formats.
1216 */
1217
1218static char *array[] =
1219{
1220 "(%%A) full weekday name, var length (Sunday..Saturday) %A",
1221 "(%%B) full month name, var length (January..December) %B",
1222 "(%%C) Century %C",
1223 "(%%D) date (%%m/%%d/%%y) %D",
1224 "(%%E) Locale extensions (ignored) %E",
1225 "(%%H) hour (24-hour clock, 00..23) %H",
1226 "(%%I) hour (12-hour clock, 01..12) %I",
1227 "(%%M) minute (00..59) %M",
1228 "(%%O) Locale extensions (ignored) %O",
1229 "(%%R) time, 24-hour (%%H:%%M) %R",
1230 "(%%S) second (00..60) %S",
1231 "(%%T) time, 24-hour (%%H:%%M:%%S) %T",
1232 "(%%U) week of year, Sunday as first day of week (00..53) %U",
1233 "(%%V) week of year according to ISO 8601 %V",
1234 "(%%W) week of year, Monday as first day of week (00..53) %W",
1235 "(%%X) appropriate locale time representation (%H:%M:%S) %X",
1236 "(%%Y) year with century (1970...) %Y",
1237 "(%%Z) timezone (EDT), or blank if timezone not determinable %Z",
1238 "(%%a) locale's abbreviated weekday name (Sun..Sat) %a",
1239 "(%%b) locale's abbreviated month name (Jan..Dec) %b",
1240 "(%%c) full date (Sat Nov 4 12:02:33 1989)%n%t%t%t %c",
1241 "(%%d) day of the month (01..31) %d",
1242 "(%%e) day of the month, blank-padded ( 1..31) %e",
1243 "(%%h) should be same as (%%b) %h",
1244 "(%%j) day of the year (001..366) %j",
1245 "(%%k) hour, 24-hour clock, blank pad ( 0..23) %k",
1246 "(%%l) hour, 12-hour clock, blank pad ( 1..12) %l",
1247 "(%%m) month (01..12) %m",
1248 "(%%p) locale's AM or PM based on 12-hour clock %p",
1249 "(%%r) time, 12-hour (same as %%I:%%M:%%S %%p) %r",
1250 "(%%u) ISO 8601: Weekday as decimal number [1 (Monday) - 7] %u",
1251 "(%%v) VMS date (dd-bbb-YYYY) %v",
1252 "(%%w) day of week (0..6, Sunday == 0) %w",
1253 "(%%x) appropriate locale date representation %x",
1254 "(%%y) last two digits of year (00..99) %y",
1255 "(%%z) timezone offset east of GMT as HHMM (e.g. -0500) %z",
1256 (char *) NULL
1257};
1258
1259/* main routine. */
1260
1261int
1262main(int argc, char **argv)
1263{
1264 long time();
1265
1266 char *next;
1267 char string[MAXTIME];
1268
1269 int k;
1270 int length;
1271
1272 struct tm *tm;
1273
1274 long clock;
1275
1276 /* Call the function. */
1277
1278 clock = time((long *) 0);
1279 tm = localtime(&clock);
1280
1281 for (k = 0; next = array[k]; k++) {
1282 length = strftime(string, MAXTIME, next, tm);
1283 printf("%s\n", string);
1284 }
1285
1286 exit(0);
1287}
1288#endif /* TEST_STRFTIME */
#define ISUPPER
@old{rb_isupper}
Definition ctype.h:89
#define TOUPPER
@old{rb_toupper}
Definition ctype.h:100
#define ISLOWER
@old{rb_islower}
Definition ctype.h:90
#define TOLOWER
@old{rb_tolower}
Definition ctype.h:101
#define INT2FIX
Old name of RB_INT2FIX.
Definition long.h:48
#define ECONV_UNDEF_REPLACE
Old name of RUBY_ECONV_UNDEF_REPLACE.
Definition transcode.h:526
#define FIX2INT
Old name of RB_FIX2INT.
Definition int.h:41
#define ECONV_INVALID_REPLACE
Old name of RUBY_ECONV_INVALID_REPLACE.
Definition transcode.h:524
#define NUM2INT
Old name of RB_NUM2INT.
Definition int.h:44
#define Qnil
Old name of RUBY_Qnil.
#define FIX2LONG
Old name of RB_FIX2LONG.
Definition long.h:46
#define NIL_P
Old name of RB_NIL_P.
#define NUM2LONG
Old name of RB_NUM2LONG.
Definition long.h:51
#define ENC_CODERANGE_CLEAR(obj)
Old name of RB_ENC_CODERANGE_CLEAR.
Definition coderange.h:187
#define FIXNUM_P
Old name of RB_FIXNUM_P.
void rb_syserr_fail_str(int e, VALUE mesg)
Identical to rb_syserr_fail(), except it takes the message in Ruby's String instead of C's.
Definition error.c:3915
VALUE rb_obj_reveal(VALUE obj, VALUE klass)
Make a hidden object visible again.
Definition object.c:109
VALUE rb_obj_hide(VALUE obj)
Make the object invisible from Ruby code.
Definition object.c:100
VALUE rb_Integer(VALUE val)
This is the logic behind Kernel#Integer.
Definition object.c:3381
VALUE rb_cString
String class.
Definition string.c:84
Encoding relates APIs.
VALUE rb_str_conv_enc_opts(VALUE str, rb_encoding *from, rb_encoding *to, int ecflags, VALUE ecopts)
Identical to rb_str_conv_enc(), except it additionally takes IO encoder options.
Definition string.c:1226
VALUE rb_funcall(VALUE recv, ID mid, int n,...)
Calls a method.
Definition vm_eval.c:1117
size_t rb_str_capacity(VALUE str)
Queries the capacity of the given string.
Definition string.c:1001
void rb_str_set_len(VALUE str, long len)
Overwrites the length of the string.
Definition string.c:3390
void rb_str_modify_expand(VALUE str, long capa)
Identical to rb_str_modify(), except it additionally expands the capacity of the receiver.
Definition string.c:2747
int off
Offset inside of ptr.
Definition io.h:5
int len
Length of the buffer.
Definition io.h:8
VALUE rb_str_format(int argc, const VALUE *argv, VALUE fmt)
Formats a string.
Definition sprintf.c:215
#define RB_GC_GUARD(v)
Prevents premature destruction of local objects.
Definition memory.h:167
#define StringValueCStr(v)
Identical to StringValuePtr, except it additionally checks for the contents for viability as a C stri...
Definition rstring.h:89
Definition timev.h:5
uintptr_t VALUE
Type that represents a Ruby object.
Definition value.h:40