diff options
author | manga_osyo <manga.osyo@gmail.com> | 2019-03-16 14:42:24 +0900 |
---|---|---|
committer | Nobuyoshi Nakada <nobu@ruby-lang.org> | 2019-05-23 22:30:19 +0900 |
commit | f5415a95ce1d393a3fd1d7f657ba85d85171356a (patch) | |
tree | 6cbc9cdcba1020be455ed96bf7e90cd28fc7b7e1 /time.c | |
parent | fe3ff5afb07e171fd950623c69abfbabbb2762a3 (diff) | |
download | ruby-f5415a95ce1d393a3fd1d7f657ba85d85171356a.tar.gz |
Add `Time#ceil`.
Closes: https://github.com/ruby/ruby/pull/2133
Diffstat (limited to 'time.c')
-rw-r--r-- | time.c | 62 |
1 files changed, 62 insertions, 0 deletions
@@ -4287,6 +4287,67 @@ time_floor(int argc, VALUE *argv, VALUE time) } /* + * 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); |