summaryrefslogtreecommitdiff
path: root/lib/date/delta.rb
blob: e524cbc324e26940e68ed949b9c1b4be6617ebf5 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
# delta.rb: Written by Tadayoshi Funaba 2004-2010

require 'date'
require 'date/delta/parser'

class Date

  class Delta # :nodoc:

    include Comparable

    UNIT_PREFIXES = {
      'yotta'      => Rational(10**24),
      'zetta'      => Rational(10**21),
      'exa'        => Rational(10**18),
      'peta'       => Rational(10**15),
      'tera'       => Rational(10**12),
      'giga'       => Rational(10**9),
      'mega'       => Rational(10**6),
      'kilo'       => Rational(10**3),
      'hecto'      => Rational(10**2),
      'deca'       => Rational(10**1),
      'deka'       => Rational(10**1),
      'deci'       => Rational(1, 10**1),
      'centi'      => Rational(1, 10**2),
      'milli'      => Rational(1, 10**3),
      'decimilli'  => Rational(1, 10**4),
      'centimilli' => Rational(1, 10**5),
      'micro'      => Rational(1, 10**6),
      'nano'       => Rational(1, 10**9),
      'millimicro' => Rational(1, 10**9),
      'pico'       => Rational(1, 10**12),
      'micromicro' => Rational(1, 10**12),
      'femto'      => Rational(1, 10**15),
      'atto'       => Rational(1, 10**18),
      'zepto'      => Rational(1, 10**21),
      'yocto'      => Rational(1, 10**24)
    }

    IUNITS = {
      'year'       => Complex(0, 12),
      'month'      => Complex(0, 1)
    }

    RUNITS = {
      'day'        => Rational(1),
      'week'       => Rational(7),
      'sennight'   => Rational(7),
      'fortnight'  => Rational(14),
      'hour'       => Rational(1, 24),
      'minute'     => Rational(1, 1440),
      'second'     => Rational(1, 86400)
    }

    UNIT_PREFIXES.each do |k, v|
      RUNITS[k + 'second'] = v * RUNITS['second']
    end

    remove_const :UNIT_PREFIXES

    UNITS = {}

    IUNITS.each do |k, v|
      UNITS[k] = v
    end

    RUNITS.each do |k, v|
      UNITS[k] = v
    end

    UNITS4KEY = {}

    UNITS.each do |k, v|
      UNITS4KEY[k] = UNITS4KEY[k + 's'] = v
    end

    UNITS4KEY['y'] = UNITS4KEY['years']
    UNITS4KEY['yr'] = UNITS4KEY['years']
    UNITS4KEY['yrs'] = UNITS4KEY['years']
    UNITS4KEY['m'] = UNITS4KEY['months']
    UNITS4KEY['mo'] = UNITS4KEY['months']
    UNITS4KEY['mon'] = UNITS4KEY['months']
    UNITS4KEY['mnth'] = UNITS4KEY['months']
    UNITS4KEY['mnths'] = UNITS4KEY['months']
    UNITS4KEY['w'] = UNITS4KEY['weeks']
    UNITS4KEY['wk'] = UNITS4KEY['weeks']
    UNITS4KEY['d'] = UNITS4KEY['days']
    UNITS4KEY['dy'] = UNITS4KEY['days']
    UNITS4KEY['dys'] = UNITS4KEY['days']
    UNITS4KEY['h'] = UNITS4KEY['hours']
    UNITS4KEY['hr'] = UNITS4KEY['hours']
    UNITS4KEY['hrs'] = UNITS4KEY['hours']
    UNITS4KEY['min'] = UNITS4KEY['minutes']
    UNITS4KEY['mins'] = UNITS4KEY['minutes']
    UNITS4KEY['s'] = UNITS4KEY['seconds']
    UNITS4KEY['sec'] = UNITS4KEY['seconds']
    UNITS4KEY['secs'] = UNITS4KEY['seconds']
    UNITS4KEY['ms'] = UNITS4KEY['milliseconds']
    UNITS4KEY['msec'] = UNITS4KEY['milliseconds']
    UNITS4KEY['msecs'] = UNITS4KEY['milliseconds']
    UNITS4KEY['milli'] = UNITS4KEY['milliseconds']
    UNITS4KEY['us'] = UNITS4KEY['microseconds']
    UNITS4KEY['usec'] = UNITS4KEY['microseconds']
    UNITS4KEY['usecs'] = UNITS4KEY['microseconds']
    UNITS4KEY['micro'] = UNITS4KEY['microseconds']
    UNITS4KEY['ns'] = UNITS4KEY['nanoseconds']
    UNITS4KEY['nsec'] = UNITS4KEY['nanoseconds']
    UNITS4KEY['nsecs'] = UNITS4KEY['nanoseconds']
    UNITS4KEY['nano'] = UNITS4KEY['nanoseconds']

    def self.delta_to_dhms(delta)
      fr = delta.imag.abs
      y,   fr = fr.divmod(12)
      m,   fr = fr.divmod(1)

      if delta.imag < 0
	y = -y
	m = -m
      end

      fr = delta.real.abs
      ss,  fr = fr.divmod(SECONDS_IN_DAY) # 4p
      d,   ss = ss.divmod(86400)
      h,   ss = ss.divmod(3600)
      min, s  = ss.divmod(60)

      if delta.real < 0
	d = -d
	h = -h
	min = -min
	s = -s
      end

      return y, m, d, h, min, s, fr
    end

    def self.dhms_to_delta(y, m, d, h, min, s, fr)
      fr = 0 if fr == 0
      Complex(0, y.to_i * 12 + m.to_i) +
	Rational(d * 86400 + h * 3600 + min * 60 + (s + fr), 86400) # 4p
    end

    def initialize(delta)
      @delta = delta
      @__ca__ = {}
    end

    class << self; alias_method :new!, :new end

    def self.new(arg=0, h=0, min=0, s=0)
      if Hash === arg
	d = Complex(0)
	arg.each do |k, v|
	  k = k.to_s.downcase
	  unless UNITS4KEY[k]
	    raise ArgumentError, "unknown keyword #{k}"
	  end
	  d += v * UNITS4KEY[k]
	end
      else
	d = dhms_to_delta(0, 0, arg, h, min, s, 0)
      end
      new!(d)
    end

    UNITS.each_key do |k|
      module_eval <<-"end;"
	def self.#{k}s(n=1)
	  new(:d=>n * UNITS['#{k}'])
	end
      end;
    end

    class << self; alias_method :mins, :minutes end
    class << self; alias_method :secs, :seconds end

    def self.parse(str)
      d = begin (@@pa ||= Parser.new).parse(str)
	  rescue Racc::ParseError
	    raise ArgumentError, 'syntax error'
	  end
      new!(d)
    end

    def self.diff(d1, d2) new(d1.ajd - d2.ajd) end

    class << self

      def once(*ids) # :nodoc: -- restricted
	for id in ids
	  module_eval <<-"end;"
	    alias_method :__#{id.object_id}__, :#{id.to_s}
	    private :__#{id.object_id}__
	    def #{id.to_s}(*args)
	      @__ca__[#{id.object_id}] ||= __#{id.object_id}__(*args)
	    end
	  end;
        end
      end

      private :once

    end

    def dhms() self.class.delta_to_dhms(@delta) end

    once :dhms

    def delta() @delta end

    protected :delta

    def years() dhms[0] end
    def months() dhms[1] end
    def days() dhms[2] end
    def hours() dhms[3] end
    def minutes() dhms[4] end
    def seconds() dhms[5] end
    def second_fractions() dhms[6] end

    alias_method :mins, :minutes
    alias_method :secs, :seconds
    alias_method :sec_fractions, :second_fractions

    RUNITS.each_key do |k|
      module_eval <<-"end;"
	def in_#{k}s(u=1)
	  if @delta.imag != 0
	    raise ArgumentError, "#{k}: #{self} has month"
	  end
	  @delta.real / (u * RUNITS['#{k}'])
	end
      end;
    end # <<dummy

    alias_method :in_mins, :in_minutes
    alias_method :in_secs, :in_seconds

    def zero?() @delta.zero? end
    def nonzero?() unless zero? then self end end

    def integer? () @delta.imag == 0 && @delta.real.integer? end

    def -@ () self.class.new!(-@delta) end
    def +@ () self.class.new!(+@delta) end

    def dx_addsub(m, n)
      case n
      when Numeric; return self.class.new!(@delta.__send__(m, n))
      when Delta; return self.class.new!(@delta.__send__(m, n.delta))
      else
	l, r = n.coerce(self)
	return l.__send__(m, r)
      end
    end

    private :dx_addsub

    def + (n) dx_addsub(:+, n) end
    def - (n) dx_addsub(:-, n) end

    def dx_muldiv(m, n)
      case n
      when Numeric
	return self.class.new!(@delta.__send__(m, n))
      else
	l, r = n.coerce(self)
	return l.__send__(m, r)
      end
    end

    private :dx_muldiv

    def * (n) dx_muldiv(:*, n) end
    def / (n) dx_muldiv(:/, n) end

    def dx_conv1(m, n)
      if @delta.imag != 0
	raise ArgumentError, "#{m}: #{self} has month"
      end
      case n
      when Numeric
	return self.class.new!(Complex(@delta.real.__send__(m, n), 0))
      else
	l, r = n.coerce(self)
	return l.__send__(m, r)
      end
    end

    private :dx_conv1

    def % (n) dx_conv1(:%, n) end

    def div(n) dx_conv1(:div, n) end
    def modulo(n) dx_conv1(:modulo, n) end
    def divmod(n) [div(n), modulo(n)] end

    def quotient(n)
      if @delta.imag != 0
	raise ArgumentError, "quotient: #{self} has month"
      end
      case n
      when Numeric
	return self.class.new!(Complex((@delta.real / n).truncate))
      else
	l, r = n.coerce(self)
	return l.__send__(m, r)
      end
    end

    def remainder(n) dx_conv1(:remainder, n) end
    def quotrem(n) [quotient(n), remainder(n)] end

    def ** (n) dx_conv1(:**, n) end
    def quo(n) dx_muldiv(:quo, n) end

    def <=> (other)
      if @delta.imag != 0
	raise ArgumentError, "<=>: #{self} has month"
      end
      case other
      when Numeric; return @delta.real <=> other
      when Delta;   return @delta.real <=> other.delta.real
      else
	begin
	  l, r = other.coerce(self)
	  return l <=> r
	rescue NoMethodError
	end
      end
      nil
    end

    def == (other)
      case other
      when Numeric; return @delta == other
      when Delta;   return @delta == other
      else
	begin
	  l, r = other.coerce(self)
	  return l == r
	rescue NoMethodError
	end
      end
      nil
    end

    def coerce(other)
      case other
      when Numeric; return other, @delta
      else
	super
      end
    end

    def eql? (other) Delta === other && self == other end
    def hash() @delta.hash end

    def dx_conv0(m)
      if @delta.imag != 0
	raise ArgumentError, "#{m}: #{self} has month"
      end
      @delta.real.__send__(m)
    end

    private :dx_conv0

    def abs() dx_conv0(:abs) end

    def ceil() dx_conv0(:ceil) end
    def floor() dx_conv0(:floor) end
    def round() dx_conv0(:round) end
    def truncate() dx_conv0(:truncate) end

    def to_i() dx_conv0(:to_i) end
    def to_f() dx_conv0(:to_f) end
    def to_r() dx_conv0(:to_r) end
    def to_c() @delta end

    alias_method :to_int, :to_i

    def inspect() format('#<%s: %s (%s)>', self.class, to_s, @delta) end

    def to_s
      format(%(%s(%dd %.02d:%02d'%02d"%03d)%s(%dy %dm)), # '
	     if @delta.real < 0 then '-' else '+' end,
	     days.abs, hours.abs, mins.abs, secs.abs, sec_fractions.abs * 1000,
	     if @delta.imag < 0 then '-' else '+' end,
	     years.abs, months.abs)
    end

    def marshal_dump() @delta end

    def marshal_load(a)
      @delta = a
      @__ca__ = {}
    end

  end

end

vsave = $VERBOSE
$VERBOSE = false

class Date

  def + (n)
    case n
    when Numeric; return self.class.new!(@ajd + n, @of, @sg)
    when Delta
      d = n.__send__(:delta)
      return (self >> d.imag) + d.real
    end
    raise TypeError, 'expected numeric'
  end

  def - (x)
    case x
    when Numeric; return self.class.new!(@ajd - x, @of, @sg)
    when Date;    return @ajd - x.ajd
    when Delta
      d = x.__send__(:delta)
      return (self << d.imag) - d.real
    end
    raise TypeError, 'expected numeric'
  end

end

$VERBOSE = vsave