edtf 4.1.1 → 5.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/lib/edtf/date.rb CHANGED
@@ -1,373 +1,524 @@
1
- class Date
2
-
3
- PRECISION = [:year, :month, :day].freeze
4
- PRECISIONS = Hash[*PRECISION.map { |p| [p, "#{p}s".to_sym] }.flatten].freeze
1
+ module EDTF
2
+
3
+ # EDTF dates extend the regular Ruby Date class.
4
+ # Every EDTF date acts as you would normally expect,
5
+ # but provides additional functionality.
6
+ #
7
+ # Most notably, EDTF dates come in day, month, or year precision.
8
+ # This is a subtle difference that determines how many other methods work:
9
+ # the bounds, stepping with `succ`, `prev`, `upto` and `downto`,
10
+ # and the EDTF string all follow the precision.
11
+ # Dates are proleptic Gregorian unless in another calendar Ruby supports
12
+ # (calendar: :julian, :italy, :england, or the Julian day of a reform).
13
+ # Years are astronomical (0 is 1 BC), as in ISO 8601;
14
+ # with year_zero: false, they are written without year 0 (1 BC is -0001),
15
+ # and unspecified digits apply to the written year.
16
+ # Dates can also be uncertain, approximate, or have unspecified digits,
17
+ # marked by bitmasks.
18
+ #
19
+ # Years of any size are written with a Y prefix beyond four digits (Y17002),
20
+ # and may have significant digits (1950S2 spans 1900 to 1999).
21
+ #
22
+ # Dates are frozen; use `with` for a modified copy.
23
+ # Date math (+, -, >>, <<) and calendar conversions return plain dates,
24
+ # because the result no longer stands for the same EDTF string.
25
+ # Create dates with `new`, `EDTF()` or `EDTF.parse`;
26
+ # Ruby's other constructors (today, parse, …) are private.
27
+ class Date < ::Date
28
+ include Period
29
+
30
+ PRECISION = %i[year month day].freeze
31
+
32
+ # The masks that cover the whole date, by number of values.
33
+ MASKS = [
34
+ nil,
35
+ Bitmask::YEAR,
36
+ Bitmask::YM,
37
+ Bitmask::YMD
38
+ ].freeze
39
+
40
+ QUALIFIERS = %i[
41
+ uncertain approximate unspecified significant
42
+ ].freeze
43
+
44
+ ATTRIBUTES = [*PRECISION, :precision, *QUALIFIERS].freeze
45
+
46
+ # Ruby's constructors skip initialize, so their dates would not be frozen.
47
+ private_class_method(*%i[
48
+ today civil jd ordinal commercial parse strptime
49
+ iso8601 rfc3339 xmlschema rfc2822 rfc822 httpdate jisx0301
50
+ ].select { |name| ::Date.respond_to?(name) })
51
+
52
+ DATE_MARSHAL = %i[marshal_dump marshal_load].to_h { |name|
53
+ [name, ::Date.instance_method(name)]
54
+ }.freeze
55
+ private_constant :DATE_MARSHAL
56
+
57
+ # JRuby's Date.new is a native Date.civil that skips initialize.
58
+ def self.new(...)
59
+ allocate.tap { |date| date.send(:initialize, ...) }
60
+ end
5
61
 
6
- FORMATS = %w{ %04d %02d %02d }.freeze
62
+ def initialize(
63
+ year,
64
+ month = nil,
65
+ day = nil,
66
+ uncertain: nil,
67
+ approximate: nil,
68
+ unspecified: nil,
69
+ significant: nil,
70
+ calendar: nil,
71
+ year_zero: true
72
+ )
73
+ values = [year, month, day].compact
74
+ raise ArgumentError, 'day given without month' if day && month.nil?
75
+
76
+ start = Period.start(calendar)
77
+ if month == 2 && day == 29
78
+ leap = Date.leap_years(year, unspecified, start, year_zero).first
79
+ year = leap || year
80
+ end
7
81
 
