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