From f5415a95ce1d393a3fd1d7f657ba85d85171356a Mon Sep 17 00:00:00 2001 From: manga_osyo Date: Sat, 16 Mar 2019 14:42:24 +0900 Subject: Add `Time#ceil`. Closes: https://github.com/ruby/ruby/pull/2133 --- time.c | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) (limited to 'time.c') diff --git a/time.c b/time.c index ac9a13d7fd..d9729aee30 100644 --- a/time.c +++ b/time.c @@ -4286,6 +4286,67 @@ time_floor(int argc, VALUE *argv, VALUE time) return time_add(tobj, time, v, -1); } +/* + * call-seq: + * time.ceil([ndigits]) -> new_time + * + * Ceils sub seconds to a given precision in decimal digits (0 digits by default). + * It returns a new Time object. + * +ndigits+ should be zero or a positive integer. + * + * require 'time' + * + * t = Time.utc(2010,3,30, 5,43,"25.0123456789".to_r) + * t.iso8601(10) #=> "2010-03-30T05:43:25.0123456789Z" + * t.ceil.iso8601(10) #=> "2010-03-30T05:43:26.0000000000Z" + * t.ceil(0).iso8601(10) #=> "2010-03-30T05:43:26.0000000000Z" + * t.ceil(1).iso8601(10) #=> "2010-03-30T05:43:25.1000000000Z" + * t.ceil(2).iso8601(10) #=> "2010-03-30T05:43:25.0200000000Z" + * t.ceil(3).iso8601(10) #=> "2010-03-30T05:43:25.0130000000Z" + * t.ceil(4).iso8601(10) #=> "2010-03-30T05:43:25.0124000000Z" + * + * t = Time.utc(1999,12,31, 23,59,59) + * (t + 0.4).ceil.iso8601(3) #=> "2000-01-01T00:00:00.000Z" + * (t + 0.9).ceil.iso8601(3) #=> "2000-01-01T00:00:00.000Z" + * (t + 1.4).ceil.iso8601(3) #=> "2000-01-01T00:00:01.000Z" + * (t + 1.9).ceil.iso8601(3) #=> "2000-01-01T00:00:01.000Z" + * + * t = Time.utc(1999,12,31, 23,59,59) + * (t + 0.123456789).ceil(4).iso8601(6) #=> "1999-12-31T23:59:59.123500Z" + */ + +static VALUE +time_ceil(int argc, VALUE *argv, VALUE time) +{ + VALUE ndigits, v, a, b, den; + long nd; + struct time_object *tobj; + + if (!rb_check_arity(argc, 0, 1) || NIL_P(ndigits = argv[0])) + ndigits = INT2FIX(0); + else + ndigits = rb_to_int(ndigits); + + nd = NUM2LONG(ndigits); + if (nd < 0) + rb_raise(rb_eArgError, "negative ndigits given"); + + GetTimeval(time, tobj); + v = w2v(rb_time_unmagnify(tobj->timew)); + + a = INT2FIX(1); + b = INT2FIX(10); + while (0 < nd) { + if (nd & 1) + a = mulv(a, b); + b = mulv(b, b); + nd = nd >> 1; + } + den = quov(INT2FIX(1), a); + v = modv(v, den); + return time_add(tobj, time, subv(den, v), 1); +} + /* * call-seq: * time.sec -> integer @@ -5689,6 +5750,7 @@ Init_Time(void) rb_define_method(rb_cTime, "succ", time_succ, 0); rb_define_method(rb_cTime, "round", time_round, -1); rb_define_method(rb_cTime, "floor", time_floor, -1); + rb_define_method(rb_cTime, "ceil", time_ceil, -1); rb_define_method(rb_cTime, "sec", time_sec, 0); rb_define_method(rb_cTime, "min", time_min, 0); -- cgit v1.2.3