8
- SYMBOLS = {
9
- :uncertain => '?',
10
- :approximate => '~',
11
- :calendar => '^',
12
- :unspecified => 'X'
13
- }.freeze
82
+ # Ruby's Date#initialize takes other arguments on JRuby;
83
+ # both read the day from a plain date's Marshal data.
84
+ DATE_MARSHAL[:marshal_load].bind_call(
85
+ self,
86
+ ::Date.civil(year, month || 1, day || 1, start).marshal_dump)
87
+
88
+ @precision = PRECISION[values.length - 1]
89
+ @uncertain = bits(uncertain)
90
+ @approximate = bits(approximate)
91
+ @unspecified = bits(unspecified)
92
+ @significant = significant && Integer(significant)
93
+ @historical = !year_zero
94
+
95
+ check_digits
96
+ freeze
97
+ end
14
98
 
15
- EXTENDED_ATTRIBUTES = %w{
16
- calendar precision uncertain approximate unspecified skip_timezone
17
- }.map(&:to_sym).freeze
99
+ attr_reader :significant
18
100
 
19
- extend Forwardable
101
+ def calendar
102
+ Period.calendar(start)
103
+ end
20
104
 
21
- class << self
22
- def gregorian(year = -4712, month = 1, mday = 1)
23
- new(year, month, mday, Date::GREGORIAN)
105
+ # False if years are written without year 0 (1 BC is -0001).
106
+ def year_zero?
107
+ !@historical
24
108
  end
25
-
26
- def edtf(input, options = {})
27
- warn '`Date.edtf` is deprecated, use `EDTF.parse`', category: :deprecated, uplevel: 1
28
- ::EDTF.parse(input, options)
109
+
110
+ # February 29 in a year with unspecified digits (19XX-02-29)
111
+ # falls in the leap years the digits allow;
112
+ # such a date stores the first one (1904).
113
+ def self.leap_years(year, unspecified, start, year_zero) # :nodoc:
114
+ written = Period.written_year(year, year_zero)
115
+ mask = Bitmask.new(unspecified)
116
+ pattern = mask.masks([format('%04d', written.abs)])[0]
117
+ return [year] unless pattern.include?('X')
118
+
119
+ digits = Regexp.new("\\A#{pattern.gsub('X') { '\\d' }}\\z")
120
+ sign = written.negative? ? -1 : 1
121
+
122
+ (year_zero ? 0 : 1).upto(9999).filter_map do |n|
123
+ next unless digits.match?(format('%04d', n))
124
+
125
+ year = Period.astronomical_year(sign * n, year_zero)
126
+ year if ::Date.valid_date?(year, 2, 29, start)
127
+ end
29
128
  end
30
129
 
31
- def edtf!(input, options = {})
32
- warn '`Date.edtf!` is deprecated, use `EDTF.parse!` or `EDTF()`', category: :deprecated, uplevel: 1
33
- ::EDTF.parse!(input, options)
130
+ # Instances created by Ruby's own date methods skip initialize;
131
+ # they behave like unqualified dates with day precision.
132
+ def precision
133
+ @precision || :day
34
134
  end
35
- end
36
135
 
37
- attr_accessor :calendar, :skip_timezone
136
+ def uncertain
137
+ @uncertain || Bitmask.new
138
+ end
38
139
 
39
- PRECISION.each do |p|
40
- define_method("#{p}_precision?") { precision == p }
140
+ def approximate
141
+ @approximate || Bitmask.new
142
+ end
41
143
 
42
- define_method("#{p}_precision!") do
43
- self.precision = p
44
- self
144
+ def unspecified
145
+ @unspecified || Bitmask.new
45
146
  end
46
147
 
47
- define_method("#{p}_precision") do
48
- change(:precision => p)
148
+ def uncertain?(part = nil)
149
+ qualified?(uncertain, part)
49
150
  end
50
- end
51
151
 
152
+ def approximate?(part = nil)
153
+ qualified?(approximate, part)
154
+ end
52
155
 
53
- alias original_initialize_copy initialize_copy
156
+ def unspecified?(part = nil)
157
+ qualified?(unspecified, part)
158
+ end
54
159
 
55
- def initialize_copy(other)
56
- original_initialize_copy(other)
57
- copy_extended_attributes(other)
58
- end
160
+ # Unspecified digits hold their lowest values.
161
+ def values
162
+ [year, month, day].take(values_count)
163
+ end
59
164
 
165
+ # Returns a copy with the given EDTF attributes replaced, like Data#with.
166
+ # Values beyond the precision raise (2016 has no month to replace).
167
+ def with(**changes)
168
+ return self if changes.empty?
60
169
 
