Debian Codegraph @

vendor/mruby-source/mrbgems/mruby-time/src/time.c

raw
1 /*
2 ** time.c - Time class
3 **
4 ** See Copyright Notice in mruby.h
5 */
6
7 #include <mruby.h>
8 #include <mruby/class.h>
9 #include <mruby/data.h>
10 #include <mruby/numeric.h>
11 #include <mruby/time.h>
12 #include <mruby/string.h>
13 #include <mruby/internal.h>
14 #include <mruby/presym.h>
15
16 #ifdef MRB_NO_STDIO
17 #include <string.h>
18 #endif
19
20
21 #include <stdlib.h>
22 #ifndef _WIN32
23 #include <unistd.h>
24 #endif
25
26 #define NDIV(x,y) (-(-((x)+1)/(y))-1)
27 #define TO_S_FMT "%Y-%m-%d %H:%M:%S "
28
29 #if defined(_MSC_VER) && _MSC_VER < 1800
30 double round(double x) {
31 return floor(x + 0.5);
32 }
33 #endif
34
35 #ifndef MRB_NO_FLOAT
36 # if !defined(__MINGW64__) && defined(_WIN32)
37 # define llround(x) round(x)
38 # endif
39 #endif
40
41 #if defined(__MINGW64__) || defined(__MINGW32__)
42 # include <sys/time.h>
43 #endif
44
45 /** Time class configuration */
46
47 /* gettimeofday(2) */
48 /* C99 does not have gettimeofday that is required to retrieve microseconds */
49 /* uncomment following macro on platforms without gettimeofday(2) */
50 /* #define NO_GETTIMEOFDAY */
51
52 /* gmtime(3) */
53 /* C99 does not have reentrant gmtime_r() so it might cause troubles under */
54 /* multi-threading environment. undef following macro on platforms that */
55 /* does not have gmtime_r() and localtime_r(). */
56 /* #define NO_GMTIME_R */
57
58 #ifdef _WIN32
59 #ifdef _MSC_VER
60 /* Win32 platform do not provide gmtime_r/localtime_r; emulate them using gmtime_s/localtime_s */
61 #define gmtime_r(tp, tm) ((gmtime_s((tm), (tp)) == 0) ? (tm) : NULL)
62 #define localtime_r(tp, tm) ((localtime_s((tm), (tp)) == 0) ? (tm) : NULL)
63 #else
64 #define NO_GMTIME_R
65 #endif
66 #endif
67 #ifdef __STRICT_ANSI__
68 /* Strict ANSI (e.g. -std=c99) do not provide gmtime_r/localtime_r */
69 #define NO_GMTIME_R
70 #endif
71
72 /* asctime(3) */
73 /* mruby usually use its own implementation of struct tm to string conversion */
74 /* except when MRB_NO_STDIO is set. In that case, it uses asctime() or asctime_r(). */
75 /* By default mruby tries to use asctime_r() which is reentrant. */
76 /* Undef following macro on platforms that does not have asctime_r(). */
77 /* #define NO_ASCTIME_R */
78
79 /* timegm(3) */
80 /* mktime() creates tm structure for localtime; timegm() is for UTC time */
81 /* define following macro to use probably faster timegm() on the platform */
82 /* #define USE_SYSTEM_TIMEGM */
83
84 /** end of Time class configuration */
85
86 #if (defined(_POSIX_TIMERS) && _POSIX_TIMERS > 0) && defined(CLOCK_REALTIME)
87 # define USE_CLOCK_GETTIME
88 #endif
89
90 #if !defined(NO_GETTIMEOFDAY)
91 # if defined(_WIN32) && !defined(USE_CLOCK_GETTIME)
92 # define WIN32_LEAN_AND_MEAN /* don't include winsock.h */
93 # include <windows.h>
94 # define gettimeofday my_gettimeofday
95
96 # ifdef _MSC_VER
97 # define UI64(x) x##ui64
98 # else
99 # define UI64(x) x##ull
100 # endif
101
102 typedef long suseconds_t;
103
104 # if (!defined __MINGW64__) && (!defined __MINGW32__)
105 struct timeval {
106 time_t tv_sec;
107 suseconds_t tv_usec;
108 };
109 # endif
110
111 static int
112 gettimeofday(struct timeval *tv, void *tz)
113 {
114 if (tz) {
115 mrb_assert(0); /* timezone is not supported */
116 }
117 if (tv) {
118 union {
119 FILETIME ft;
120 unsigned __int64 u64;
121 } t;
122 GetSystemTimeAsFileTime(&t.ft); /* 100 ns intervals since Windows epoch */
123 t.u64 -= UI64(116444736000000000); /* Unix epoch bias */
124 t.u64 /= 10; /* to microseconds */
125 tv->tv_sec = (time_t)(t.u64 / (1000 * 1000));
126 tv->tv_usec = t.u64 % (1000 * 1000);
127 }
128 return 0;
129 }
130 # else
131 # include <sys/time.h>
132 # endif
133 #endif
134 #ifdef NO_GMTIME_R
135 #define gmtime_r(t,r) gmtime(t)
136 #define localtime_r(t,r) localtime(t)
137 #endif
138
139 #ifndef USE_SYSTEM_TIMEGM
140 #define timegm my_timgm
141
142 static unsigned int
143 is_leapyear(unsigned int y)
144 {
145 return (y % 4) == 0 && ((y % 100) != 0 || (y % 400) == 0);
146 }
147
148 static time_t
149 timegm(struct tm *tm)
150 {
151 static const unsigned int ndays[2][12] = {
152 {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31},
153 {31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}
154 };
155 time_t r = 0;
156 int i;
157 unsigned int *nday = (unsigned int*) ndays[is_leapyear(tm->tm_year+1900)];
158
159 static const int epoch_year = 70;
160 if (tm->tm_year >= epoch_year) {
161 for (i = epoch_year; i < tm->tm_year; ++i)
162 r += is_leapyear(i+1900) ? 366*24*60*60 : 365*24*60*60;
163 }
164 else {
165 for (i = tm->tm_year; i < epoch_year; ++i)
166 r -= is_leapyear(i+1900) ? 366*24*60*60 : 365*24*60*60;
167 }
168 for (i = 0; i < tm->tm_mon; ++i)
169 r += nday[i] * 24 * 60 * 60;
170 r += (tm->tm_mday - 1) * 24 * 60 * 60;
171 r += tm->tm_hour * 60 * 60;
172 r += tm->tm_min * 60;
173 r += tm->tm_sec;
174 return r;
175 }
176 #endif
177
178 /* Since we are limited to using ISO C99, this implementation is based
179 * on time_t. That means the resolution of time is only precise to the
180 * second level. Also, there are only 2 timezones, namely UTC and LOCAL.
181 */
182
183 #ifndef MRB_NO_STDIO
184 static const char mon_names[12][4] = {
185 "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec",
186 };
187
188 static const char wday_names[7][4] = {
189 "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat",
190 };
191 #endif
192
193 struct mrb_time {
194 time_t sec;
195 time_t usec;
196 enum mrb_timezone timezone;
197 struct tm datetime;
198 };
199
200 static const struct mrb_data_type time_type = { "Time", mrb_free };
201
202 #define MRB_TIME_T_UINT (~(time_t)0 > 0)
203 #define MRB_TIME_MIN ( \
204 MRB_TIME_T_UINT ? 0 : \
205 (sizeof(time_t) <= 4 ? INT32_MIN : INT64_MIN) \
206 )
207 #define MRB_TIME_MAX (time_t)( \
208 MRB_TIME_T_UINT ? (sizeof(time_t) <= 4 ? UINT32_MAX : UINT64_MAX) : \
209 (sizeof(time_t) <= 4 ? INT32_MAX : INT64_MAX) \
210 )
211
212 /* return true if time_t is fit in mrb_int */
213 static mrb_bool
214 fixable_time_t_p(time_t v)
215 {
216 if (MRB_INT_MIN <= MRB_TIME_MIN && MRB_TIME_MAX <= MRB_INT_MAX) return TRUE;
217 if (v > (time_t)MRB_INT_MAX) return FALSE;
218 if (MRB_TIME_T_UINT) return TRUE;
219 if (MRB_INT_MIN > (mrb_int)v) return FALSE;
220 return TRUE;
221 }
222
223 static time_t
224 mrb_to_time_t(mrb_state *mrb, mrb_value obj, time_t *usec)
225 {
226 time_t t;
227
228 switch (mrb_type(obj)) {
229 #ifndef MRB_NO_FLOAT
230 case MRB_TT_FLOAT:
231 {
232 mrb_float f = mrb_float(obj);
233
234 mrb_check_num_exact(mrb, f);
235 if (f >= ((mrb_float)MRB_TIME_MAX-1.0) || f < ((mrb_float)MRB_TIME_MIN+1.0)) {
236 goto out_of_range;
237 }
238
239 if (usec) {
240 double tt = floor(f);
241 if (!isfinite(tt)) goto out_of_range;
242 t = (time_t)tt;
243 *usec = (time_t)trunc((f - tt) * 1.0e+6);
244 }
245 else {
246 double tt = round(f);
247 if (!isfinite(tt)) goto out_of_range;
248 t = (time_t)tt;
249 }
250 }
251 break;
252 #endif /* MRB_NO_FLOAT */
253
254 #ifdef MRB_USE_BIGINT
255 case MRB_TT_BIGINT:
256 {
257 if (sizeof(time_t) > sizeof(mrb_int)) {
258 if (MRB_TIME_T_UINT) {
259 t = (time_t)mrb_bint_as_uint64(mrb, obj);
260 }
261 else {
262 t = (time_t)mrb_bint_as_int64(mrb, obj);
263 }
264 if (usec) { *usec = 0; }
265 break;
266 }
267 else {
268 mrb_int i = mrb_bint_as_int(mrb, obj);
269 obj = mrb_int_value(mrb, i);
270 }
271 }
272 /* fall through */
273 #endif /* MRB_USE_BIGINT */
274
275 case MRB_TT_INTEGER:
276 {
277 mrb_int i = mrb_integer(obj);
278
279 if ((MRB_INT_MAX > MRB_TIME_MAX && i > 0 && (time_t)i > MRB_TIME_MAX) ||
280 (0 > MRB_TIME_MIN && MRB_TIME_MIN > MRB_INT_MIN && MRB_TIME_MIN > i)) {
281 goto out_of_range;
282 }
283
284 t = (time_t)i;
285 if (usec) { *usec = 0; }
286 }
287 break;
288
289 default:
290 mrb_raisef(mrb, E_TYPE_ERROR, "cannot convert %Y to time", obj);
291 return 0;
292 }
293
294 return t;
295
296 out_of_range:
297 mrb_raisef(mrb, E_ARGUMENT_ERROR, "%v out of Time range", obj);
298
299 /* not reached */
300 return 0;
301 }
302
303 static mrb_value
304 time_value_from_time_t(mrb_state *mrb, time_t t)
305 {
306 if (!fixable_time_t_p(t)) {
307 #if defined(MRB_USE_BIGINT)
308 if (MRB_TIME_T_UINT) {
309 return mrb_bint_new_uint64(mrb, (uint64_t)t);
310 }
311 else {
312 return mrb_bint_new_int64(mrb, (int64_t)t);
313 }
314 #elif !defined(MRB_NO_FLOAT)
315 return mrb_float_value(mrb, (mrb_float)t);
316 #else
317 mrb_raisef(mrb, E_ARGUMENT_ERROR, "Time too big");
318 #endif
319 }
320 return mrb_int_value(mrb, (mrb_int)t);
321 }
322
323 /** Updates the datetime of a mrb_time based on it's timezone and
324 seconds setting. Returns self on success, NULL of failure.
325 if `dealloc` is set `true`, it frees `self` on error. */
326 static struct mrb_time*
327 time_update_datetime(mrb_state *mrb, struct mrb_time *self, int dealloc)
328 {
329 struct tm *aid;
330 time_t t = self->sec;
331
332 if (self->timezone == MRB_TIMEZONE_UTC) {
333 aid = gmtime_r(&t, &self->datetime);
334 }
335 else {
336 aid = localtime_r(&t, &self->datetime);
337 }
338 if (!aid) {
339 if (dealloc) mrb_free(mrb, self);
340 mrb_raisef(mrb, E_ARGUMENT_ERROR, "%v out of Time range", time_value_from_time_t(mrb, t));
341 /* not reached */
342 return NULL;
343 }
344 #ifdef NO_GMTIME_R
345 self->datetime = *aid; /* copy data */
346 #endif
347
348 return self;
349 }
350
351 static mrb_value
352 time_wrap(mrb_state *mrb, struct RClass *tc, struct mrb_time *tm)
353 {
354 return mrb_obj_value(Data_Wrap_Struct(mrb, tc, &time_type, tm));
355 }
356
357 /* Allocates a mrb_time object and initializes it. */
358 static struct mrb_time*
359 time_alloc_time(mrb_state *mrb, time_t sec, time_t usec, enum mrb_timezone timezone)
360 {
361 struct mrb_time *tm;
362
363 tm = (struct mrb_time*)mrb_malloc(mrb, sizeof(struct mrb_time));
364 tm->sec = sec;
365 tm->usec = usec;
366 if (!MRB_TIME_T_UINT && tm->usec < 0) {
367 long sec2 = (long)NDIV(tm->usec,1000000); /* negative div */
368 tm->usec -= sec2 * 1000000;
369 tm->sec += sec2;
370 }
371 else if (tm->usec >= 1000000) {
372 long sec2 = (long)(tm->usec / 1000000);
373 tm->usec -= sec2 * 1000000;
374 tm->sec += sec2;
375 }
376 tm->timezone = timezone;
377 time_update_datetime(mrb, tm, TRUE);
378
379 return tm;
380 }
381
382 static struct mrb_time*
383 time_alloc(mrb_state *mrb, mrb_value sec, mrb_value usec, enum mrb_timezone timezone)
384 {
385 time_t tsec, tusec;
386
387 tsec = mrb_to_time_t(mrb, sec, &tusec);
388 tusec += mrb_to_time_t(mrb, usec, NULL);
389
390 return time_alloc_time(mrb, tsec, tusec, timezone);
391 }
392
393 static mrb_value
394 time_make_time(mrb_state *mrb, struct RClass *c, time_t sec, time_t usec, enum mrb_timezone timezone)
395 {
396 return time_wrap(mrb, c, time_alloc_time(mrb, sec, usec, timezone));
397 }
398
399 static mrb_value
400 time_make(mrb_state *mrb, struct RClass *c, mrb_value sec, mrb_value usec, enum mrb_timezone timezone)
401 {
402 return time_wrap(mrb, c, time_alloc(mrb, sec, usec, timezone));
403 }
404
405 static struct mrb_time*
406 current_mrb_time(mrb_state *mrb)
407 {
408 struct mrb_time tmzero = {0};
409 struct mrb_time *tm;
410 time_t sec, usec;
411
412 #if defined(TIME_UTC) && !defined(__ANDROID__)
413 {
414 struct timespec ts;
415 timespec_get(&ts, TIME_UTC);
416 sec = ts.tv_sec;
417 usec = ts.tv_nsec / 1000;
418 }
419 #elif defined(USE_CLOCK_GETTIME)
420 {
421 struct timespec ts;
422 clock_gettime(CLOCK_REALTIME, &ts);
423 sec = ts.tv_sec;
424 usec = ts.tv_nsec / 1000;
425 }
426 #elif defined(NO_GETTIMEOFDAY)
427 {
428 static time_t last_sec = 0, last_usec = 0;
429
430 sec = time(NULL);
431 if (sec != last_sec) {
432 last_sec = sec;
433 last_usec = 0;
434 }
435 else {
436 /* add 1 usec to differentiate two times */
437 last_usec += 1;
438 }
439 usec = last_usec;
440 }
441 #else
442 {
443 struct timeval tv;
444
445 gettimeofday(&tv, NULL);
446 sec = tv.tv_sec;
447 usec = tv.tv_usec;
448 }
449 #endif
450 tm = (struct mrb_time*)mrb_malloc(mrb, sizeof(*tm));
451 *tm = tmzero;
452 tm->sec = sec; tm->usec = usec;
453 tm->timezone = MRB_TIMEZONE_LOCAL;
454 time_update_datetime(mrb, tm, TRUE);
455
456 return tm;
457 }
458
459 /* Allocates a new Time object with given millis value. */
460 static mrb_value
461 time_now(mrb_state *mrb, mrb_value self)
462 {
463 return time_wrap(mrb, mrb_class_ptr(self), current_mrb_time(mrb));
464 }
465
466 MRB_API mrb_value
467 time_at(mrb_state *mrb, time_t sec, time_t usec, enum mrb_timezone zone)
468 {
469 return time_make_time(mrb, mrb_class_get_id(mrb, MRB_SYM(Time)), sec, usec, zone);
470 }
471
472 /* 15.2.19.6.1 */
473 /* Creates an instance of time at the given time in seconds, etc. */
474 static mrb_value
475 time_at_m(mrb_state *mrb, mrb_value self)
476 {
477 mrb_value sec;
478 mrb_value usec = mrb_fixnum_value(0);
479
480 mrb_get_args(mrb, "o|o", &sec, &usec);
481
482 return time_make(mrb, mrb_class_ptr(self), sec, usec, MRB_TIMEZONE_LOCAL);
483 }
484
485 static struct mrb_time*
486 time_mktime(mrb_state *mrb, mrb_int ayear, mrb_int amonth, mrb_int aday,
487 mrb_int ahour, mrb_int amin, mrb_int asec, mrb_int ausec,
488 enum mrb_timezone timezone)
489 {
490 time_t nowsecs;
491 struct tm nowtime = { 0 };
492
493 #if MRB_INT_MAX > INT_MAX
494 #define OUTINT(x) (((MRB_TIME_T_UINT ? 0 : INT_MIN) > (x)) || (x) > INT_MAX)
495 #else
496 #define OUTINT(x) 0
497 #endif
498
499 ayear -= 1900;
500 if (OUTINT(ayear) ||
501 amonth < 1 || amonth > 12 ||
502 aday < 1 || aday > 31 ||
503 ahour < 0 || ahour > 24 ||
504 (ahour == 24 && (amin > 0 || asec > 0)) ||
505 amin < 0 || amin > 59 ||
506 asec < 0 || asec > 60)
507 mrb_raise(mrb, E_ARGUMENT_ERROR, "argument out of range");
508
509 nowtime.tm_year = (int)ayear;
510 nowtime.tm_mon = (int)(amonth - 1);
511 nowtime.tm_mday = (int)aday;
512 nowtime.tm_hour = (int)ahour;
513 nowtime.tm_min = (int)amin;
514 nowtime.tm_sec = (int)asec;
515 nowtime.tm_isdst = -1;
516
517 time_t (*mk)(struct tm*);
518 if (timezone == MRB_TIMEZONE_UTC) {
519 mk = timegm;
520 }
521 else {
522 mk = mktime;
523 }
524 nowsecs = (*mk)(&nowtime);
525 if (nowsecs == (time_t)-1) {
526 nowtime.tm_sec += 1; /* maybe Epoch-1 sec */
527 nowsecs = (*mk)(&nowtime);
528 if (nowsecs != 0) { /* check if Epoch */
529 mrb_raise(mrb, E_ARGUMENT_ERROR, "Not a valid time");
530 }
531 nowsecs = (time_t)-1; /* valid Epoch-1 */
532 }
533
534 return time_alloc_time(mrb, nowsecs, ausec, timezone);
535 }
536
537 /* 15.2.19.6.2 */
538 /* Creates an instance of time at the given time in UTC. */
539 static mrb_value
540 time_gm(mrb_state *mrb, mrb_value self)
541 {
542 mrb_int ayear = 0, amonth = 1, aday = 1, ahour = 0, amin = 0, asec = 0, ausec = 0;
543
544 mrb_get_args(mrb, "i|iiiiii",
545 &ayear, &amonth, &aday, &ahour, &amin, &asec, &ausec);
546 return time_wrap(mrb, mrb_class_ptr(self),
547 time_mktime(mrb, ayear, amonth, aday, ahour, amin, asec, ausec, MRB_TIMEZONE_UTC));
548 }
549
550
551 /* 15.2.19.6.3 */
552 /* Creates an instance of time at the given time in local time zone. */
553 static mrb_value
554 time_local(mrb_state *mrb, mrb_value self)
555 {
556 mrb_int ayear = 0, amonth = 1, aday = 1, ahour = 0, amin = 0, asec = 0, ausec = 0;
557
558 mrb_get_args(mrb, "i|iiiiii",
559 &ayear, &amonth, &aday, &ahour, &amin, &asec, &ausec);
560 return time_wrap(mrb, mrb_class_ptr(self),
561 time_mktime(mrb, ayear, amonth, aday, ahour, amin, asec, ausec, MRB_TIMEZONE_LOCAL));
562 }
563
564 static struct mrb_time*
565 time_get_ptr(mrb_state *mrb, mrb_value time)
566 {
567 struct mrb_time *tm;
568
569 tm = DATA_GET_PTR(mrb, time, &time_type, struct mrb_time);
570 if (!tm) {
571 mrb_raise(mrb, E_ARGUMENT_ERROR, "uninitialized time");
572 }
573 return tm;
574 }
575
576 static mrb_value
577 time_eq(mrb_state *mrb, mrb_value self)
578 {
579 mrb_value other = mrb_get_arg1(mrb);
580 struct mrb_time *tm1, *tm2;
581 mrb_bool eq_p;
582
583 tm1 = DATA_GET_PTR(mrb, self, &time_type, struct mrb_time);
584 tm2 = DATA_CHECK_GET_PTR(mrb, other, &time_type, struct mrb_time);
585 eq_p = tm1 && tm2 && tm1->sec == tm2->sec && tm1->usec == tm2->usec;
586
587 return mrb_bool_value(eq_p);
588 }
589
590 static mrb_value
591 time_cmp(mrb_state *mrb, mrb_value self)
592 {
593 mrb_value other = mrb_get_arg1(mrb);
594 struct mrb_time *tm1, *tm2;
595
596 tm1 = DATA_GET_PTR(mrb, self, &time_type, struct mrb_time);
597 tm2 = DATA_CHECK_GET_PTR(mrb, other, &time_type, struct mrb_time);
598 if (!tm1 || !tm2) return mrb_nil_value();
599 if (tm1->sec > tm2->sec) {
600 return mrb_fixnum_value(1);
601 }
602 else if (tm1->sec < tm2->sec) {
603 return mrb_fixnum_value(-1);
604 }
605 /* tm1->sec == tm2->sec */
606 if (tm1->usec > tm2->usec) {
607 return mrb_fixnum_value(1);
608 }
609 else if (tm1->usec < tm2->usec) {
610 return mrb_fixnum_value(-1);
611 }
612 return mrb_fixnum_value(0);
613 }
614
615 static mrb_noreturn void
616 int_overflow(mrb_state *mrb, const char *reason)
617 {
618 mrb_raisef(mrb, E_RANGE_ERROR, "time_t overflow in Time %s", reason);
619 }
620
621 static mrb_value
622 time_plus(mrb_state *mrb, mrb_value self)
623 {
624 mrb_value o = mrb_get_arg1(mrb);
625 struct mrb_time *tm;
626 time_t sec, usec;
627
628 tm = time_get_ptr(mrb, self);
629 sec = mrb_to_time_t(mrb, o, &usec);
630 #ifdef MRB_HAVE_TYPE_GENERIC_CHECKED_ARITHMETIC_BUILTINS
631 if (__builtin_add_overflow(tm->sec, sec, &sec)) {
632 int_overflow(mrb, "addition");
633 }
634 #else
635 if (sec >= 0) {
636 if (tm->sec > MRB_TIME_MAX - sec) {
637 int_overflow(mrb, "addition");
638 }
639 }
640 else {
641 if (tm->sec < MRB_TIME_MIN - sec) {
642 int_overflow(mrb, "addition");
643 }
644 }
645 sec = tm->sec + sec;
646 #endif
647 return time_make_time(mrb, mrb_obj_class(mrb, self), sec, tm->usec+usec, tm->timezone);
648 }
649
650 static mrb_value
651 time_minus(mrb_state *mrb, mrb_value self)
652 {
653 mrb_value other = mrb_get_arg1(mrb);
654 struct mrb_time *tm, *tm2;
655
656 tm = time_get_ptr(mrb, self);
657 tm2 = DATA_CHECK_GET_PTR(mrb, other, &time_type, struct mrb_time);
658 if (tm2) {
659 #ifndef MRB_NO_FLOAT
660 mrb_float f;
661 f = (mrb_float)(tm->sec - tm2->sec)
662 + (mrb_float)(tm->usec - tm2->usec) / 1.0e6;
663 return mrb_float_value(mrb, f);
664 #else
665 mrb_int f;
666 f = tm->sec - tm2->sec;
667 if (tm->usec < tm2->usec) f--;
668 return mrb_int_value(mrb, f);
669 #endif
670 }
671 else {
672 time_t sec, usec;
673 sec = mrb_to_time_t(mrb, other, &usec);
674 #ifdef MRB_HAVE_TYPE_GENERIC_CHECKED_ARITHMETIC_BUILTINS
675 if (__builtin_sub_overflow(tm->sec, sec, &sec)) {
676 int_overflow(mrb, "subtraction");
677 }
678 #else
679 if (sec >= 0) {
680 if (tm->sec < MRB_TIME_MIN + sec) {
681 int_overflow(mrb, "subtraction");
682 }
683 }
684 else {
685 if (tm->sec > MRB_TIME_MAX + sec) {
686 int_overflow(mrb, "subtraction");
687 }
688 }
689 sec = tm->sec - sec;
690 #endif
691 return time_make_time(mrb, mrb_obj_class(mrb, self), sec, tm->usec-usec, tm->timezone);
692 }
693 }
694
695 /* 15.2.19.7.30 */
696 /* Returns week day number of time. */
697 static mrb_value
698 time_wday(mrb_state *mrb, mrb_value self)
699 {
700 struct mrb_time *tm;
701
702 tm = time_get_ptr(mrb, self);
703 return mrb_fixnum_value(tm->datetime.tm_wday);
704 }
705
706 /* 15.2.19.7.31 */
707 /* Returns year day number of time. */
708 static mrb_value
709 time_yday(mrb_state *mrb, mrb_value self)
710 {
711 struct mrb_time *tm;
712
713 tm = time_get_ptr(mrb, self);
714 return mrb_fixnum_value(tm->datetime.tm_yday + 1);
715 }
716
717 /* 15.2.19.7.32 */
718 /* Returns year of time. */
719 static mrb_value
720 time_year(mrb_state *mrb, mrb_value self)
721 {
722 struct mrb_time *tm;
723
724 tm = time_get_ptr(mrb, self);
725 return mrb_fixnum_value(tm->datetime.tm_year + 1900);
726 }
727
728 static size_t
729 time_zonename(mrb_state *mrb, struct mrb_time *tm, char *buf, size_t len)
730 {
731 #if defined(_MSC_VER) && _MSC_VER < 1900 || defined(__MINGW64__) || defined(__MINGW32__)
732 struct tm datetime = {0};
733 time_t utc_sec = timegm(&tm->datetime);
734 int offset = abs((int)(utc_sec - tm->sec) / 60);
735 datetime.tm_year = 100;
736 datetime.tm_hour = offset / 60;
737 datetime.tm_min = offset % 60;
738 buf[0] = utc_sec < tm->sec ? '-' : '+';
739 return strftime(buf+1, len-1, "%H%M", &datetime) + 1;
740 #else
741 return strftime(buf, len, "%z", &tm->datetime);
742 #endif
743 }
744
745 /* 15.2.19.7.33 */
746 /* Returns name of time's timezone. */
747 static mrb_value
748 time_zone(mrb_state *mrb, mrb_value self)
749 {
750 struct mrb_time *tm = time_get_ptr(mrb, self);
751 if (tm->timezone == MRB_TIMEZONE_UTC) {
752 return mrb_str_new_lit(mrb, "UTC");
753 }
754 char buf[64];
755 size_t len = time_zonename(mrb, tm, buf, sizeof(buf));
756 return mrb_str_new(mrb, buf, len);
757 }
758
759 /* 15.2.19.7.4 */
760 /* Returns a string that describes the time. */
761 static mrb_value
762 time_asctime(mrb_state *mrb, mrb_value self)
763 {
764 struct mrb_time *tm = time_get_ptr(mrb, self);
765 struct tm *d = &tm->datetime;
766 int len;
767
768 #if defined(MRB_NO_STDIO)
769 # ifdef NO_ASCTIME_R
770 char *buf = asctime(d);
771 # else
772 char buf[32], *s;
773 s = asctime_r(d, buf);
774 # endif
775 len = strlen(buf)-1; /* truncate the last newline */
776 #else
777 char buf[32];
778
779 len = snprintf(buf, sizeof(buf), "%s %s %2d %02d:%02d:%02d %.4d",
780 wday_names[d->tm_wday], mon_names[d->tm_mon], d->tm_mday,
781 d->tm_hour, d->tm_min, d->tm_sec,
782 d->tm_year + 1900);
783 #endif
784 return mrb_str_new(mrb, buf, len);
785 }
786
787 /* 15.2.19.7.6 */
788 /* Returns the day in the month of the time. */
789 static mrb_value
790 time_day(mrb_state *mrb, mrb_value self)
791 {
792 struct mrb_time *tm;
793
794 tm = time_get_ptr(mrb, self);
795 return mrb_fixnum_value(tm->datetime.tm_mday);
796 }
797
798
799 /* 15.2.19.7.7 */
800 /* Returns true if daylight saving was applied for this time. */
801 static mrb_value
802 time_dst_p(mrb_state *mrb, mrb_value self)
803 {
804 struct mrb_time *tm;
805
806 tm = time_get_ptr(mrb, self);
807 return mrb_bool_value(tm->datetime.tm_isdst);
808 }
809
810 /* 15.2.19.7.8 */
811 /* 15.2.19.7.10 */
812 /* Returns the Time object of the UTC(GMT) timezone. */
813 static mrb_value
814 time_getutc(mrb_state *mrb, mrb_value self)
815 {
816 struct mrb_time *tm, *tm2;
817
818 tm = time_get_ptr(mrb, self);
819 tm2 = (struct mrb_time*)mrb_malloc(mrb, sizeof(*tm));
820 *tm2 = *tm;
821 tm2->timezone = MRB_TIMEZONE_UTC;
822 time_update_datetime(mrb, tm2, TRUE);
823 return time_wrap(mrb, mrb_obj_class(mrb, self), tm2);
824 }
825
826 /* 15.2.19.7.9 */
827 /* Returns the Time object of the LOCAL timezone. */
828 static mrb_value
829 time_getlocal(mrb_state *mrb, mrb_value self)
830 {
831 struct mrb_time *tm, *tm2;
832
833 tm = time_get_ptr(mrb, self);
834 tm2 = (struct mrb_time*)mrb_malloc(mrb, sizeof(*tm));
835 *tm2 = *tm;
836 tm2->timezone = MRB_TIMEZONE_LOCAL;
837 time_update_datetime(mrb, tm2, TRUE);
838 return time_wrap(mrb, mrb_obj_class(mrb, self), tm2);
839 }
840
841 /* 15.2.19.7.15 */
842 /* Returns hour of time. */
843 static mrb_value
844 time_hour(mrb_state *mrb, mrb_value self)
845 {
846 struct mrb_time *tm;
847
848 tm = time_get_ptr(mrb, self);
849 return mrb_fixnum_value(tm->datetime.tm_hour);
850 }
851
852 /* 15.2.19.7.16 */
853 /* Initializes a time by setting the amount of milliseconds since the epoch.*/
854 static mrb_value
855 time_init(mrb_state *mrb, mrb_value self)
856 {
857 mrb_int ayear = 0, amonth = 1, aday = 1, ahour = 0,
858 amin = 0, asec = 0, ausec = 0;
859 mrb_int n;
860 struct mrb_time *tm;
861
862 n = mrb_get_args(mrb, "|iiiiiii",
863 &ayear, &amonth, &aday, &ahour, &amin, &asec, &ausec);
864 tm = (struct mrb_time*)DATA_PTR(self);
865 if (tm) {
866 mrb_free(mrb, tm);
867 }
868 mrb_data_init(self, NULL, &time_type);
869
870 if (n == 0) {
871 tm = current_mrb_time(mrb);
872 }
873 else {
874 tm = time_mktime(mrb, ayear, amonth, aday, ahour, amin, asec, ausec, MRB_TIMEZONE_LOCAL);
875 }
876 mrb_data_init(self, tm, &time_type);
877 return self;
878 }
879
880 /* 15.2.19.7.17(x) */
881 /* Initializes a copy of this time object. */
882 static mrb_value
883 time_init_copy(mrb_state *mrb, mrb_value copy)
884 {
885 mrb_value src = mrb_get_arg1(mrb);
886 struct mrb_time *t1, *t2;
887
888 if (mrb_obj_equal(mrb, copy, src)) return copy;
889 if (!mrb_obj_is_instance_of(mrb, src, mrb_obj_class(mrb, copy))) {
890 mrb_raise(mrb, E_TYPE_ERROR, "wrong argument class");
891 }
892 t1 = (struct mrb_time*)DATA_PTR(copy);
893 t2 = (struct mrb_time*)DATA_PTR(src);
894 if (!t2) {
895 mrb_raise(mrb, E_ARGUMENT_ERROR, "uninitialized time");
896 }
897 if (!t1) {
898 t1 = (struct mrb_time*)mrb_malloc(mrb, sizeof(struct mrb_time));
899 mrb_data_init(copy, t1, &time_type);
900 }
901 *t1 = *t2;
902 return copy;
903 }
904
905 /* 15.2.19.7.18 */
906 /* Sets the timezone attribute of the Time object to LOCAL. */
907 static mrb_value
908 time_localtime(mrb_state *mrb, mrb_value self)
909 {
910 struct mrb_time *tm;
911
912 tm = time_get_ptr(mrb, self);
913 tm->timezone = MRB_TIMEZONE_LOCAL;
914 time_update_datetime(mrb, tm, FALSE);
915 return self;
916 }
917
918 /* 15.2.19.7.19 */
919 /* Returns day of month of time. */
920 static mrb_value
921 time_mday(mrb_state *mrb, mrb_value self)
922 {
923 struct mrb_time *tm;
924
925 tm = time_get_ptr(mrb, self);
926 return mrb_fixnum_value(tm->datetime.tm_mday);
927 }
928
929 /* 15.2.19.7.20 */
930 /* Returns minutes of time. */
931 static mrb_value
932 time_min(mrb_state *mrb, mrb_value self)
933 {
934 struct mrb_time *tm;
935
936 tm = time_get_ptr(mrb, self);
937 return mrb_fixnum_value(tm->datetime.tm_min);
938 }
939
940 /* 15.2.19.7.21 (mon) and 15.2.19.7.22 (month) */
941 /* Returns month of time. */
942 static mrb_value
943 time_mon(mrb_state *mrb, mrb_value self)
944 {
945 struct mrb_time *tm;
946
947 tm = time_get_ptr(mrb, self);
948 return mrb_fixnum_value(tm->datetime.tm_mon + 1);
949 }
950
951 /* 15.2.19.7.23 */
952 /* Returns seconds in minute of time. */
953 static mrb_value
954 time_sec(mrb_state *mrb, mrb_value self)
955 {
956 struct mrb_time *tm;
957
958 tm = time_get_ptr(mrb, self);
959 return mrb_fixnum_value(tm->datetime.tm_sec);
960 }
961
962 #ifndef MRB_NO_FLOAT
963 /* 15.2.19.7.24 */
964 /* Returns a Float with the time since the epoch in seconds. */
965 static mrb_value
966 time_to_f(mrb_state *mrb, mrb_value self)
967 {
968 struct mrb_time *tm;
969
970 tm = time_get_ptr(mrb, self);
971 return mrb_float_value(mrb, (mrb_float)tm->sec + (mrb_float)tm->usec/1.0e6);
972 }
973 #endif
974
975 /* 15.2.19.7.25 */
976 /* Returns an Integer with the time since the epoch in seconds. */
977 static mrb_value
978 time_to_i(mrb_state *mrb, mrb_value self)
979 {
980 struct mrb_time *tm;
981
982 tm = time_get_ptr(mrb, self);
983 return time_value_from_time_t(mrb, tm->sec);
984 }
985
986 /* 15.2.19.7.26 */
987 /* Returns the number of microseconds for time. */
988 static mrb_value
989 time_usec(mrb_state *mrb, mrb_value self)
990 {
991 struct mrb_time *tm;
992
993 tm = time_get_ptr(mrb, self);
994 return mrb_fixnum_value((mrb_int)tm->usec);
995 }
996
997 /* 15.2.19.7.27 */
998 /* Sets the timezone attribute of the Time object to UTC. */
999 static mrb_value
1000 time_utc(mrb_state *mrb, mrb_value self)
1001 {
1002 struct mrb_time *tm;
1003
1004 tm = time_get_ptr(mrb, self);
1005 tm->timezone = MRB_TIMEZONE_UTC;
1006 time_update_datetime(mrb, tm, FALSE);
1007 return self;
1008 }
1009
1010 /* 15.2.19.7.28 */
1011 /* Returns true if this time is in the UTC timezone false if not. */
1012 static mrb_value
1013 time_utc_p(mrb_state *mrb, mrb_value self)
1014 {
1015 struct mrb_time *tm;
1016
1017 tm = time_get_ptr(mrb, self);
1018 return mrb_bool_value(tm->timezone == MRB_TIMEZONE_UTC);
1019 }
1020
1021 static mrb_value
1022 time_to_s(mrb_state *mrb, mrb_value self)
1023 {
1024 struct mrb_time *tm = time_get_ptr(mrb, self);
1025 char buf[64];
1026 size_t len;
1027
1028 if (tm->timezone == MRB_TIMEZONE_UTC) {
1029 len = strftime(buf, sizeof(buf), TO_S_FMT "UTC", &tm->datetime);
1030 }
1031 else {
1032 len = strftime(buf, sizeof(buf), TO_S_FMT, &tm->datetime);
1033 len += time_zonename(mrb, tm, buf+len, sizeof(buf)-len);
1034 }
1035 mrb_value str = mrb_str_new(mrb, buf, len);
1036 RSTR_SET_ASCII_FLAG(mrb_str_ptr(str));
1037 return str;
1038 }
1039
1040 static mrb_value
1041 time_hash(mrb_state *mrb, mrb_value self)
1042 {
1043 struct mrb_time *tm = time_get_ptr(mrb, self);
1044 uint32_t hash = mrb_byte_hash((uint8_t*)&tm->sec, sizeof(time_t));
1045 hash = mrb_byte_hash_step((uint8_t*)&tm->usec, sizeof(time_t), hash);
1046 hash = mrb_byte_hash_step((uint8_t*)&tm->timezone, sizeof(tm->timezone), hash);
1047 return mrb_int_value(mrb, hash);
1048 }
1049
1050 #define wday_impl(num) \
1051 struct mrb_time *tm = time_get_ptr(mrb, self);\
1052 return mrb_bool_value(tm->datetime.tm_wday == (num));
1053
1054 static mrb_value
1055 time_sunday(mrb_state *mrb, mrb_value self)
1056 {
1057 wday_impl(0);
1058 }
1059
1060 static mrb_value
1061 time_monday(mrb_state *mrb, mrb_value self)
1062 {
1063 wday_impl(1);
1064 }
1065
1066 static mrb_value
1067 time_tuesday(mrb_state *mrb, mrb_value self)
1068 {
1069 wday_impl(2);
1070 }
1071
1072 static mrb_value
1073 time_wednesday(mrb_state *mrb, mrb_value self)
1074 {
1075 wday_impl(3);
1076 }
1077
1078 static mrb_value
1079 time_thursday(mrb_state *mrb, mrb_value self)
1080 {
1081 wday_impl(4);
1082 }
1083
1084 static mrb_value
1085 time_friday(mrb_state *mrb, mrb_value self)
1086 {
1087 wday_impl(5);
1088 }
1089
1090 static mrb_value
1091 time_saturday(mrb_state *mrb, mrb_value self)
1092 {
1093 wday_impl(6);
1094 }
1095
1096 void
1097 mrb_mruby_time_gem_init(mrb_state* mrb)
1098 {
1099 struct RClass *tc;
1100 /* ISO 15.2.19.2 */
1101 tc = mrb_define_class(mrb, "Time", mrb->object_class);
1102 MRB_SET_INSTANCE_TT(tc, MRB_TT_CDATA);
1103 mrb_include_module(mrb, tc, mrb_module_get(mrb, "Comparable"));
1104 mrb_define_class_method(mrb, tc, "at", time_at_m, MRB_ARGS_ARG(1, 1)); /* 15.2.19.6.1 */
1105 mrb_define_class_method(mrb, tc, "gm", time_gm, MRB_ARGS_ARG(1,6)); /* 15.2.19.6.2 */
1106 mrb_define_class_method(mrb, tc, "local", time_local, MRB_ARGS_ARG(1,6)); /* 15.2.19.6.3 */
1107 mrb_define_class_method(mrb, tc, "mktime", time_local, MRB_ARGS_ARG(1,6));/* 15.2.19.6.4 */
1108 mrb_define_class_method(mrb, tc, "now", time_now, MRB_ARGS_NONE()); /* 15.2.19.6.5 */
1109 mrb_define_class_method(mrb, tc, "utc", time_gm, MRB_ARGS_ARG(1,6)); /* 15.2.19.6.6 */
1110
1111 mrb_define_method(mrb, tc, "hash" , time_hash , MRB_ARGS_NONE());
1112 mrb_define_method(mrb, tc, "eql?" , time_eq , MRB_ARGS_REQ(1));
1113 mrb_define_method(mrb, tc, "==" , time_eq , MRB_ARGS_REQ(1));
1114 mrb_define_method(mrb, tc, "<=>" , time_cmp , MRB_ARGS_REQ(1)); /* 15.2.19.7.1 */
1115 mrb_define_method(mrb, tc, "+" , time_plus , MRB_ARGS_REQ(1)); /* 15.2.19.7.2 */
1116 mrb_define_method(mrb, tc, "-" , time_minus , MRB_ARGS_REQ(1)); /* 15.2.19.7.3 */
1117 mrb_define_method(mrb, tc, "to_s" , time_to_s , MRB_ARGS_NONE());
1118 mrb_define_method(mrb, tc, "inspect", time_to_s , MRB_ARGS_NONE());
1119 mrb_define_method(mrb, tc, "asctime", time_asctime, MRB_ARGS_NONE()); /* 15.2.19.7.4 */
1120 mrb_define_method(mrb, tc, "ctime" , time_asctime, MRB_ARGS_NONE()); /* 15.2.19.7.5 */
1121 mrb_define_method(mrb, tc, "day" , time_day , MRB_ARGS_NONE()); /* 15.2.19.7.6 */
1122 mrb_define_method(mrb, tc, "dst?" , time_dst_p , MRB_ARGS_NONE()); /* 15.2.19.7.7 */
1123 mrb_define_method(mrb, tc, "getgm" , time_getutc , MRB_ARGS_NONE()); /* 15.2.19.7.8 */
1124 mrb_define_method(mrb, tc, "getlocal",time_getlocal,MRB_ARGS_NONE()); /* 15.2.19.7.9 */
1125 mrb_define_method(mrb, tc, "getutc" , time_getutc , MRB_ARGS_NONE()); /* 15.2.19.7.10 */
1126 mrb_define_method(mrb, tc, "gmt?" , time_utc_p , MRB_ARGS_NONE()); /* 15.2.19.7.11 */
1127 mrb_define_method(mrb, tc, "gmtime" , time_utc , MRB_ARGS_NONE()); /* 15.2.19.7.13 */
1128 mrb_define_method(mrb, tc, "hour" , time_hour, MRB_ARGS_NONE()); /* 15.2.19.7.15 */
1129 mrb_define_method(mrb, tc, "localtime", time_localtime, MRB_ARGS_NONE()); /* 15.2.19.7.18 */
1130 mrb_define_method(mrb, tc, "mday" , time_mday, MRB_ARGS_NONE()); /* 15.2.19.7.19 */
1131 mrb_define_method(mrb, tc, "min" , time_min, MRB_ARGS_NONE()); /* 15.2.19.7.20 */
1132
1133 mrb_define_method(mrb, tc, "mon" , time_mon, MRB_ARGS_NONE()); /* 15.2.19.7.21 */
1134 mrb_define_method(mrb, tc, "month", time_mon, MRB_ARGS_NONE()); /* 15.2.19.7.22 */
1135
1136 mrb_define_method(mrb, tc, "sec" , time_sec, MRB_ARGS_NONE()); /* 15.2.19.7.23 */
1137 mrb_define_method(mrb, tc, "to_i", time_to_i, MRB_ARGS_NONE()); /* 15.2.19.7.25 */
1138 #ifndef MRB_NO_FLOAT
1139 mrb_define_method(mrb, tc, "to_f", time_to_f, MRB_ARGS_NONE()); /* 15.2.19.7.24 */
1140 #endif
1141 mrb_define_method(mrb, tc, "usec", time_usec, MRB_ARGS_NONE()); /* 15.2.19.7.26 */
1142 mrb_define_method(mrb, tc, "utc" , time_utc, MRB_ARGS_NONE()); /* 15.2.19.7.27 */
1143 mrb_define_method(mrb, tc, "utc?", time_utc_p,MRB_ARGS_NONE()); /* 15.2.19.7.28 */
1144 mrb_define_method(mrb, tc, "wday", time_wday, MRB_ARGS_NONE()); /* 15.2.19.7.30 */
1145 mrb_define_method(mrb, tc, "yday", time_yday, MRB_ARGS_NONE()); /* 15.2.19.7.31 */
1146 mrb_define_method(mrb, tc, "year", time_year, MRB_ARGS_NONE()); /* 15.2.19.7.32 */
1147 mrb_define_method(mrb, tc, "zone", time_zone, MRB_ARGS_NONE()); /* 15.2.19.7.33 */
1148
1149 mrb_define_method(mrb, tc, "initialize", time_init, MRB_ARGS_REQ(1)); /* 15.2.19.7.16 */
1150 mrb_define_method(mrb, tc, "initialize_copy", time_init_copy, MRB_ARGS_REQ(1)); /* 15.2.19.7.17 */
1151
1152 mrb_define_method(mrb, tc, "sunday?", time_sunday, MRB_ARGS_NONE());
1153 mrb_define_method(mrb, tc, "monday?", time_monday, MRB_ARGS_NONE());
1154 mrb_define_method(mrb, tc, "tuesday?", time_tuesday, MRB_ARGS_NONE());
1155 mrb_define_method(mrb, tc, "wednesday?", time_wednesday, MRB_ARGS_NONE());
1156 mrb_define_method(mrb, tc, "thursday?", time_thursday, MRB_ARGS_NONE());
1157 mrb_define_method(mrb, tc, "friday?", time_friday, MRB_ARGS_NONE());
1158 mrb_define_method(mrb, tc, "saturday?", time_saturday, MRB_ARGS_NONE());
1159
1160 /*
1161 methods not available:
1162 gmt_offset(15.2.19.7.12)
1163 gmtoff(15.2.19.7.14)
1164 utc_offset(15.2.19.7.29)
1165 */
1166 }
1167
1168 void
1169 mrb_mruby_time_gem_final(mrb_state* mrb)
1170 {
1171 }