Ruby: strftime.c Source File

Ruby 3.3.6p108 (2024-11-05 revision 75015d4c1f6965b5e85e96fb309f1f2129f933c0)

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