61
- # Alias advance method from Active Support.
62
- alias original_advance advance
170
+ check_keys!(changes, ATTRIBUTES)
63
171
 
64
- # Provides precise Date calculations for years, months, and days. The +options+ parameter takes a hash with
65
- # any of these keys: <tt>:years</tt>, <tt>:months</tt>, <tt>:weeks</tt>, <tt>:days</tt>.
66
- def advance(options)
67
- original_advance(options).copy_extended_attributes(self)
68
- end
172
+ precision = changes.fetch(:precision, self.precision).to_sym
173
+ unless PRECISION.include?(precision)
174
+ raise ArgumentError, "invalid precision: #{precision.inspect}"
175
+ end
69
176
 
70
- # Alias change method from Active Support.
71
- alias original_change change
177
+ count = PRECISION.index(precision) + 1
178
+ beyond = PRECISION.drop(count) & changes.keys
179
+ unless beyond.empty?
180
+ raise ArgumentError,
181
+ "#{beyond.join(' and ')} beyond #{precision} precision"
182
+ end
72
183
 
73
- # Returns a new Date where one or more of the elements have been changed according to the +options+ parameter.
74
- def change(options)
75
- d = original_change(options)
76
- EXTENDED_ATTRIBUTES.each do |attribute|
77
- d.send("#{attribute}=", options[attribute] || send(attribute))
184
+ values = PRECISION.take(count).map { |name|
185
+ changes.fetch(name) { send(name) }
186
+ }
187
+ qualifiers = QUALIFIERS.to_h { |name|
188
+ [name, changes.fetch(name) { send(name) }]
189
+ }
190
+
191
+ self.class.new(
192
+ *values,
193
+ **qualifiers,
194
+ calendar: calendar,
195
+ year_zero: year_zero?
196
+ )
78
197
  end
79
- d
80
- end
81
-
82
198
 
83
- # Returns a copy with the given EDTF attributes replaced.
84
- def with(precision: self.precision,
85
- uncertain: PRECISION.select { |p| uncertain?(p) },
86
- approximate: PRECISION.select { |p| approximate?(p) })
87
- date = dup
88
- date.precision = precision
89
- date.uncertain.certain!.uncertain!(uncertain)
90
- date.approximate.certain!.uncertain!(approximate)
91
- date
92
- end
93
-
94
- # Returns this Date's precision.
95
- def precision
96
- @precision ||= :day
97
- end
199
+ def begin
200
+ return plain if atomic?
201
+ return ::Date.new(significant_years.first, 1, 1, start) if significant
202
+ return ::Date.new(leap_years.min, 2, 29, start) if leap_day?
203
+
204
+ year, month, day = unspecified.min(absolute_values, start)
205
+ year =
206
+ if written_year.negative?
207
+ -unspecified.max([written_year.abs])[0]
208
+ else
209
+ nonzero(year)
210
+ end
98
211
 
99
- # Sets this Date/Time's precision to the passed-in value.
100
- def precision=(precision)
101
- precision = precision.to_sym
102
- raise ArgumentError, "invalid precision #{precision.inspect}" unless PRECISION.include?(precision)
103
- @precision = precision
104
- update_precision_filter[-1]
105
- end
212
+ ::Date.new(astronomical(year), month || 1, day || 1, start)
213
+ end
106
214
 
107
- def uncertain
108
- @uncertain ||= EDTF::Uncertainty.new
109
- end
215
+ def end
216
+ return plain if atomic?
217
+ return ::Date.new(significant_years.last, 12, 31, start) if significant
218
+ return ::Date.new(leap_years.max, 2, 29, start) if leap_day?
110
219
 
111
- def approximate
112
- @approximate ||= EDTF::Uncertainty.new(nil, nil, nil, 8)
113
- end
220
+ year, month, day = unspecified.max(absolute_values, start)
221
+ if written_year.negative?
222
+ year = -least(unspecified.min([written_year.abs])[0])
223
+ end
224
+ year = astronomical(year)
114
225
 
115
- def unspecified
116
- @unspecified ||= EDTF::Unspecified.new
117
- end
226
+ return ::Date.new(year, 12, 31, start) if month.nil?
227
+ return ::Date.new(year, month, -1, start) if day.nil?
118
228
 
119
- def_delegators :uncertain, :uncertain?, :certain?
229
+ last = ::Date.new(year, month, -1, start).day
230
+ ::Date.new(year, month, [day, last].min, start)
231
+ end
120
232
 
121
- def certain!(arguments = precision_filter)
122
- uncertain.certain!(arguments)
123
- self
124
- end
233
+ # Returns the next day, month, or year depending on the date's precision.
234
+ # Unspecified digits step by the unit they leave open (201X -> 202X).
235
+ def succ(by = 1)
236
+ forward = by.positive? ^ written_year.negative?
237
+ year, month, day =
238
+ unspecified.zero? ? values : bound_values(forward: forward)
239
+
240
+ values =
241
+ case precision
242
+ when :year
243
+ [year + by]
244
+ when :month
245
+ y, m = (year * 12 + month - 1 + by).divmod(12)
246
+ [y, m + 1]
247
+ else
248
+ date = ::Date.new(year, month, day, start) + by
249
+ [date.year, date.month, date.day]
250
+ end
125
251
 
126
- def uncertain!(arguments = precision_filter)
127
- uncertain.uncertain!(arguments)
128
- self
129
- end
252
+ # Keep the lowest values the unspecified digits allow, as parsing does.
253
+ unless unspecified.zero?
254
+ written = Period.written_year(values[0], year_zero?)
255
+ values = unspecified.min([written.abs, *values.drop(1)], start)
256
+ year = written.negative? ? -least(values[0]) : nonzero(values[0])
257
+ values[0] = astronomical(year)
258
+ end
130
259
 
131
- def approximate?(arguments = precision_filter)
132
- approximate.uncertain?(arguments)
133
- end
260
+ self.class.new(
261
+ *values,
262
+ uncertain: uncertain,
263
+ approximate: approximate,
264
+ unspecified: unspecified,
265
+ significant: significant,
266
+ calendar: calendar,
267
+ year_zero: year_zero?
268
+ )
269
+ end
134
270
 
135
- alias approximately? approximate?
271
+ alias next succ
136
272
 
137
- def approximate!(arguments = precision_filter)
138
- approximate.uncertain!(arguments)
139
- self
140
- end
273
+ def prev(by = 1)
274
+ succ(-by)
275
+ end
141
276
 
142
- alias approximately! approximate!
277
+ # Yields each date at this precision that begins on or before max ends.
278
+ def upto(max)
279
+ return to_enum(:upto, max) unless block_given?
143
280
 
144
- def precise?(arguments = precision_filter)
145
- !approximate?(arguments)
146
- end
281
+ last = Period.bounds(max)&.last
282
+ date = self
283
+ while last && date.begin <= last
284
+ yield date
285
+ date = date.succ
286
+ end
287
+ self
288
+ end
147
289
 
148
- alias precisely? precise?
290
+ # Yields each date at this precision that ends on or after min begins.
291
+ def downto(min)
292
+ return to_enum(:downto, min) unless block_given?
149
293
 
150
- def precise!(arguments = precision_filter)
151
- approximate.certain!(arguments)
152
- self
153
- end
294
+ first = Period.bounds(min)&.first
295
+ date = self
296
+ while first && date.end >= first
297
+ yield date
298
+ date = date.prev
299
+ end
300
+ self
301
+ end
154
302
 
155
- alias precisely! precise!
303
+ def +(other)
304
+ plain + other
305
+ end
156
306
 
157
- def_delegators :unspecified, :unspecified?, :specified?, :unspecific?, :specific?
307
+ def -(other)
308
+ plain - other
309
+ end
158
310
 
159
- def unspecified!(arguments = precision_filter)
160
- unspecified.unspecified!(arguments)
161
- self
162
- end
311
+ def >>(other)
312
+ plain >> other
313
+ end
163
314
 
164
- alias unspecific! unspecified!
315
+ def <<(other)
316
+ plain << other
317
+ end
165
318
 
166
- def specified!(arguments = precision_filter)
167
- unspecified.specified!(arguments)
168
- self
169
- end
319
+ %i[
320
+ next_day prev_day next_month prev_month next_year prev_year
321
+ ].each do |name|
322
+ define_method(name) { |n = 1| plain.send(name, n) }
323
+ end
170
324
 
171
- alias specific! specified!
325
+ def new_start(start = ::Date::ITALY)
326
+ plain.new_start(start)
327
+ end
172
328
 
173
- # Returns false for Dates.
174
- def season?; false; end
329
+ %i[julian gregorian italy england].each do |name|
330
+ define_method(name) { plain.send(name) }
331
+ end
175
332
 
176
- # Returns true if the Date has an EDTF calendar string attached.
177
- def calendar?; !!@calendar; end
333
+ # Ruby's Date Marshal data keeps instance variables on MRI only.
334
+ def marshal_dump
335
+ variables = instance_variables.to_h { |name|
336
+ [name, instance_variable_get(name)]
337
+ }
338
+ [DATE_MARSHAL[:marshal_dump].bind_call(self), variables]
339
+ end
178
340
 
179
- # Returns true if the Date's EDTF string should be printed without timezone.
180
- def skip_timezone?; !!@skip_timezone; end
341
+ def marshal_load((data, variables))
342
+ DATE_MARSHAL[:marshal_load].bind_call(self, data)
343
+ variables.each { |name, value| instance_variable_set(name, value) }
344
+ freeze
345
+ end
181
346
 
182
- # Converts the Date into a season.
183
- def season
184
- Season.new(self)
185
- end
347
+ def ==(other)
348
+ (self <=> other) == 0
349
+ end
186
350
 
187
- # Returns the Date's EDTF string.
188
- def edtf
189
- return "Y#{year}" if long_year?
190
-
191
- v = values
192
- s = FORMATS.take(v.length).zip(v).map { |f,d| f % d.abs }
193
- s[0] = "-#{s[0]}" if year < 0
194
- s = unspecified.mask(s)
195
-
196
- unless (h = ua_hash).zero?
197
- #
198
- # To efficiently calculate the uncertain/approximate state we use
199
- # the bitmask. The primary flags are:
200
- #
201
- # Uncertain: 1 - year, 2 - month, 4 - day
202
- # Approximate: 8 - year, 16 - month, 32 - day
203
- #
204
- # Invariant: assumes that uncertain/approximate are not set for values
205
- # not covered by precision!
206
- #
207
- y, m, d = s
208
-
209
- # ?/~ if true-false or true-true and other false-true
210
- y << SYMBOLS[:uncertain] if 3&h==1 || 27&h==19
211
- y << SYMBOLS[:approximate] if 24&h==8 || 27&h==26
212
-
213
-
214
- # combine if false-true-true and other m == d
215
- if 7&h==6 && (48&h==48 || 48&h==0) || 56&h==48 && (6&h==6 || 6&h==0)
216
- m[0,0] = '('
217
- d << ')'
351
+ # Returns true if other is the same date and has the same EDTF attributes.
352
+ def eql?(other)
353
+ case other
354
+ when Date
355
+ jd == other.jd && state == other.state
356
+ when ::Date
357
+ plain? && plain.eql?(other)
218
358
  else
219
- case
220
- # false-true
221
- when 3&h==2 || 24&h==16
222
- m[0,0] = '('
223
- m << ')'
224
-
225
- # *-false-true
226
- when 6&h==4 || 48&h==32
227
- d[0,0] = '('
228
- d << ')'
229
- end
230
-
231
- # ?/~ if *-true-false or *-true-true and other m != d
232
- m << SYMBOLS[:uncertain] if h!=31 && (6&h==2 || 6&h==6 && (48&h==16 || 48&h==32))
233
- m << SYMBOLS[:approximate] if h!=59 && (48&h==16 || 48&h==48 && (6&h==2 || 6&h==4))
359
+ false
234
360
  end
361
+ end
235
362
 
236
- # ?/~ if *-*-true
237
- d << SYMBOLS[:uncertain] if 4&h==4
238
- d << SYMBOLS[:approximate] if 32&h==32
363
+ # Returns the plain Date hash unless EDTF attributes are set.
364
+ def hash
365
+ plain? ? plain.hash : [jd, *state].hash
239
366
  end
240
367
 
241
- s = s.join('-')
242
- s << SYMBOLS[:calendar] << calendar if calendar?
243
- s
244
- end
368
+ def edtf
369
+ year = written_year
370
+ sign = year.negative? ? '-' : ''
371
+ suffix = "S#{significant}" if significant
245
372
 
246
- alias to_edtf edtf
373
+ return "Y#{year}#{suffix}" if long_year?
374
+ return "#{sign}#{format('%04d', year.abs)}#{suffix}" if significant
247
375
 
248
- remove_method :next
376
+ values = [year, *self.values.drop(1)].each_with_index.map { |value, i|
377
+ format(i.zero? ? '%04d' : '%02d', value.abs)
378
+ }
249
379
 
250
- # Returns an array of the next n days, months, or years depending on the
251
- # current Date/Time's precision.
252
- def next(n = 1)
253
- 1.upto(n).map { |by| advance(PRECISIONS[precision] => by) }
254
- end
380
+ return sign + unspecified.masks(values).join('-') unless unspecified.zero?
255
381
 
256
- remove_method :succ
382
+ values = uncertain.marks(values, '?') unless uncertain.zero?
383
+ unless approximate.zero?
384
+ values = approximate.marks(values, '~').map { |value|
385
+ value.sub(/~\?|\?~/, '%')
386
+ }
387
+ end
257
388
 
258
- def succ
259
- advance(PRECISIONS[precision] => 1)
260
- end
389
+ sign + values.join('-')
390
+ end
261
391
 
262
- # Returns the Date of the previous day, month, or year depending on the
263
- # current Date/Time's precision.
264
- def prev(n = 1)
265
- if n > 1
266
- 1.upto(n).map { |by| advance(PRECISIONS[precision] => -by) }
267
- else
268
- advance(PRECISIONS[precision] => -1)
392
+ protected
393
+
394
+ # Plain days compare by day like Ruby dates, whatever their calendar.
395
+ # Year zero matters only to unspecified year digits (00XX).
396
+ def state
397
+ state = [
398
+ precision,
399
+ uncertain.value,
400
+ approximate.value,
401
+ unspecified.value,
402
+ significant,
403
+ year_zero? || !unspecified.year?
404
+ ]
405
+ plain? ? state : state << calendar
269
406
  end
270
- end
271
407
 
272
- def <=>(other)
273
- case other
274
- when ::Date
275
- values <=> other.values
276
- when EDTF::Interval, EDTF::Season, EDTF::Epoch
277
- (c = other <=> self) && -c
278
- else
279
- nil
408
+ private
409
+
410
+ def bits(value)
411
+ mask = value == true ? MASKS[values_count] : Bitmask.convert(value)
412
+ Bitmask.new(mask & MASKS[values_count])
280
413
  end
281
- end
282
414
 
283
- alias original_eql? eql?
284
- alias original_hash hash
415
+ def values_count
416
+ PRECISION.index(precision) + 1
417
+ end
285
418
 
286
- # Returns true if other is the same date and has the same EDTF attributes.
287
- def eql?(other)
288
- if original_eql?(other)
289
- extended_hash == other.extended_hash && calendar == other.calendar
290
- else
291
- false
419
+ def long_year?
420
+ precision == :year && written_year.abs > 9999
292
421
  end
293
- end
294
422
 
295
- # Returns the original Date hash unless EDTF attributes are set.
296
- def hash
297
- h = extended_hash
298
- if h.zero? && !calendar?
299
- original_hash
300
- else
301
- [original_hash, h, @calendar].hash
423
+ # Masks cover four-digit years only,
424
+ # and EDTF does not qualify long years or years with significant digits.
425
+ def check_digits
426
+ if written_year.abs > 9999 && precision != :year
427
+ raise ArgumentError, 'years beyond four digits need year precision'
428
+ end
429
+
430
+ if significant && precision != :year
431
+ raise ArgumentError, 'significant digits need year precision'
432
+ end
433
+
434
+ if significant && significant < 1
435
+ raise ArgumentError, "invalid significant digits: #{significant}"
436
+ end
437
+
438
+ unless unspecified.zero? || (uncertain.zero? && approximate.zero?)
439
+ raise ArgumentError, 'unspecified digits cannot be qualified'
440
+ end
441
+
442
+ return unless long_year? || significant
443
+
444
+ unless [uncertain, approximate, unspecified].all?(&:zero?)
445
+ raise ArgumentError, 'long years and significant digits ' \
446
+ 'cannot be qualified or unspecified'
447
+ end
302
448
  end
303
- end
304
449
 
450
+ # The first and last year the significant digits allow.
451
+ def significant_years
452
+ return year..year if significant >= written_year.abs.to_s.length
305
453
 
306
- # Returns an array of the current year, month, and day values filtered by
307
- # the Date/Time's precision.
308
- def values
309
- precision_filter.map { |p| send(p) }
310
- end
454
+ unit = 10**(written_year.abs.to_s.length - significant)
455
+ low = written_year.abs / unit * unit
456
+ high = low + unit - 1
457
+ low = 1 if low.zero? && !year_zero?
311
458
 
312
- # Returns the same date but with negated year.
313
- def negate
314
- change(:year => year * -1)
315
- end
459
+ years = written_year.negative? ? [-high, -low] : [low, high]
460
+ astronomical(years[0])..astronomical(years[1])
461
+ end
316
462
 
317
- alias -@ negate
463
+ def qualified?(mask, part)
464
+ part.nil? ? !mask.zero? : mask.intersect?(part)
465
+ end
318
466
 
319
- # Returns true if this Date/Time has year precision and the year exceeds four digits.
320
- def long_year?
321
- year_precision? && year.abs > 9999
322
- end
467
+ def leap_day?
468
+ precision == :day && month == 2 && day == 29 &&
469
+ unspecified.year? && !unspecified.month? && !unspecified.day?
470
+ end
323
471
 
472
+ def leap_years
473
+ Date.leap_years(year, unspecified, start, year_zero?)
474
+ end
324
475
 
325
- private
476
+ def plain?
477
+ precision == :day && unspecified.zero? &&
478
+ uncertain.zero? && approximate.zero?
479
+ end
326
480
 
327
- def ua_hash
328
- uncertain.hash + approximate.hash
329
- end
481
+ def atomic?
482
+ precision == :day && unspecified.zero?
483
+ end
330
484
 
331
- def precision_filter
332
- @precision_filter ||= update_precision_filter
333
- end
485
+ def plain
486
+ ::Date.jd(jd, start)
487
+ end
334
488
 
335
- def update_precision_filter
336
- @precision_filter = case precision
337
- when :year
338
- [:year]
339
- when :month
340
- [:year,:month]
341
- else
342
- [:year,:month,:day]
489
+ def least(year)
490
+ year.zero? ? unspecified.least_year(year) : year
343
491
  end
344
- end
345
492
 
346
- protected
493
+ # Without year zero, positive written years skip 0, too (00XX begins at 1).
494
+ def nonzero(year)
495
+ year_zero? ? year : least(year)
496
+ end
347
497
 
348
- attr_writer :uncertain, :unspecified, :approximate
498
+ def written_year
499
+ @historical && year < 1 ? year - 1 : year
500
+ end
349
501
 
350
- # Bits 0-1: precision (0 - day, 1 - month, 2 - year)
351
- # Bits 2-4: uncertain year, month, day (Uncertainty#hash with base 1)
352
- # Bits 5-7: approximate year, month, day (Uncertainty#hash with base 8)
353
- # Bits 8-15: unspecified year, month, and day digits
354
- def extended_hash
355
- h = @precision == :year ? 2 : @precision == :month ? 1 : 0
356
- h |= @uncertain.hash << 2 if @uncertain
357
- h |= @approximate.hash << 2 if @approximate
358
- h |= @unspecified.hash << 8 if @unspecified
359
- h
360
- end
502
+ def astronomical(year)
503
+ Period.astronomical_year(year, year_zero?)
504
+ end
361
505
 
362
- def copy_extended_attributes(other)
363
- @uncertain = other.uncertain.dup
364
- @approximate = other.approximate.dup
365
- @unspecified = other.unspecified.dup
506
+ # The digits as written: masks apply to the written year.
507
+ def absolute_values
508
+ [written_year.abs, *values.drop(1)]
509
+ end
366
510
 
367
- @calendar = other.calendar.dup if other.calendar?
368
- @precision = other.precision
511
+ def bound_values(forward:)
512
+ values =
513
+ if forward
514
+ unspecified.max(absolute_values, start)
515
+ else
516
+ unspecified.min(absolute_values, start)
517
+ end
369
518
 
370
- self
519
+ values[0] = astronomical(written_year.negative? ? -values[0] : values[0])
520
+ values
521
+ end
371
522
  end
372
523
 
373
524
  end