From bae5812eab6c5e11cc11ff259a7f6f28bd95b976 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 11 Feb 2026 21:55:57 +0900 Subject: [PATCH 001/144] Replace Date and DateTime classes from C to Ruby. C implementation has been rewritten as faithfully as possible in pure Ruby. [Feature #21264] https://bugs.ruby-lang.org/issues/21264 --- Rakefile | 61 +- date.gemspec | 24 +- ext/date/extconf.rb | 21 +- lib/date.rb | 17 +- lib/date/constants.rb | 182 ++ lib/date/core.rb | 3693 +++++++++++++++++++++++++++++++++++++++++ lib/date/datetime.rb | 826 +++++++++ lib/date/parse.rb | 2607 +++++++++++++++++++++++++++++ lib/date/patterns.rb | 403 +++++ lib/date/strftime.rb | 600 +++++++ lib/date/strptime.rb | 769 +++++++++ lib/date/time.rb | 59 + lib/date/version.rb | 5 + lib/date/zonetab.rb | 405 +++++ 14 files changed, 9619 insertions(+), 53 deletions(-) create mode 100644 lib/date/constants.rb create mode 100644 lib/date/core.rb create mode 100644 lib/date/datetime.rb create mode 100644 lib/date/parse.rb create mode 100644 lib/date/patterns.rb create mode 100644 lib/date/strftime.rb create mode 100644 lib/date/strptime.rb create mode 100644 lib/date/time.rb create mode 100644 lib/date/version.rb create mode 100644 lib/date/zonetab.rb diff --git a/Rakefile b/Rakefile index 933384c0..06175d09 100644 --- a/Rakefile +++ b/Rakefile @@ -1,30 +1,47 @@ require "bundler/gem_tasks" require "rake/testtask" -require "shellwords" -require "rake/extensiontask" -extask = Rake::ExtensionTask.new("date") do |ext| - ext.name = "date_core" - ext.lib_dir.sub!(%r[(?=/|\z)], "/#{RUBY_VERSION}/#{ext.platform}") -end +if RUBY_VERSION >= "3.3" + # Pure Ruby — no compilation needed + Rake::TestTask.new(:test) do |t| + t.libs << "lib" + t.libs << "test/lib" + t.ruby_opts << "-rhelper" + t.test_files = FileList['test/**/test_*.rb'] + end -Rake::TestTask.new(:test) do |t| - t.libs << extask.lib_dir - t.libs << "test/lib" - t.ruby_opts << "-rhelper" - t.test_files = FileList['test/**/test_*.rb'] -end + task :compile # no-op + +else + # C extension for Ruby < 3.3 + require "shellwords" + require "rake/extensiontask" + + extask = Rake::ExtensionTask.new("date") do |ext| + ext.name = "date_core" + ext.lib_dir.sub!(%r[(?=/|\z)], "/#{RUBY_VERSION}/#{ext.platform}") + end + + Rake::TestTask.new(:test) do |t| + t.libs << extask.lib_dir + t.libs << "test/lib" + t.ruby_opts << "-rhelper" + t.test_files = FileList['test/**/test_*.rb'] + end + + task test: :compile -task compile: "ext/date/zonetab.h" -file "ext/date/zonetab.h" => "ext/date/zonetab.list" do |t| - dir, hdr = File.split(t.name) - make_program_name = - ENV['MAKE'] || ENV['make'] || - RbConfig::CONFIG['configure_args'][/with-make-prog\=\K\w+/] || - (/mswin/ =~ RUBY_PLATFORM ? 'nmake' : 'make') - make_program = Shellwords.split(make_program_name) - sh(*make_program, "-f", "prereq.mk", "top_srcdir=.."+"/.."*dir.count("/"), - hdr, chdir: dir) + task compile: "ext/date/zonetab.h" + file "ext/date/zonetab.h" => "ext/date/zonetab.list" do |t| + dir, hdr = File.split(t.name) + make_program_name = + ENV['MAKE'] || ENV['make'] || + RbConfig::CONFIG['configure_args'][/with-make-prog\=\K\w+/] || + (/mswin/ =~ RUBY_PLATFORM ? 'nmake' : 'make') + make_program = Shellwords.split(make_program_name) + sh(*make_program, "-f", "prereq.mk", "top_srcdir=.."+"/.."*dir.count("/"), + hdr, chdir: dir) + end end task :default => [:compile, :test] diff --git a/date.gemspec b/date.gemspec index cb439bd0..d8da6dd2 100644 --- a/date.gemspec +++ b/date.gemspec @@ -1,29 +1,19 @@ # frozen_string_literal: true -version = File.foreach(File.expand_path("../lib/date.rb", __FILE__)).find do |line| - /^\s*VERSION\s*=\s*["'](.*)["']/ =~ line and break $1 -end +require_relative "lib/date/version" Gem::Specification.new do |s| s.name = "date" - s.version = version + s.version = Date::VERSION s.summary = "The official date library for Ruby." s.description = "The official date library for Ruby." - if Gem::Platform === s.platform and s.platform =~ 'java' or RUBY_ENGINE == 'jruby' - s.platform = 'java' - # No files shipped, no require path, no-op for now on JRuby - else - s.require_path = %w{lib} + s.require_path = %w{lib} - s.files = [ - "README.md", "COPYING", "BSDL", - "lib/date.rb", "ext/date/date_core.c", "ext/date/date_parse.c", "ext/date/date_strftime.c", - "ext/date/date_strptime.c", "ext/date/date_tmx.h", "ext/date/extconf.rb", "ext/date/prereq.mk", - "ext/date/zonetab.h", "ext/date/zonetab.list" - ] - s.extensions = "ext/date/extconf.rb" - end + s.files = Dir["README.md", "COPYING", "BSDL", "lib/**/*.rb", + "ext/date/*.c", "ext/date/*.h", "ext/date/extconf.rb", + "ext/date/prereq.mk", "ext/date/zonetab.list"] + s.extensions = ["ext/date/extconf.rb"] s.required_ruby_version = ">= 2.6.0" diff --git a/ext/date/extconf.rb b/ext/date/extconf.rb index 8a1467df..f00d8771 100644 --- a/ext/date/extconf.rb +++ b/ext/date/extconf.rb @@ -1,13 +1,16 @@ # frozen_string_literal: true require 'mkmf' -config_string("strict_warnflags") {|w| $warnflags += " #{w}"} - -append_cflags("-Wno-compound-token-split-by-macro") if RUBY_VERSION < "2.7." -have_func("rb_category_warn") -with_werror("", {:werror => true}) do |opt, | - have_var("timezone", "time.h", opt) - have_var("altzone", "time.h", opt) +if RUBY_VERSION >= "3.3" + # Pure Ruby implementation; skip C extension build + File.write("Makefile", dummy_makefile($srcdir).join("")) +else + config_string("strict_warnflags") {|w| $warnflags += " #{w}"} + append_cflags("-Wno-compound-token-split-by-macro") if RUBY_VERSION < "2.7." + have_func("rb_category_warn") + with_werror("", {:werror => true}) do |opt, | + have_var("timezone", "time.h", opt) + have_var("altzone", "time.h", opt) + end + create_makefile('date_core') end - -create_makefile('date_core') diff --git a/lib/date.rb b/lib/date.rb index 0cb76301..3ad70c9c 100644 --- a/lib/date.rb +++ b/lib/date.rb @@ -1,11 +1,20 @@ # frozen_string_literal: true # date.rb: Written by Tadayoshi Funaba 1998-2011 -require 'date_core' +if RUBY_VERSION >= "3.3" + require_relative "date/version" + require_relative "date/constants" + require_relative "date/core" + require_relative "date/strftime" + require_relative "date/parse" + require_relative "date/strptime" + require_relative "date/time" + require_relative "date/datetime" +else + require 'date_core' +end class Date - VERSION = "3.5.1" # :nodoc: - # call-seq: # infinite? -> false # @@ -64,7 +73,5 @@ def to_f -Float::INFINITY end end - end - end diff --git a/lib/date/constants.rb b/lib/date/constants.rb new file mode 100644 index 00000000..d9db674b --- /dev/null +++ b/lib/date/constants.rb @@ -0,0 +1,182 @@ +# frozen_string_literal: true + +# Constants +class Date + HAVE_JD = 0b00000001 # 1 + HAVE_DF = 0b00000010 # 2 + HAVE_CIVIL = 0b00000100 # 4 + HAVE_TIME = 0b00001000 # 8 + COMPLEX_DAT = 0b10000000 # 128 + private_constant :HAVE_JD, :HAVE_DF, :HAVE_CIVIL, :HAVE_TIME, :COMPLEX_DAT + + MONTHNAMES = [nil, "January", "February", "March", "April", "May", "June", + "July", "August", "September", "October", "November", "December"] + .map { |s| s&.encode(Encoding::US_ASCII)&.freeze }.freeze + ABBR_MONTHNAMES = [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun", + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] + .map { |s| s&.encode(Encoding::US_ASCII)&.freeze }.freeze + DAYNAMES = %w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday] + .map { |s| s.encode(Encoding::US_ASCII).freeze }.freeze + ABBR_DAYNAMES = %w[Sun Mon Tue Wed Thu Fri Sat] + .map { |s| s.encode(Encoding::US_ASCII).freeze }.freeze + + # Pattern constants for regex + ABBR_DAYS_PATTERN = 'sun|mon|tue|wed|thu|fri|sat' + DAYS_PATTERN = 'sunday|monday|tuesday|wednesday|thursday|friday|saturday' + ABBR_MONTHS_PATTERN = 'jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec' + private_constant :ABBR_DAYS_PATTERN, :DAYS_PATTERN, :ABBR_MONTHS_PATTERN + + ITALY = 2299161 # 1582-10-15 + ENGLAND = 2361222 # 1752-09-14 + JULIAN = Float::INFINITY + GREGORIAN = -Float::INFINITY + + DEFAULT_SG = ITALY + private_constant :DEFAULT_SG + + MINUTE_IN_SECONDS = 60 + HOUR_IN_SECONDS = 3600 + DAY_IN_SECONDS = 86400 + HALF_DAYS_IN_SECONDS = DAY_IN_SECONDS / 2 + SECOND_IN_MILLISECONDS = 1000 + SECOND_IN_NANOSECONDS = 1_000_000_000 + private_constant :MINUTE_IN_SECONDS, :HOUR_IN_SECONDS, :DAY_IN_SECONDS, :SECOND_IN_MILLISECONDS, :SECOND_IN_NANOSECONDS, :HALF_DAYS_IN_SECONDS + + JC_PERIOD0 = 1461 # 365.25 * 4 + GC_PERIOD0 = 146097 # 365.2425 * 400 + CM_PERIOD0 = 71149239 # (lcm 7 1461 146097) + CM_PERIOD = (0xfffffff / CM_PERIOD0) * CM_PERIOD0 + CM_PERIOD_JCY = (CM_PERIOD / JC_PERIOD0) * 4 + CM_PERIOD_GCY = (CM_PERIOD / GC_PERIOD0) * 400 + private_constant :JC_PERIOD0, :GC_PERIOD0, :CM_PERIOD0, :CM_PERIOD, :CM_PERIOD_JCY, :CM_PERIOD_GCY + + REFORM_BEGIN_YEAR = 1582 + REFORM_END_YEAR = 1930 + REFORM_BEGIN_JD = 2298874 # ns 1582-01-01 + REFORM_END_JD = 2426355 # os 1930-12-31 + private_constant :REFORM_BEGIN_YEAR, :REFORM_END_YEAR, :REFORM_BEGIN_JD, :REFORM_END_JD + + SEC_WIDTH = 6 + MIN_WIDTH = 6 + HOUR_WIDTH = 5 + MDAY_WIDTH = 5 + MON_WIDTH = 4 + private_constant :SEC_WIDTH, :MIN_WIDTH, :HOUR_WIDTH, :MDAY_WIDTH, :MON_WIDTH + + SEC_SHIFT = 0 + MIN_SHIFT = SEC_WIDTH + HOUR_SHIFT = MIN_WIDTH + SEC_WIDTH + MDAY_SHIFT = HOUR_WIDTH + MIN_WIDTH + SEC_WIDTH + MON_SHIFT = MDAY_WIDTH + HOUR_WIDTH + MIN_WIDTH + SEC_WIDTH + private_constant :SEC_SHIFT, :MIN_SHIFT, :HOUR_SHIFT, :MDAY_SHIFT, :MON_SHIFT + + PK_MASK = ->(x) { (1 << x) - 1 } + private_constant :PK_MASK + + # Days in each month (non-leap and leap year) + MONTH_DAYS = [ + [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], # non-leap + [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # leap + ].freeze + private_constant :MONTH_DAYS + + YEARTAB = [ + [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], # non-leap + [0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335] # leap + ].freeze + private_constant :YEARTAB + + # Neri-Schneider algorithm constants + # JDN of March 1, Year 0 in proleptic Gregorian calendar + NS_EPOCH = 1721120 + private_constant :NS_EPOCH + + # Days in a 4-year cycle (3 normal years + 1 leap year) + NS_DAYS_IN_4_YEARS = 1461 + private_constant :NS_DAYS_IN_4_YEARS + + # Days in a 400-year Gregorian cycle (97 leap years in 400 years) + NS_DAYS_IN_400_YEARS = 146097 + private_constant :NS_DAYS_IN_400_YEARS + + # Years per century + NS_YEARS_PER_CENTURY = 100 + private_constant :NS_YEARS_PER_CENTURY + + # Multiplier for extracting year within century using fixed-point arithmetic. + # This is ceil(2^32 / NS_DAYS_IN_4_YEARS) for the Euclidean affine function. + NS_YEAR_MULTIPLIER = 2939745 + private_constant :NS_YEAR_MULTIPLIER + + # Coefficients for month calculation from day-of-year. + # Maps day-of-year to month using: month = (NS_MONTH_COEFF * doy + NS_MONTH_OFFSET) >> 16 + NS_MONTH_COEFF = 2141 + NS_MONTH_OFFSET = 197913 + private_constant :NS_MONTH_COEFF, :NS_MONTH_OFFSET + + # Coefficients for civil date to JDN month contribution. + # Maps month to accumulated days: days = (NS_CIVIL_MONTH_COEFF * m - NS_CIVIL_MONTH_OFFSET) / 32 + NS_CIVIL_MONTH_COEFF = 979 + NS_CIVIL_MONTH_OFFSET = 2919 + NS_CIVIL_MONTH_DIVISOR = 32 + private_constant :NS_CIVIL_MONTH_COEFF, :NS_CIVIL_MONTH_OFFSET, :NS_CIVIL_MONTH_DIVISOR + + # Days from March 1 to December 31 (for Jan/Feb year adjustment) + NS_DAYS_BEFORE_NEW_YEAR = 306 + private_constant :NS_DAYS_BEFORE_NEW_YEAR + + # Safe bounds for Neri-Schneider algorithm to avoid integer overflow. + # These correspond to approximately years -1,000,000 to +1,000,000. + NS_JD_MIN = -364_000_000 + NS_JD_MAX = 538_000_000 + private_constant :NS_JD_MIN, :NS_JD_MAX + + JULIAN_EPOCH_DATE = "-4712-01-01" + JULIAN_EPOCH_DATETIME = "-4712-01-01T00:00:00+00:00" + JULIAN_EPOCH_DATETIME_RFC2822 = "Mon, 1 Jan -4712 00:00:00 +0000" + JULIAN_EPOCH_DATETIME_HTTPDATE = "Mon, 01 Jan -4712 00:00:00 GMT" + private_constant :JULIAN_EPOCH_DATE, :JULIAN_EPOCH_DATETIME, :JULIAN_EPOCH_DATETIME_RFC2822, :JULIAN_EPOCH_DATETIME_HTTPDATE + + JISX0301_ERA_INITIALS = 'mtshr' + JISX0301_DEFAULT_ERA = 'H' # obsolete + private_constant :JISX0301_ERA_INITIALS, :JISX0301_DEFAULT_ERA + + HAVE_ALPHA = 1 << 0 + HAVE_DIGIT = 1 << 1 + HAVE_DASH = 1 << 2 + HAVE_DOT = 1 << 3 + HAVE_SLASH = 1 << 4 + private_constant :HAVE_ALPHA, :HAVE_DIGIT, :HAVE_DASH, :HAVE_DOT, :HAVE_SLASH + + # C: default strftime format is US-ASCII + STRFTIME_DEFAULT_FMT = '%F'.encode(Encoding::US_ASCII) + private_constant :STRFTIME_DEFAULT_FMT + + # strftime spec categories + NUMERIC_SPECS = %w[Y C y m d j H I M S L N G g U W V u w s Q].freeze + SPACE_PAD_SPECS = %w[e k l].freeze + CHCASE_UPPER_SPECS = %w[A a B b h].freeze + CHCASE_LOWER_SPECS = %w[Z p].freeze + private_constant :NUMERIC_SPECS, :SPACE_PAD_SPECS, + :CHCASE_UPPER_SPECS, :CHCASE_LOWER_SPECS + + # strptime digit-consuming specs + NUM_PATTERN_SPECS = "CDdeFGgHIjkLlMmNQRrSsTUuVvWwXxYy" + private_constant :NUM_PATTERN_SPECS + + # Fragment completion table for DateTime parsing + COMPLETE_FRAGS_TABLE = [ + [:time, [:hour, :min, :sec].freeze], + [nil, [:jd].freeze], + [:ordinal, [:year, :yday, :hour, :min, :sec].freeze], + [:civil, [:year, :mon, :mday, :hour, :min, :sec].freeze], + [:commercial, [:cwyear, :cweek, :cwday, :hour, :min, :sec].freeze], + [:wday, [:wday, :hour, :min, :sec].freeze], + [:wnum0, [:year, :wnum0, :wday, :hour, :min, :sec].freeze], + [:wnum1, [:year, :wnum1, :wday, :hour, :min, :sec].freeze], + [nil, [:cwyear, :cweek, :wday, :hour, :min, :sec].freeze], + [nil, [:year, :wnum0, :cwday, :hour, :min, :sec].freeze], + [nil, [:year, :wnum1, :cwday, :hour, :min, :sec].freeze], + ].each { |a| a.freeze }.freeze + private_constant :COMPLETE_FRAGS_TABLE +end diff --git a/lib/date/core.rb b/lib/date/core.rb new file mode 100644 index 00000000..03b6d9cb --- /dev/null +++ b/lib/date/core.rb @@ -0,0 +1,3693 @@ +# frozen_string_literal: true + +# Implementation of ruby/date/ext/date/date_core.c +class Date + include Comparable + + Error = Class.new(ArgumentError) + + # Initialize method + # call-seq: + # Date.new(year = -4712, month = 1, mday = 1, start = Date::ITALY) -> date + # + # Returns a new Date object constructed from the given arguments: + # + # Date.new(2022).to_s # => "2022-01-01" + # Date.new(2022, 2).to_s # => "2022-02-01" + # Date.new(2022, 2, 4).to_s # => "2022-02-04" + # + # Argument +month+ should be in range (1..12) or range (-12..-1); + # when the argument is negative, counts backward from the end of the year: + # + # Date.new(2022, -11, 4).to_s # => "2022-02-04" + # + # Argument +mday+ should be in range (1..n) or range (-n..-1) + # where +n+ is the number of days in the month; + # when the argument is negative, counts backward from the end of the month. + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # + # Related: Date.jd. + def initialize(year = -4712, month = 1, day = 1, start = DEFAULT_SG) + y = year + m = month + d = day + sg = start + fr2 = 0 + + # argument type checking + if y + raise TypeError, "invalid year (not numeric)" unless year.is_a?(Numeric) + end + if m + raise TypeError, "invalid month (not numeric)" unless month.is_a?(Numeric) + end + if d + raise TypeError, "invalid day (not numeric)" unless day.is_a?(Numeric) + # Check if there is a decimal part. + d_trunc, fr = d_trunc_with_frac(d) + d = d_trunc + fr2 = fr if fr.nonzero? + end + + sg = self.class.send(:valid_sg, sg) + style = self.class.send(:guess_style, y, sg) + + if style < 0 + # gregorian calendar only + result = self.class.send(:valid_gregorian_p, y, m, d) + raise Error unless result + + nth, ry = self.class.send(:decode_year, y, -1) + rm = result[:rm] + rd = result[:rd] + + @nth = canon(nth) + @jd = 0 + @sg = sg + @year = ry + @month = rm + @day = rd + @has_jd = false + @has_civil = true + @df = nil + @sf = nil + @of = nil + else + # full validation + result = self.class.send(:valid_civil_p, y, m, d, sg) + raise Error unless result + + nth = result[:nth] + ry = result[:ry] + rm = result[:rm] + rd = result[:rd] + rjd = result[:rjd] + + @nth = canon(nth) + @jd = rjd + @sg = sg + @year = ry + @month = rm + @day = rd + @has_jd = true + @has_civil = true + @df = nil + @sf = nil + @of = nil + end + + # Add any decimal parts. + if fr2.nonzero? + new_date = self + fr2 + @nth = new_date.instance_variable_get(:@nth) + @jd = new_date.instance_variable_get(:@jd) + @sg = new_date.instance_variable_get(:@sg) + @year = new_date.instance_variable_get(:@year) + @month = new_date.instance_variable_get(:@month) + @day = new_date.instance_variable_get(:@day) + @has_jd = new_date.instance_variable_get(:@has_jd) + @has_civil = new_date.instance_variable_get(:@has_civil) + @df = new_date.instance_variable_get(:@df) + @sf = new_date.instance_variable_get(:@sf) + @of = new_date.instance_variable_get(:@of) + end + + self + end + + # Class methods + class << self + # Same as `Date.new`. + alias_method :civil, :new + + # call-seq: + # Date.valid_civil?(year, month, mday, start = Date::ITALY) -> true or false + # + # Returns +true+ if the arguments define a valid ordinal date, + # +false+ otherwise: + # + # Date.valid_date?(2001, 2, 3) # => true + # Date.valid_date?(2001, 2, 29) # => false + # Date.valid_date?(2001, 2, -1) # => true + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # + # Related: Date.jd, Date.new. + def valid_civil?(year, month, day, start = DEFAULT_SG) + return false unless numeric?(year) + return false unless numeric?(month) + return false unless numeric?(day) + + result = valid_civil_sub(year, month, day, start, 0) + + !result.nil? + end + alias_method :valid_date?, :valid_civil? + + # call-seq: + # Date.jd(jd = 0, start = Date::ITALY) -> date + # + # Returns a new \Date object formed from the arguments: + # + # Date.jd(2451944).to_s # => "2001-02-03" + # Date.jd(2451945).to_s # => "2001-02-04" + # Date.jd(0).to_s # => "-4712-01-01" + # + # The returned date is: + # + # - Gregorian, if the argument is greater than or equal to +start+: + # + # Date::ITALY # => 2299161 + # Date.jd(Date::ITALY).gregorian? # => true + # Date.jd(Date::ITALY + 1).gregorian? # => true + # + # - Julian, otherwise + # + # Date.jd(Date::ITALY - 1).julian? # => true + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # + # Related: Date.new. + def jd(jd = 0, start = DEFAULT_SG) + j = 0 + fr = 0 + sg = start + + sg = valid_sg(start) if start + + if jd + raise TypeError, "invalid jd (not numeric)" unless jd.is_a?(Numeric) + + j, fr = value_trunc(jd) + end + + nth, rjd = decode_jd(j) + + ret = d_simple_new_internal(nth, rjd, sg, 0, 0, 0, HAVE_JD) + + ret = ret + fr if fr.nonzero? + + ret + end + + # call-seq: + # Date.valid_jd?(jd, start = Date::ITALY) -> true + # + # Implemented for compatibility; + # returns +true+ unless +jd+ is invalid (i.e., not a Numeric). + # + # Date.valid_jd?(2451944) # => true + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # + # Related: Date.jd. + def valid_jd?(jd, start = DEFAULT_SG) + return false unless numeric?(jd) + + result = valid_jd_sub(jd, start, 0) + + !result.nil? + end + + # call-seq: + # Date.gregorian_leap?(year) -> true or false + # + # Returns +true+ if the given year is a leap year + # in the {proleptic Gregorian calendar}[https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar], +false+ otherwise: + # + # Date.gregorian_leap?(2000) # => true + # Date.gregorian_leap?(2001) # => false + # + # Related: Date.julian_leap?. + def gregorian_leap?(year) + raise TypeError, "invalid year (not numeric)" unless numeric?(year) + + _, ry = decode_year(year, -1) + + c_gregorian_leap_p?(ry) + end + alias_method :leap?, :gregorian_leap? + + # call-seq: + # Date.julian_leap?(year) -> true or false + # + # Returns +true+ if the given year is a leap year + # in the {proleptic Julian calendar}[https://en.wikipedia.org/wiki/Proleptic_Julian_calendar], +false+ otherwise: + # + # Date.julian_leap?(1900) # => true + # Date.julian_leap?(1901) # => false + # + # Related: Date.gregorian_leap?. + def julian_leap?(year) + raise TypeError, "invalid year (not numeric)" unless numeric?(year) + + _, ry = decode_year(year, +1) + + c_julian_leap_p?(ry) + end + + # call-seq: + # Date.ordinal(year = -4712, yday = 1, start = Date::ITALY) -> date + # + # Returns a new \Date object formed fom the arguments. + # + # With no arguments, returns the date for January 1, -4712: + # + # Date.ordinal.to_s # => "-4712-01-01" + # + # With argument +year+, returns the date for January 1 of that year: + # + # Date.ordinal(2001).to_s # => "2001-01-01" + # Date.ordinal(-2001).to_s # => "-2001-01-01" + # + # With positive argument +yday+ == +n+, + # returns the date for the +nth+ day of the given year: + # + # Date.ordinal(2001, 14).to_s # => "2001-01-14" + # + # With negative argument +yday+, counts backward from the end of the year: + # + # Date.ordinal(2001, -14).to_s # => "2001-12-18" + # + # Raises an exception if +yday+ is zero or out of range. + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # + # Related: Date.jd, Date.new. + def ordinal(year = -4712, yday = 1, start = DEFAULT_SG) + y = year + d = yday + fr2 = 0 + sg = start + + if y + raise TypeError, "invalid year (not numeric)" unless year.is_a?(Numeric) + end + if d + raise TypeError, "invalid yday (not numeric)" unless yday.is_a?(Numeric) + d_trunc, fr = value_trunc(d) + d = d_trunc + fr2 = fr if fr.nonzero? + end + + result = valid_ordinal_p(year, yday, start) + raise Error unless result + + nth = result[:nth] + rjd = result[:rjd] + + obj = d_simple_new_internal(nth, rjd, sg, 0, 0, 0, HAVE_JD) + + obj = obj + fr2 if fr2.nonzero? + + obj + end + + # call-seq: + # Date.valid_ordinal?(year, yday, start = Date::ITALY) -> true or false + # + # Returns +true+ if the arguments define a valid ordinal date, + # +false+ otherwise: + # + # Date.valid_ordinal?(2001, 34) # => true + # Date.valid_ordinal?(2001, 366) # => false + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # + # Related: Date.jd, Date.ordinal. + def valid_ordinal?(year, day, start = DEFAULT_SG) + return false unless numeric?(year) + return false unless numeric?(day) + + result = valid_ordinal_sub(year, day, start, false) + + !result.nil? + end + + # call-seq: + # Date.commercial(cwyear = -4712, cweek = 1, cwday = 1, start = Date::ITALY) -> date + # + # Returns a new \Date object constructed from the arguments. + # + # Argument +cwyear+ gives the year, and should be an integer. + # + # Argument +cweek+ gives the index of the week within the year, + # and should be in range (1..53) or (-53..-1); + # in some years, 53 or -53 will be out-of-range; + # if negative, counts backward from the end of the year: + # + # Date.commercial(2022, 1, 1).to_s # => "2022-01-03" + # Date.commercial(2022, 52, 1).to_s # => "2022-12-26" + # + # Argument +cwday+ gives the indes of the weekday within the week, + # and should be in range (1..7) or (-7..-1); + # 1 or -7 is Monday; + # if negative, counts backward from the end of the week: + # + # Date.commercial(2022, 1, 1).to_s # => "2022-01-03" + # Date.commercial(2022, 1, -7).to_s # => "2022-01-03" + # + # When +cweek+ is 1: + # + # - If January 1 is a Friday, Saturday, or Sunday, + # the first week begins in the week after: + # + # Date::ABBR_DAYNAMES[Date.new(2023, 1, 1).wday] # => "Sun" + # Date.commercial(2023, 1, 1).to_s # => "2023-01-02" + # Date.commercial(2023, 1, 7).to_s # => "2023-01-08" + # + # - Otherwise, the first week is the week of January 1, + # which may mean some of the days fall on the year before: + # + # Date::ABBR_DAYNAMES[Date.new(2020, 1, 1).wday] # => "Wed" + # Date.commercial(2020, 1, 1).to_s # => "2019-12-30" + # Date.commercial(2020, 1, 7).to_s # => "2020-01-05" + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # + # Related: Date.jd, Date.new, Date.ordinal. + def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = DEFAULT_SG) + y = cwyear + w = cweek + d = cwday + fr2 = 0 + sg = start + + if y + raise TypeError, "invalid year (not numeric)" unless cwyear.is_a?(Numeric) + end + if w + raise TypeError, "invalid cweek (not numeric)" unless cweek.is_a?(Numeric) + w = w.to_i + end + if d + raise TypeError, "invalid cwday (not numeric)" unless cwday.is_a?(Numeric) + d_trunc, fr = value_trunc(d) + d = d_trunc + fr2 = fr if fr.nonzero? + end + + sg = valid_sg(start) if start + + result = valid_commercial_p(y, w, d, sg) + raise Error unless result + + nth = result[:nth] + rjd = result[:rjd] + + obj = d_simple_new_internal(nth, rjd, sg, 0, 0, 0, HAVE_JD) + + obj = obj + fr2 if fr2.nonzero? + + obj + end + + # call-seq: + # Date.valid_commercial?(cwyear, cweek, cwday, start = Date::ITALY) -> true or false + # + # Returns +true+ if the arguments define a valid commercial date, + # +false+ otherwise: + # + # Date.valid_commercial?(2001, 5, 6) # => true + # Date.valid_commercial?(2001, 5, 8) # => false + # + # See Date.commercial. + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # + # Related: Date.jd, Date.commercial. + def valid_commercial?(year, week, day, start = DEFAULT_SG) + return false unless numeric?(year) + return false unless numeric?(week) + return false unless numeric?(day) + + result = valid_commercial_sub(year, week, day, start, false) + + !result.nil? + end + + # call-seq: + # Date.today(start = Date::ITALY) -> date + # + # Returns a new \Date object constructed from the present date: + # + # Date.today.to_s # => "2022-07-06" + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + def today(start = DEFAULT_SG) + begin + time = Time.now + rescue + raise SystemCallError, "time" + end + + begin + y = time.year + m = time.month + d = time.day + rescue + raise SystemCallError, "localtime" + end + + nth, ry, _, _ = decode_year(y, -1) + + obj = allocate + obj.instance_variable_set(:@nth, nth) + obj.instance_variable_set(:@year, ry) + obj.instance_variable_set(:@month, m) + obj.instance_variable_set(:@day, d) + obj.instance_variable_set(:@jd, nil) + obj.instance_variable_set(:@sg, GREGORIAN) + obj.instance_variable_set(:@has_jd, false) + obj.instance_variable_set(:@has_civil, true) + + if start != GREGORIAN + obj.instance_variable_set(:@sg, start) + if obj.instance_variable_get(:@has_jd) + obj.instance_variable_set(:@jd, nil) + obj.instance_variable_set(:@has_jd, false) + end + end + + obj + end + + # :nodoc: + # C: date_s__load — for Marshal format 1.4, 1.6, 1.8 (u: prefix) + def _load(s) + a = Marshal.load(s) + obj = allocate + obj.marshal_load(a) + obj + end + + private + + # Optimized: Gregorian date -> Julian Day Number + def gregorian_civil_to_jd(year, month, day) + # Shift epoch to March 1 of year 0 (Jan/Feb belong to previous year) + j = (month < 3) ? 1 : 0 + y0 = year - j + m0 = j == 1 ? month + 12 : month + d0 = day - 1 + + # Calculate year contribution with leap year correction + q1 = y0 / NS_YEARS_PER_CENTURY + yc = (NS_DAYS_IN_4_YEARS * y0) / 4 - q1 + (q1 / 4) + + # Calculate month contribution using integer arithmetic + mc = (NS_CIVIL_MONTH_COEFF * m0 - NS_CIVIL_MONTH_OFFSET) / NS_CIVIL_MONTH_DIVISOR + + # Combine and add epoch offset to get JDN + yc + mc + d0 + NS_EPOCH + end + + def julian_civil_to_jd(y, m, d) + # Traditional Julian calendar algorithm + y2 = y + m2 = m + + if m2 <= 2 + y2 -= 1 + m2 += 12 + end + + (365.25 * (y2 + 4716)).floor + (30.6001 * (m2 + 1)).floor + d - 1524 + end + + def validate_ordinal(year, yday, sg) + # Handling negative day of year + if yday < 0 + # Counting backwards from the end of the year + last_jd, _ = c_find_ldoy(year, sg) + return nil unless last_jd + + # Recalculate the total number of days in the year from the calculated JD + adjusted_jd = last_jd + yday + 1 + y, d = jd_to_ordinal(adjusted_jd, sg) + + # Invalid if the year does not match + return nil if y != year + + yday = d + end + + # Calculate jd from the day of the year + nth, ry, _, _ = decode_year(year, sg) + first_jd, ns = c_find_fdoy(ry, sg) + + return nil unless first_jd + + jd = first_jd + yday - 1 + + # Verify that the calculated jd actually belongs to the specified year + verify_y, verify_d = jd_to_ordinal(jd, sg) + return nil if verify_y != ry || verify_d != yday + + [nth, ry, yday, jd, ns] + end + + def extract_fraction(value) + if value.is_a?(Rational) || value.is_a?(Float) + int_part = value.floor + frac_part = value - int_part + [int_part, frac_part] + else + [value.to_i, 0] + end + end + + def jd_to_ordinal(jd, sg) + year, _, _ = jd_to_civil_internal(jd, sg) + first_jd, _ = c_find_fdoy(year, sg) + yday = jd - first_jd + 1 + + [year, yday] + end + + def validate_commercial(year, week, day, sg) + if day < 0 + day += 8 # -1 -> 7 (Sun), -7 -> 1 (Mon) + end + + return nil if day < 1 || day > 7 + + if week < 0 + next_year_jd, ns = commercial_to_jd_internal(year + 1, 1, 1, sg) + return nil unless next_year_jd + + adjusted_jd = next_year_jd + week * 7 + y2, w2, _ = jd_to_commercial_internal(adjusted_jd, sg) + + return nil if y2 != year + + week = w2 + end + + # Calculate jd from ISO week date + nth, ry, _, _ = decode_year(year, sg) + jd, ns = commercial_to_jd_internal(ry, week, day, sg) + + return nil unless jd + + verify_y, verify_w, verify_d = jd_to_commercial_internal(jd, sg) + return nil if verify_y != ry || verify_w != week || verify_d != day + + [nth, ry, week, day, jd, ns] + end + + def commercial_to_jd_internal(cwyear, cweek, cwday, sg) + # Calculating ISO week date(The week containing January 4 is week 1) + jan4_jd = gregorian_civil_to_jd(cwyear, 1, 4) + + # Day of the week on which January 4th falls + # (0 = Sun, 1 = Mon, ..., 6 = Sat) + jan4_wday = (jan4_jd + 1) % 7 + + # Monday of week 1 + week1_mon = jan4_jd - jan4_wday + 1 + + # jd for a specified weekday + jd = week1_mon + (cweek - 1) * 7 + (cwday - 1) + + # If before sg, it is the Julian calendar + ns = jd >= sg ? 1 : 0 + + [jd, ns] + end + + def jd_to_commercial_internal(jd, sg) + # get date from jd + year, _, _ = jd_to_civil_internal(jd, sg) + + # calculate jd for January 4 of that year + jan4_jd = gregorian_civil_to_jd(year, 1, 4) + jan4_wday = (jan4_jd + 1) % 7 + week1_mon = jan4_jd - jan4_wday + 1 + + # If jd is before the first week, it belongs to the previous year + if jd < week1_mon + year -= 1 + jan4_jd = gregorian_civil_to_jd(year, 1, 4) + jan4_wday = (jan4_jd + 1) % 7 + week1_mon = jan4_jd - jan4_wday + 1 + end + + # check the first week of the next year + next_jan4 = gregorian_civil_to_jd(year + 1, 1, 4) + next_jan4_wday = (next_jan4 + 1) % 7 + next_week1_mon = next_jan4 - next_jan4_wday + 1 + + if jd >= next_week1_mon + year += 1 + week1_mon = next_week1_mon + end + + # Calculate the week number + week = (jd - week1_mon) / 7 + 1 + + # week(1 = mon, ..., 7 = sun) + cwday = (jd + 1) % 7 + cwday = 7 if cwday.zero? + + [year, week, cwday] + end + + def jd_to_civil_internal(jd, sg) + # Does it overlap with jd_to_civil? + # Calculate the date from jd (using existing methods) + # simple version + r0 = jd - NS_EPOCH + + n1 = 4 * r0 + 3 + q1 = n1 / NS_DAYS_IN_400_YEARS + r1 = (n1 % NS_DAYS_IN_400_YEARS) / 4 + + n2 = 4 * r1 + 3 + u2 = NS_YEAR_MULTIPLIER * n2 + q2 = u2 >> 32 + r2 = (u2 & 0xFFFFFFFF) / NS_YEAR_MULTIPLIER / 4 + + n3 = NS_MONTH_COEFF * r2 + NS_MONTH_OFFSET + q3 = n3 >> 16 + r3 = (n3 & 0xFFFF) / NS_MONTH_COEFF + + y0 = NS_YEARS_PER_CENTURY * q1 + q2 + j = (r2 >= NS_DAYS_BEFORE_NEW_YEAR) ? 1 : 0 + + year = y0 + j + month = j == 1 ? q3 - 12 : q3 + day = r3 + 1 + + [year, month, day] + end + + def valid_civil_date?(year, month, day, sg) + return false if month < 1 || month > 12 + + if sg == GREGORIAN || sg < 0 + last_day = last_day_of_month_gregorian(year, month) + elsif sg == JULIAN || sg > 0 + last_day = last_day_of_month_julian(year, month) + else + # Calculate (calendar reform period - jd) and determine + jd = gregorian_civil_to_jd(year, month, day) + + if jd < sg + last_day = last_day_of_month_julian(year, month) + else + last_day = last_day_of_month_gregorian(year, month) + end + end + + return false if day < 1 || day > last_day + + true + end + + def last_day_of_month_gregorian(y, m) + return nil if m < 1 || m > 12 + + leap_index = gregorian_leap?(y) ? 1 : 0 + MONTH_DAYS[leap_index][m] + end + + def last_day_of_month_julian(y, m) + return nil if m < 1 || m > 12 + + leap_index = julian_leap?(y) ? 1 : 0 + MONTH_DAYS[leap_index][m] + end + + def civil_to_jd_with_check(year, month, day, sg) + return nil unless valid_civil_date?(year, month, day, sg) + + jd, ns = civil_to_jd(year, month, day, sg) + + [jd, ns] + end + + def civil_to_jd(year, month, day, sg) + if sg == GREGORIAN + jd = gregorian_civil_to_jd(year, month, day) + + return [jd, 1] + end + + jd = gregorian_civil_to_jd(year, month, day) + + if jd < sg + jd = julian_civil_to_jd(year, month, day) + ns = 0 + else + ns = 1 + end + + [jd, ns] + end + + def last_day_of_month_for_sg(year, month, sg) + last_day_of_month_gregorian(year, month) + end + + def validate_civil(year, month, day, sg) + month += 13 if month < 0 + return nil if month < 1 || month > 12 + + if day < 0 + last_day = last_day_of_month_gregorian(year, month) + return nil unless last_day + day = last_day + day + 1 + end + + last_day = last_day_of_month_gregorian(year, month) + return nil if day < 1 || day > last_day + + nth, ry = decode_year(year, -1) + + jd, ns = civil_to_jd_with_style(ry, month, day, sg) + + [nth, ry, month, day, jd, ns] + end + + def civil_to_jd_with_style(year, month, day, sg) + jd = gregorian_civil_to_jd(year, month, day) + + if jd < sg + jd = julian_civil_to_jd(year, month, day) + ns = 0 + else + ns = 1 + end + + [jd, ns] + end + + def convert_to_integer(value) + if value.respond_to?(:to_int) + value.to_int + elsif value.is_a?(Numeric) + value.to_i + else + value + end + end + + def numeric?(value) + value.is_a?(Numeric) || value.respond_to?(:to_int) + end + + def valid_civil_sub(year, month, day, start, need_jd) + year = convert_to_integer(year) + month = convert_to_integer(month) + day = convert_to_integer(day) + + start = valid_sg(start) + + return nil if month < 1 || month > 12 + + leap_year = start == JULIAN ? julian_leap?(year) : gregorian_leap?(year) + + days_in_month = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + max_day = (month == 2 && leap_year) ? 29 : days_in_month[month] + + return nil if day < 1 || day > max_day + + need_jd ? civil_to_jd(year, month, day, start) : 0 + end + + def valid_sg(start) + unless c_valid_start_p(start) + warn "invalid start is ignored" + return 0 + end + + start + end + + def c_valid_start_p(start) + return false unless start.is_a?(Numeric) + + return false if start.respond_to?(:nan?) && start.nan? + + return true if start.respond_to?(:infinite?) && start.infinite? + + return false if start < REFORM_BEGIN_JD || start > REFORM_END_JD + + true + end + + def valid_jd_sub(jd, start, need_jd) + valid_sg(start) + + jd + end + + def valid_commercial_sub(year, week, day, start, need_jd) + week = convert_to_integer(week) + day = convert_to_integer(day) + + valid_sg(start) + + result = valid_commercial_p(year, week, day, start) + + return nil unless result + + return 0 unless need_jd + + encode_jd(result[:nth], result[:rjd]) + end + + def valid_commercial_p(year, week, day, start) + style = guess_style(year, start) + + if style.zero? + int_year = year.to_i + result = c_valid_commercial_p(int_year, week, day, start) + return nil unless result + + nth, rjd = decode_jd(result[:jd]) + + if f_zero_p?(nth) + ry = int_year + else + ns = result[:ns] + _, ry = decode_year(year, ns.nonzero? ? -1 : 1) + end + + { nth: nth, ry: ry, rw: result[:rw], rd: result[:rd], rjd: rjd, ns: result[:ns] } + else + nth, ry = decode_year(year, style) + result = c_valid_commercial_p(ry, week, day, style) + return nil unless result + + { nth: nth, ry: ry, rw: result[:rw], rd: result[:rd], rjd: result[:jd], ns: result[:ns] } + end + end + + def guess_style(year, sg) + return sg if sg.infinite? + return year >= 0 ? GREGORIAN : JULIAN unless year.is_a?(Integer) && year.abs < (1 << 62) + + int_year = year.to_i + if int_year < REFORM_BEGIN_YEAR + JULIAN + elsif int_year > REFORM_END_YEAR + GREGORIAN + else + 0 + end + end + + def c_valid_commercial_p(year, week, day, sg) + day += 8 if day < 0 + + if week < 0 + rjd2, _ = c_commercial_to_jd(year + 1, 1, 1, sg) + ry2, rw2, _ = c_jd_to_commercial(rjd2 + week * 7, sg) + return nil if ry2 != year + + week = rw2 + end + + rjd, ns = c_commercial_to_jd(year, week, day, sg) + ry2, rw, rd = c_jd_to_commercial(rjd, sg) + + return nil if year != ry2 || week != rw || day != rd + + { jd: rjd, ns: ns, rw: rw, rd: rd } + end + + def c_commercial_to_jd(year, week, day, sg) + rjd2, _ = c_find_fdoy(year, sg) + rjd2 += 3 + + # Calcurate ISO week number. + rjd = (rjd2 - ((rjd2 - 1 + 1) % 7)) + 7 * (week - 1) + (day - 1) + ns = (rjd < sg) ? 0 : 1 + + [rjd, ns] + end + + def c_jd_to_commercial(jd, sg) + ry2, _, _ = c_jd_to_civil(jd - 3, sg) + a = ry2 + + rjd2, _ = c_commercial_to_jd(a + 1, 1, 1, sg) + if jd >= rjd2 + ry = a + 1 + else + rjd2, _ = c_commercial_to_jd(a, 1, 1, sg) + ry = a + end + + rw = 1 + (jd - rjd2) / 7 + rd = (jd + 1) % 7 + rd = 7 if rd.zero? + + [ry, rw, rd] + end + + def c_find_fdoy(year, sg) + if c_gregorian_only_p?(sg) + jd = c_gregorian_fdoy(year) + + return [jd, 1] + end + + # Keep existing loop for Julian/reform period + (1..30).each do |d| + result = c_valid_civil_p(year, 1, d, sg) + + return [result[:jd], result[:ns]] if result + end + + [nil, nil] + end + + def c_find_ldom(year, month, sg) + if c_gregorian_only_p?(sg) + jd = c_gregorian_ldom_jd(year, month) + + return [jd, 1] + end + + # Keep existing loop for Julian/reform period + (0..29).each do |i| + result = c_valid_civil_p(year, month, 31 - i, sg) + return [result[:jd], result[:ns]] if result + end + + nil + end + + def c_gregorian_fdoy(year) + c_gregorian_civil_to_jd(year, 1, 1) + end + + def c_jd_to_civil(jd, sg) + # Fast path: pure Gregorian or date after switchover, within safe range + if (c_gregorian_only_p?(sg) || jd >= sg) && ns_jd_in_range(jd) + return c_gregorian_jd_to_civil(jd) + end + + # Original algorithm for Julian calendar or extreme dates + if jd < sg + a = jd + else + x = ((jd - 1867216.25) / 36524.25).floor + a = jd + 1 + x - (x / 4.0).floor + end + + b = a + 1524 + c = ((b - 122.1) / 365.25).floor + d = (365.25 * c).floor + e = ((b - d) / 30.6001).floor + dom = b - d - (30.6001 * e).floor + + if e <= 13 + m = e - 1 + y = c - 4716 + else + m = e - 13 + y = c - 4715 + end + + [y.to_i, m.to_i, dom.to_i] + end + + # Optimized: Julian Day Number -> Gregorian date + def c_gregorian_jd_to_civil(jd) + # The argument jd of c_gregorian_jd_to_civil implemented in C is of type int, + # so it is converted to Integer. + jd = jd.to_i unless jd.is_a?(Integer) + + # Convert JDN to rata die (March 1, Year 0 epoch) + r0 = jd - NS_EPOCH + + # Extract century and day within 400-year cycle + # Use Euclidean (floor) division for negative values + n1 = 4 * r0 + 3 + q1 = n1 / NS_DAYS_IN_400_YEARS + r1 = (n1 % NS_DAYS_IN_400_YEARS) / 4 + + # Calculate year within century and day of year + n2 = 4 * r1 + 3 + # Use 64-bit arithmetic to avoid overflow + u2 = NS_YEAR_MULTIPLIER * n2 + q2 = u2 >> 32 + r2 = (u2 & 0xFFFFFFFF) / NS_YEAR_MULTIPLIER / 4 + + # Calculate month and day using integer arithmetic + n3 = NS_MONTH_COEFF * r2 + NS_MONTH_OFFSET + q3 = n3 >> 16 + r3 = (n3 & 0xFFFF) / NS_MONTH_COEFF + + # Combine century and year + y0 = NS_YEARS_PER_CENTURY * q1 + q2 + + # Adjust for January/February (shift from fiscal year) + j = (r2 >= NS_DAYS_BEFORE_NEW_YEAR) ? 1 : 0 + + ry = y0 + j + rm = j.nonzero? ? q3 - 12 : q3 + rd = r3 + 1 + + [ry, rm, rd] + end + + def c_gregorian_civil_to_jd(year, month, day) + j = (month < 3) ? 1 : 0 + y0 = year - j + m0 = j.nonzero? ? month + 12 : month + d0 = day - 1 + + q1 = y0 / 100 + yc = (NS_DAYS_IN_4_YEARS * y0) / 4 - q1 + q1 / 4 + + mc = (NS_DAYS_BEFORE_NEW_YEAR * m0 - 914) / 10 + + yc + mc + d0 + NS_EPOCH + end + + def valid_civil_p(y, m, d, sg) + style = guess_style(y, sg) + + if style.zero? + # If year is a Fixnum + int_year = y.to_i + + # Validate with c_valid_civil_p + result = c_valid_civil_p(int_year, m, d, sg) + return nil unless result + + # decode_jd + nth, rjd = decode_jd(result[:jd]) + + if f_zero_p?(nth) + ry = int_year + else + ns = result[:ns] + _, ry = decode_year(y, ns.nonzero? ? -1 : 1) + end + + return { nth: nth, ry: ry, rm: result[:rm], rd: result[:rd], rjd: rjd, ns: result[:ns] } + else + # If year is a large number + nth, ry = decode_year(y, style) + + result = style < 0 ? c_valid_gregorian_p(ry, m, d) : result = c_valid_julian_p(ry, m, d) + return nil unless result + + # Calculate JD from civil + rjd, ns = c_civil_to_jd(ry, result[:rm], result[:rd], style) + + return { nth: nth, ry: ry, rm: result[:rm], rd: result[:rd], rjd: rjd, ns: ns } + end + end + + def c_valid_civil_p(year, month, day, sg) + month += 13 if month < 0 + return nil if month < 1 || month > 12 + + rd = day + if rd < 0 + result = c_find_ldom(year, month, sg) + return nil unless result + + rjd2, _ = result + ry2, rm2, rd2 = c_jd_to_civil(rjd2 + rd + 1, sg) + return nil if ry2 != year || rm2 != month + + rd = rd2 + end + + rjd, ns = c_civil_to_jd(year, month, rd, sg) + ry2, rm2, rd2 = c_jd_to_civil(rjd, sg) + + return nil if ry2 != year || rm2 != month || rd2 != rd + + { jd: rjd, ns: ns, rm: rm2, rd: rd } + end + + def c_gregorian_ldom_jd(year, month) + last_day = c_gregorian_last_day_of_month(year, month) + c_gregorian_civil_to_jd(year, month, last_day) + end + + def c_gregorian_last_day_of_month(year, month) + days_in_month = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] + + if month == 2 && gregorian_leap?(year) + 29 + else + days_in_month[month] + end + end + + def c_civil_to_jd(year, month, day, sg) + if c_gregorian_only_p?(sg) + jd = c_gregorian_civil_to_jd(year, month, day) + + return [jd, 1] + end + + # Calculate Gregorian JD using optimized algorithm + jd = c_gregorian_civil_to_jd(year, month, day) + + if jd < sg + y2 = year + m2 = month + if m2 <= 2 + y2 -= 1 + m2 += 12 + end + jd = (365.25 * (y2 + 4716)).floor + (30.6001 * (m2 + 1)).floor + day - 1524 + ns = 0 + else + ns = 1 + end + + [jd, ns] + end + + def decode_jd(jd) + nth = jd / CM_PERIOD + rjd = f_zero_p?(nth) ? jd : jd % CM_PERIOD + + [nth, rjd] + end + + def encode_jd(nth, rjd) + f_zero_p?(nth) ? rjd : nth * CM_PERIOD + rjd + end + + def decode_year(year, style) + period = (style < 0) ? CM_PERIOD_GCY : CM_PERIOD_JCY + + if year.is_a?(Integer) && year.abs < (1 << 30) + shifted = year + 4712 + nth = shifted / period + + shifted = shifted % period if f_nonzero_p?(nth) + + ry = shifted - 4712 + else + shifted = year + 4712 + nth = shifted / period + + shifted = shifted % period if f_nonzero_p?(nth) + + ry = shifted.to_i - 4712 + end + + [nth, ry] + end + + # Check if using pure Gregorian calendar (sg == -Infinity) + def c_gregorian_only_p?(sg) + sg.infinite? && sg < 0 + end + + def valid_ordinal_sub(year, day, start, need_jd) + day = convert_to_integer(day) + + valid_sg(start) + + result = valid_ordinal_p(year, day, start) + + return nil unless result + + return 0 unless need_jd + + encode_jd(result[:nth], result[:rjd]) + end + + def valid_ordinal_p(year, day, start) + style = guess_style(year, start) + + if style.zero? + int_year = year.to_i + result = c_valid_ordinal_p(int_year, day, start) + + return nil unless result + + nth, rjd = decode_jd(result[:jd]) + + if f_zero_p?(nth) + ry = int_year + else + ns = result[:ns] + _, ry = decode_year(year, ns.nonzero? ? -1 : 1) + end + + return { nth: nth, ry: ry, rd: result[:rd], rjd: rjd, ns: result[:ns] } + else + nth, ry = decode_year(year, style) + result = c_valid_ordinal_p(ry, day, style) + return nil unless result + + return { nth: nth, ry: ry, rd: result[:rd], rjd: result[:jd], ns: result[:ns] } + end + end + + def c_valid_ordinal_p(year, day, sg) + rd = day + if rd < 0 + result = c_find_ldoy(year, sg) + return nil unless result + + rjd2, _ = result + ry2, rd2 = c_jd_to_ordinal(rjd2 + rd + 1, sg) + return nil if ry2 != year + + rd = rd2 + end + + rjd, ns = c_ordinal_to_jd(year, rd, sg) + ry2, rd2 = c_jd_to_ordinal(rjd, sg) + + return nil if ry2 != year || rd2 != rd + + { jd: rjd, ns: ns, rd: rd } + end + + def c_find_ldoy(year, sg) + if c_gregorian_only_p?(sg) + jd = c_gregorian_ldoy(year) + + return [jd, 1] + end + + # Keep existing loop for Julian/reform period + (0..29).each do |i| + result = c_valid_civil_p(year, 12, 31 - i, sg) + + return [result[:jd], result[:ns]] if result + end + + nil + end + + # O(1) last day of year for Gregorian calendar + def c_gregorian_ldoy(year) + c_gregorian_civil_to_jd(year, 12, 31) + end + + def c_jd_to_ordinal(jd, sg) + ry, _, _ = c_jd_to_civil(jd, sg) + rjd, _ = c_find_fdoy(ry, sg) + + rd = (jd - rjd) + 1 + + [ry, rd] + end + + def c_ordinal_to_jd(year, day, sg) + rjd, _ = c_find_fdoy(year, sg) + rjd += day - 1 + ns = (rjd < sg) ? 0 : 1 + + [rjd, ns] + end + + def f_zero_p?(x) + case x + when Integer + x.zero? + when Rational + x.numerator == 0 + else + x == 0 + end + end + + def f_nonzero_p?(x) + !f_zero_p?(x) + end + + def c_gregorian_leap_p?(year) + !!(((year % 4).zero? && (year % 100).nonzero?) || (year % 400).zero?) + end + + def c_julian_leap_p?(year) + (year % 4).zero? + end + + def new_with_jd(nth, jd, start) + new_with_jd_and_time(nth, jd, nil, nil, nil, start) + end + + def new_with_jd_and_time(nth, jd, df, sf, of, start) + obj = allocate + obj.instance_variable_set(:@nth, nth) + obj.instance_variable_set(:@jd, jd) + obj.instance_variable_set(:@sg, start) + obj.instance_variable_set(:@df, df) + obj.instance_variable_set(:@sf, sf) + obj.instance_variable_set(:@of, of) + obj.instance_variable_set(:@year, nil) + obj.instance_variable_set(:@month, nil) + obj.instance_variable_set(:@day, nil) + obj.instance_variable_set(:@has_jd, true) + obj.instance_variable_set(:@has_civil, false) + + obj + end + + def valid_gregorian_p(y, m, d) + decode_year(y, -1) + + c_valid_gregorian_p(y, m, d) + end + + def c_valid_gregorian_p(y, m, d) + m += 13 if m < 0 + return nil if m < 1 || m > 12 + + last = c_gregorian_last_day_of_month(y, m) + d = last + d + 1 if d < 0 + return nil if d < 1 || d > last + + { rm: m, rd: d } + end + + def c_valid_julian_p(y, m, d) + m += 13 if m < 0 + return nil if m < 1 || m > 12 + + last = c_julian_last_day_of_month(y, m) + d = last + d + 1 if d < 0 + return nil if d < 1 || d > last + + { rm: m, rd: d } + end + + def c_julian_last_day_of_month(y, m) + raise Error unless m >= 1 && m <= 12 + + MONTH_DAYS[julian_leap?(y) ? 1 : 0][m] + end + + # Create a simple Date object. + def d_lite_s_alloc_simple + obj = allocate + obj.instance_variable_set(:@nth, 0) + obj.instance_variable_set(:@jd, 0) + obj.instance_variable_set(:@sg, DEFAULT_SG) + obj.instance_variable_set(:@df, nil) + obj.instance_variable_set(:@sf, nil) + obj.instance_variable_set(:@of, nil) + obj.instance_variable_set(:@year, nil) + obj.instance_variable_set(:@month, nil) + obj.instance_variable_set(:@day, nil) + obj.instance_variable_set(:@has_jd, true) + obj.instance_variable_set(:@has_civil, false) + + obj + end + + # Create a complex Date object. + def d_lite_s_alloc_complex + obj = allocate + obj.instance_variable_set(:@nth, 0) + obj.instance_variable_set(:@jd, 0) + obj.instance_variable_set(:@sg, DEFAULT_SG) + obj.instance_variable_set(:@df, nil) + obj.instance_variable_set(:@sf, nil) + obj.instance_variable_set(:@of, nil) + obj.instance_variable_set(:@year, nil) + obj.instance_variable_set(:@month, nil) + obj.instance_variable_set(:@day, nil) + obj.instance_variable_set(:@hour, nil) + obj.instance_variable_set(:@min, nil) + obj.instance_variable_set(:@sec, nil) + obj.instance_variable_set(:@has_jd, true) + obj.instance_variable_set(:@has_civil, false) + + obj + end + + def value_trunc(value) + if value.is_a?(Integer) + [value, 0] + elsif value.is_a?(Float) || value.is_a?(Rational) + trunc = value.truncate + frac = value - trunc + + [trunc, frac] + else + [value.to_i, 0] + end + end + + def d_simple_new_internal(nth, jd, sg, year, mon, mday, flags) + obj = allocate + obj.instance_variable_set(:@nth, canon(nth)) + obj.instance_variable_set(:@jd, jd) + obj.instance_variable_set(:@sg, sg) + obj.instance_variable_set(:@year, year) + obj.instance_variable_set(:@month, mon) + obj.instance_variable_set(:@day, mday) + obj.instance_variable_set(:@has_jd, (flags & HAVE_JD).nonzero?) + obj.instance_variable_set(:@has_civil, (flags & HAVE_CIVIL).nonzero?) + obj.instance_variable_set(:@df, nil) + obj.instance_variable_set(:@sf, nil) + obj.instance_variable_set(:@of, nil) + + obj + end + + def canon(x) + x.is_a?(Rational) && x.denominator == 1 ? x.numerator : x + end + + def ns_jd_in_range(jd) + jd >= NS_JD_MIN && jd <= NS_JD_MAX + end + + def check_limit(str, limit) + unless str.is_a?(String) + begin + str = str.to_str + rescue NoMethodError + raise TypeError, "no implicit conversion of #{str.class} into String" + end + end + + if limit && str.length > limit + raise ArgumentError, "string length (#{str.length}) exceeds the limit #{limit}" + end + + str + end + end + + # Instance methods + + # call-seq: + # year -> integer + # + # Returns the year: + # + # Date.new(2001, 2, 3).year # => 2001 + # (Date.new(1, 1, 1) - 1).year # => 0 + def year + m_real_year + end + + # call-seq: + # mon -> integer + # + # Returns the month in range (1..12): + # + # Date.new(2001, 2, 3).mon # => 2 + def month + m_mon + end + alias mon month + + def day + m_mday + end + alias mday day + + # call-seq: + # d.jd -> integer + # + # Returns the Julian day number. This is a whole number, which is + # adjusted by the offset as the local time. + # + # DateTime.new(2001,2,3,4,5,6,'+7').jd #=> 2451944 + # DateTime.new(2001,2,3,4,5,6,'-7').jd #=> 2451944 + def jd + m_real_jd + end + + # call-seq: + # start -> float + # + # Returns the Julian start date for calendar reform; + # if not an infinity, the returned value is suitable + # for passing to Date#jd: + # + # d = Date.new(2001, 2, 3, Date::ITALY) + # s = d.start # => 2299161.0 + # Date.jd(s).to_s # => "1582-10-15" + # + # d = Date.new(2001, 2, 3, Date::ENGLAND) + # s = d.start # => 2361222.0 + # Date.jd(s).to_s # => "1752-09-14" + # + # Date.new(2001, 2, 3, Date::GREGORIAN).start # => -Infinity + # Date.new(2001, 2, 3, Date::JULIAN).start # => Infinity + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + def start + @sg + end + + # call-seq: + # self <=> other -> -1, 0, 1 or nil + # + # Compares +self+ and +other+, returning: + # + # - -1 if +other+ is larger. + # - 0 if the two are equal. + # - 1 if +other+ is smaller. + # - +nil+ if the two are incomparable. + # + # Argument +other+ may be: + # + # - Another \Date object: + # + # d = Date.new(2022, 7, 27) # => # + # prev_date = d.prev_day # => # + # next_date = d.next_day # => # + # d <=> next_date # => -1 + # d <=> d # => 0 + # d <=> prev_date # => 1 + # + # - A DateTime object: + # + # d <=> DateTime.new(2022, 7, 26) # => 1 + # d <=> DateTime.new(2022, 7, 27) # => 0 + # d <=> DateTime.new(2022, 7, 28) # => -1 + # + # - A numeric (compares self.ajd to +other+): + # + # d <=> 2459788 # => -1 + # d <=> 2459787 # => 1 + # d <=> 2459786 # => 1 + # d <=> d.ajd # => 0 + # + # - Any other object: + # + # d <=> Object.new # => nil + def <=>(other) + case other + when Date + m_canonicalize_jd + other.send(:m_canonicalize_jd) + + a_nth = m_nth + b_nth = other.send(:m_nth) + + cmp = a_nth <=> b_nth + return cmp if cmp.nonzero? + + a_jd = m_jd + b_jd = other.send(:m_jd) + + cmp = a_jd <=> b_jd + return cmp if cmp.nonzero? + + a_df = m_df + b_df = other.send(:m_df) + + cmp = a_df <=> b_df + return cmp if cmp.nonzero? + + a_sf = m_sf + b_sf = other.send(:m_sf) + + a_sf <=> b_sf + when Numeric + ajd <=> other + else + begin + l, r = other.coerce(self) + l <=> r + rescue NoMethodError + nil + end + end + end + + # call-seq: + # self === other -> true, false, or nil. + # + # Returns +true+ if +self+ and +other+ represent the same date, + # +false+ if not, +nil+ if the two are not comparable. + # + # Argument +other+ may be: + # + # - Another \Date object: + # + # d = Date.new(2022, 7, 27) # => # + # prev_date = d.prev_day # => # + # next_date = d.next_day # => # + # d === prev_date # => false + # d === d # => true + # d === next_date # => false + # + # - A DateTime object: + # + # d === DateTime.new(2022, 7, 26) # => false + # d === DateTime.new(2022, 7, 27) # => true + # d === DateTime.new(2022, 7, 28) # => false + # + # - A numeric (compares self.jd to +other+): + # + # d === 2459788 # => true + # d === 2459787 # => false + # d === 2459786 # => false + # d === d.jd # => true + # + # - An object not comparable: + # + # d === Object.new # => nil + def ===(other) + return equal_gen(other) unless other.is_a?(Date) + + # Call equal_gen even if the Gregorian calendars do not match. + return equal_gen(other) unless m_gregorian_p? == other.send(:m_gregorian_p?) + + m_canonicalize_jd + other.send(:m_canonicalize_jd) + + a_nth = m_nth + b_nth = other.send(:m_nth) + a_jd = m_local_jd + b_jd = other.send(:m_local_jd) + + a_nth == b_nth && a_jd == b_jd + end + + # call-seq: + # d >> n -> new_date + # + # Returns a new \Date object representing the date + # +n+ months later; +n+ should be a numeric: + # + # (Date.new(2001, 2, 3) >> 1).to_s # => "2001-03-03" + # (Date.new(2001, 2, 3) >> -2).to_s # => "2000-12-03" + # + # When the same day does not exist for the new month, + # the last day of that month is used instead: + # + # (Date.new(2001, 1, 31) >> 1).to_s # => "2001-02-28" + # (Date.new(2001, 1, 31) >> -4).to_s # => "2000-09-30" + # + # This results in the following, possibly unexpected, behaviors: + # + # d0 = Date.new(2001, 1, 31) + # d1 = d0 >> 1 # => # + # d2 = d1 >> 1 # => # + # + # d0 = Date.new(2001, 1, 31) + # d1 = d0 >> 1 # => # + # d2 = d1 >> -1 # => # + def >>(n) + # Calculate years and months + t = m_real_year * 12 + (m_mon - 1) + n + + if t.is_a?(Integer) && t.abs < (1 << 62) + # Fixnum + y = t / 12 + m = (t % 12) + 1 + else + # Bignum + y = t.div(12) + m = (t % 12).to_i + 1 + end + + d = m_mday + sg = m_sg + + # Decrement days until a valid date. + result = nil + loop do + result = self.class.send(:valid_civil_p, y, m, d, sg) + break if result + + d -= 1 + raise Error if d < 1 + end + + nth = result[:nth] + rjd = result[:rjd] + rjd2 = self.class.send(:encode_jd, nth, rjd) + + self + (rjd2 - m_real_local_jd) + end + + # call-seq: + # d << n -> date + # + # Returns a new \Date object representing the date + # +n+ months earlier; +n+ should be a numeric: + # + # (Date.new(2001, 2, 3) << 1).to_s # => "2001-01-03" + # (Date.new(2001, 2, 3) << -2).to_s # => "2001-04-03" + # + # When the same day does not exist for the new month, + # the last day of that month is used instead: + # + # (Date.new(2001, 3, 31) << 1).to_s # => "2001-02-28" + # (Date.new(2001, 3, 31) << -6).to_s # => "2001-09-30" + # + # This results in the following, possibly unexpected, behaviors: + # + # d0 = Date.new(2001, 3, 31) + # d0 << 2 # => # + # d0 << 1 << 1 # => # + # + # d0 = Date.new(2001, 3, 31) + # d1 = d0 << 1 # => # + # d2 = d1 << -1 # => # + def <<(n) + raise TypeError, "expected numeric" unless n.is_a?(Numeric) + + self >> (-n) + end + + def ==(other) # :nodoc: + return false unless other.is_a?(Date) + + m_canonicalize_jd + other.send(:m_canonicalize_jd) + + m_nth == other.send(:m_nth) && + m_jd == other.send(:m_jd) && + m_df == other.send(:m_df) && + m_sf == other.send(:m_sf) + end + + def eql?(other) # :nodoc: + return false unless other.is_a?(Date) + + m_canonicalize_jd + other.send(:m_canonicalize_jd) + + m_nth == other.send(:m_nth) && + m_jd == other.send(:m_jd) && + @sg == other.instance_variable_get(:@sg) + end + + def hash # :nodoc: + m_canonicalize_jd + [m_nth, m_jd, @sg].hash + end + + # call-seq: + # d + other -> date + # + # Returns a date object pointing +other+ days after self. The other + # should be a numeric value. If the other is a fractional number, + # assumes its precision is at most nanosecond. + # + # Date.new(2001,2,3) + 1 #=> # + # DateTime.new(2001,2,3) + Rational(1,2) + # #=> # + # DateTime.new(2001,2,3) + Rational(-1,2) + # #=> # + # DateTime.jd(0,12) + DateTime.new(2001,2,3).ajd + # #=> # + def +(other) + case other + when Integer + nth = m_nth + jd = m_jd + + if (other / CM_PERIOD).nonzero? + nth = nth + (other / CM_PERIOD) + other = other % CM_PERIOD + end + + if other.nonzero? + jd = jd + other + nth, jd = canonicalize_jd(nth, jd) + end + + if simple_dat_p? + self.class.send(:new_with_jd, nth, jd, @sg) + else + self.class.send(:new_with_jd_and_time, nth, jd, @df || 0, @sf || 0, @of || 0, @sg) + end + when Float + s = other >= 0 ? 1 : -1 + o = other.abs + + tmp, o = o.divmod(1.0) + + if (tmp / CM_PERIOD).floor.zero? + nth = 0 + jd = tmp.to_i + else + i, f = (tmp / CM_PERIOD).divmod(1.0) + nth = i.floor + jd = (f * CM_PERIOD).to_i + end + + o *= DAY_IN_SECONDS + df, o = o.divmod(1.0) + df = df.to_i + o *= SECOND_IN_NANOSECONDS + sf = o.round + + if s < 0 + jd = -jd + df = -df + sf = -sf + end + + if sf.nonzero? + sf = 0 + sf + if sf < 0 + df -= 1 + sf += SECOND_IN_NANOSECONDS + elsif sf >= SECOND_IN_NANOSECONDS + df += 1 + sf -= SECOND_IN_NANOSECONDS + end + end + + if df.nonzero? + df = 0 + df + if df < 0 + jd -= 1 + df += DAY_IN_SECONDS + elsif df >= DAY_IN_SECONDS + jd += 1 + df -= DAY_IN_SECONDS + end + end + + if jd.nonzero? + jd = m_jd + jd + nth, jd = canonicalize_jd(nth, jd) + else + jd = m_jd + end + + nth = nth.nonzero? ? @nth + nth : @nth + + if df.zero? && sf.zero? && (@of.nil? || @of.zero?) + self.class.send(:new_with_jd, nth, jd, @sg) + else + self.class.send(:new_with_jd_and_time, nth, jd, df, sf, @of || 0, @sg) + end + when Rational + return self + other.numerator if other.denominator == 1 + + s = other >= 0 ? 1 : -1 + other = other.abs + + nth = other.div(CM_PERIOD) + t = other % CM_PERIOD + + jd = t.div(1).to_i + t = t % 1 + + t = t * DAY_IN_SECONDS + df = t.div(1).to_i + t = t % 1 + + sf = t * SECOND_IN_NANOSECONDS + + if s < 0 + nth = -nth + jd = -jd + df = -df + sf = -sf + end + + if sf.nonzero? + sf = (@sf || 0) + sf + if sf < 0 + df -= 1 + sf += SECOND_IN_NANOSECONDS + elsif sf >= SECOND_IN_NANOSECONDS + df += 1 + sf -= SECOND_IN_NANOSECONDS + end + else + sf = @sf || 0 + end + + if df.nonzero? + df = (@df || 0) + df + if df < 0 + jd -= 1 + df += DAY_IN_SECONDS + elsif df >= DAY_IN_SECONDS + jd += 1 + df -= DAY_IN_SECONDS + end + else + df = @df || 0 + end + + if jd.nonzero? + jd = m_jd + jd + nth, jd = canonicalize_jd(nth, jd) + else + jd = m_jd + end + + nth = nth.nonzero? ? @nth + nth : @nth + + if df.zero? && sf.zero? + self.class.send(:new_with_jd, nth, jd, @sg) + else + self.class.send(:new_with_jd_and_time, nth, jd, df, sf, @of || 0, @sg) + end + else + raise TypeError, "expected numeric" unless other.is_a?(Numeric) + + other = other.to_r + raise TypeError, "expected numeric" unless other.is_a?(Rational) + + self + other + end + end + + # call-seq: + # d - other -> date or rational + # + # If the other is a date object, returns a Rational + # whose value is the difference between the two dates in days. + # If the other is a numeric value, returns a date object + # pointing +other+ days before self. + # If the other is a fractional number, + # assumes its precision is at most nanosecond. + # + # Date.new(2001,2,3) - 1 #=> # + # DateTime.new(2001,2,3) - Rational(1,2) #=> # + # Date.new(2001,2,3) - Date.new(2001) #=> (33/1) + # DateTime.new(2001,2,3) - DateTime.new(2001,2,2,12) #=> (1/2) + def -(other) + return minus_dd(other) if other.is_a?(Date) + + raise TypeError, "expected numeric" unless other.is_a?(Numeric) + + # Add a negative value for numbers. + # Works with all types: Integer, Float, Rational, Bignum, etc. + self + (-other) + end + + # call-seq: + # gregorian -> new_date + # + # Equivalent to Date#new_start with argument Date::GREGORIAN. + def gregorian + dup_obj_with_new_start(GREGORIAN) + end + + # call-seq: + # gregorian? -> true or false + # + # Returns +true+ if the date is on or after + # the date of calendar reform, +false+ otherwise: + # + # Date.new(1582, 10, 15).gregorian? # => true + # (Date.new(1582, 10, 15) - 1).gregorian? # => false + def gregorian? + m_gregorian_p? + end + + # call-seq: + # italy -> new_date + # + # Equivalent to Date#new_start with argument Date::ITALY. + def italy + dup_obj_with_new_start(ITALY) + end + + # call-seq: + # england -> new_date + # + # Equivalent to Date#new_start with argument Date::ENGLAND. + def england + dup_obj_with_new_start(ENGLAND) + end + + # call-seq: + # julian -> new_date + # + # Equivalent to Date#new_start with argument Date::JULIAN. + def julian + dup_obj_with_new_start(JULIAN) + end + + # call-seq: + # d.julian? -> true or false + # + # Returns +true+ if the date is before the date of calendar reform, + # +false+ otherwise: + # + # (Date.new(1582, 10, 15) - 1).julian? # => true + # Date.new(1582, 10, 15).julian? # => false + def julian? + m_julian_p? + end + + # call-seq: + # ld -> integer + # + # Returns the + # {Lilian day number}[https://en.wikipedia.org/wiki/Lilian_date], + # which is the number of days since the beginning of the Gregorian + # calendar, October 15, 1582. + # + # Date.new(2001, 2, 3).ld # => 152784 + def ld + m_real_local_jd - 2299160 + end + + # call-seq: + # leap? -> true or false + # + # Returns +true+ if the year is a leap year, +false+ otherwise: + # + # Date.new(2000).leap? # => true + # Date.new(2001).leap? # => false + def leap? + if gregorian? + # For the Gregorian calendar, get m_year to determine if it is a leap year. + y = m_year + + return self.class.send(:c_gregorian_leap_p?, y) + end + + # For the Julian calendar, calculate JD for March 1st. + y = m_year + sg = m_virtual_sg + rjd, _ = self.class.send(:c_civil_to_jd, y, 3, 1, sg) + + # Get the date of the day before March 1st (the last day of February). + _, _, rd = self.class.send(:c_jd_to_civil, rjd - 1, sg) + + # If February 29th exists, it is a leap year. + rd == 29 + end + + # call-seq: + # new_start(start = Date::ITALY]) -> new_date + # + # Returns a copy of +self+ with the given +start+ value: + # + # d0 = Date.new(2000, 2, 3) + # d0.julian? # => false + # d1 = d0.new_start(Date::JULIAN) + # d1.julian? # => true + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + def new_start(start = DEFAULT_SG) + sg = start ? val2sg(start) : DEFAULT_SG + + dup_obj_with_new_start(sg) + end + + # call-seq: + # next_day(n = 1) -> new_date + # + # Equivalent to Date#+ with argument +n+. + def next_day(n = 1) + self + n + end + + # call-seq: + # prev_day(n = 1) -> new_date + # + # Equivalent to Date#- with argument +n+. + def prev_day(n = 1) + self - n + end + + # call-seq: + # d.next -> new_date + # + # Returns a new \Date object representing the following day: + # + # d = Date.new(2001, 2, 3) + # d.to_s # => "2001-02-03" + # d.next.to_s # => "2001-02-04" + def next + next_day + end + alias_method :succ, :next + + # call-seq: + # next_year(n = 1) -> new_date + # + # Equivalent to #>> with argument n * 12. + def next_year(n = 1) + self >> (n * 12) + end + + # call-seq: + # prev_year(n = 1) -> new_date + # + # Equivalent to #<< with argument n * 12. + def prev_year(n = 1) + self << (n * 12) + end + + # call-seq: + # next_month(n = 1) -> new_date + # + # Equivalent to #>> with argument +n+. + def next_month(n = 1) + self >> n + end + + # call-seq: + # prev_month(n = 1) -> new_date + # + # Equivalent to #<< with argument +n+. + def prev_month(n = 1) + self << n + end + + # call-seq: + # sunday? -> true or false + # + # Returns +true+ if +self+ is a Sunday, +false+ otherwise. + def sunday? + m_wday.zero? + end + + # call-seq: + # monday? -> true or false + # + # Returns +true+ if +self+ is a Monday, +false+ otherwise. + def monday? + m_wday == 1 + end + + # call-seq: + # tuesday? -> true or false + # + # Returns +true+ if +self+ is a Tuesday, +false+ otherwise. + def tuesday? + m_wday == 2 + end + + # call-seq: + # wednesday? -> true or false + # + # Returns +true+ if +self+ is a Wednesday, +false+ otherwise. + def wednesday? + m_wday == 3 + end + + # call-seq: + # thursday? -> true or false + # + # Returns +true+ if +self+ is a Thursday, +false+ otherwise. + def thursday? + m_wday == 4 + end + + # call-seq: + # friday? -> true or false + # + # Returns +true+ if +self+ is a Friday, +false+ otherwise. + def friday? + m_wday == 5 + end + + # call-seq: + # saturday? -> true or false + # + # Returns +true+ if +self+ is a Saturday, +false+ otherwise. + def saturday? + m_wday == 6 + end + + # call-seq: + # wday -> integer + # + # Returns the day of week in range (0..6); Sunday is 0: + # + # Date.new(2001, 2, 3).wday # => 6 + def wday + m_wday + end + + # call-seq: + # yday -> integer + # + # Returns the day of the year, in range (1..366): + # + # Date.new(2001, 2, 3).yday # => 34 + def yday + m_yday + end + + # call-seq: + # deconstruct_keys(array_of_names_or_nil) -> hash + # + # Returns a hash of the name/value pairs, to use in pattern matching. + # Possible keys are: :year, :month, :day, + # :wday, :yday. + # + # Possible usages: + # + # d = Date.new(2022, 10, 5) + # + # if d in wday: 3, day: ..7 # uses deconstruct_keys underneath + # puts "first Wednesday of the month" + # end + # #=> prints "first Wednesday of the month" + # + # case d + # in year: ...2022 + # puts "too old" + # in month: ..9 + # puts "quarter 1-3" + # in wday: 1..5, month: + # puts "working day in month #{month}" + # end + # #=> prints "working day in month 10" + # + # Note that deconstruction by pattern can also be combined with class check: + # + # if d in Date(wday: 3, day: ..7) + # puts "first Wednesday of the month" + # end + def deconstruct_keys(keys) + if keys.nil? + return { + year: year, + month: month, + day: day, + yday: yday, + wday: wday + } + end + + raise TypeError, "wrong argument type #{keys.class} (expected Array or nil)" unless keys.is_a?(Array) + + h = {} + keys.each do |key| + case key + when :year then h[:year] = year + when :month then h[:month] = month + when :day then h[:day] = day + when :yday then h[:yday] = yday + when :wday then h[:wday] = wday + when :zone then h[:zone] = zone + end + end + h + end + + # call-seq: + # step(limit, step = 1){|date| ... } -> self + # + # Calls the block with specified dates; + # returns +self+. + # + # - The first +date+ is +self+. + # - Each successive +date+ is date + step, + # where +step+ is the numeric step size in days. + # - The last date is the last one that is before or equal to +limit+, + # which should be a \Date object. + # + # Example: + # + # limit = Date.new(2001, 12, 31) + # Date.new(2001).step(limit){|date| p date.to_s if date.mday == 31 } + # + # Output: + # + # "2001-01-31" + # "2001-03-31" + # "2001-05-31" + # "2001-07-31" + # "2001-08-31" + # "2001-10-31" + # "2001-12-31" + # + # Returns an Enumerator if no block is given. + def step(limit, step = 1) + raise ArgumentError, "step must be numeric" unless step.respond_to?(:<=>) + + return to_enum(:step, limit, step) unless block_given? + + date = self + cmp = step <=> 0 + + raise ArgumentError, "step must be numeric" if cmp.nil? + + case cmp + when -1 + # If step is negative (reverse order) + while (date <=> limit) >= 0 + yield date + date = date + step + end + when 0 + # If step is 0 (infinite loop) + loop do + yield date + end + else + # If step is positive (forward direction) + while (date <=> limit) <= 0 + yield date + date = date + step + end + end + + self + end + + # call-seq: + # upto(max){|date| ... } -> self + # + # Equivalent to #step with arguments +max+ and +1+. + def upto(max) + return to_enum(:upto, max) unless block_given? + + date = self + + while (date <=> max) <= 0 + yield date + date = date + 1 + end + + self + end + + # call-seq: + # downto(min){|date| ... } -> self + # + # Equivalent to #step with arguments +min+ and -1. + def downto(min) + return to_enum(:downto, min) unless block_given? + + date = self + + while (date <=> min) >= 0 + yield date + date = date - 1 + end + + self + end + + # call-seq: + # day_fraction -> rational + # + # Returns the fractional part of the day in range (Rational(0, 1)...Rational(1, 1)): + # + # DateTime.new(2001,2,3,12).day_fraction # => (1/2) + def day_fraction + simple_dat_p? ? 0 : m_fr + end + + # call-seq: + # d.mjd -> integer + # + # Returns the modified Julian day number. This is a whole number, + # which is adjusted by the offset as the local time. + # + # DateTime.new(2001,2,3,4,5,6,'+7').mjd #=> 51943 + # DateTime.new(2001,2,3,4,5,6,'-7').mjd #=> 51943 + def mjd + m_real_local_jd - 2_400_001 + end + + # call-seq: + # cwyear -> integer + # + # Returns commercial-date year for +self+ + # (see Date.commercial): + # + # Date.new(2001, 2, 3).cwyear # => 2001 + # Date.new(2000, 1, 1).cwyear # => 1999 + def cwyear + m_real_cwyear + end + + # call-seq: + # cweek -> integer + # + # Returns commercial-date week index for +self+ + # (see Date.commercial): + # + # Date.new(2001, 2, 3).cweek # => 5 + def cweek + m_cweek + end + + # call-seq: + # cwday -> integer + # + # Returns the commercial-date weekday index for +self+ + # (see Date.commercial); + # 1 is Monday: + # + # Date.new(2001, 2, 3).cwday # => 6 + def cwday + m_cwday + end + + # call-seq: + # to_time -> time + # + # Returns a new Time object with the same value as +self+; + # if +self+ is a Julian date, derives its Gregorian date + # for conversion to the \Time object: + # + # Date.new(2001, 2, 3).to_time # => 2001-02-03 00:00:00 -0600 + # Date.new(2001, 2, 3, Date::JULIAN).to_time # => 2001-02-16 00:00:00 -0600 + def to_time + # Julian calendar converted to Gregorian calendar. + date = m_julian_p? ? gregorian : self + + # Create a Time object using Time.local. + Time.local( + date.send(:m_real_year), + date.send(:m_mon), + date.send(:m_mday) + ) + end + + # call-seq: + # to_date -> self + # + # Returns +self+. + def to_date + self + end + + # call-seq: + # to_datetime -> datetime + # + # Returns a DateTime whose value is the same as +self+. + def to_datetime + # Use internal constructor to bypass validation (reform-gap safety) + nth, ry = self.class.send(:decode_year, year, -1) + rjd, _ = self.class.send(:c_civil_to_jd, ry, month, day, Date::GREGORIAN) + obj = DateTime.send(:new_with_jd_and_time, nth, rjd, 0, 0, 0, Date::GREGORIAN) + obj.send(:set_sg, start) + obj + end + + # call-seq: + # d.ajd -> rational + # + # Returns the astronomical Julian day number. This is a fractional + # number, which is not adjusted by the offset. + # + # DateTime.new(2001,2,3,4,5,6,'+7').ajd #=> (11769328217/4800) + # DateTime.new(2001,2,2,14,5,6,'-7').ajd #=> (11769328217/4800) + def ajd + m_ajd + end + + # call-seq: + # d.amjd -> rational + # + # Returns the astronomical modified Julian day number. This is + # a fractional number, which is not adjusted by the offset. + # + # DateTime.new(2001,2,3,4,5,6,'+7').amjd #=> (249325817/4800) + # DateTime.new(2001,2,2,14,5,6,'-7').amjd #=> (249325817/4800) + def amjd + m_amjd + end + + # :nodoc: + # C: d_lite_initialize_copy + def initialize_copy(other) + unless other.is_a?(Date) + raise TypeError, "initialize_copy should take same class object" + end + @nth = other.instance_variable_get(:@nth) + @jd = other.instance_variable_get(:@jd) + @sg = other.instance_variable_get(:@sg) + @df = other.instance_variable_get(:@df) + @sf = other.instance_variable_get(:@sf) + @of = other.instance_variable_get(:@of) + @year = other.instance_variable_get(:@year) + @month = other.instance_variable_get(:@month) + @day = other.instance_variable_get(:@day) + @has_jd = other.instance_variable_get(:@has_jd) + @has_civil = other.instance_variable_get(:@has_civil) + self + end + + # :nodoc: + def marshal_dump + [ + m_nth, + m_jd, + m_df, + m_sf, + m_of, + @sg + ] + end + + # :nodoc: + # C: d_lite_marshal_load + # Supports 3 historical formats: + # 2 elements (1.4/1.6): [jd_like, sg_or_bool] + # 3 elements (1.8/1.9.2): [ajd, of, sg] + # 6 elements (current): [nth, jd, df, sf, of, sg] + def marshal_load(array) + raise TypeError, "expected an array" unless array.is_a?(Array) + + case array.size + when 2 # Ruby 1.4/1.6 + # C: ajd = f_sub(a[0], half_days_in_day); vof = 0; vsg = a[1] + ajd = array[0] - Rational(1, 2) + vof = 0 + vsg = array[1] + unless vsg.is_a?(Numeric) + vsg = vsg ? -Float::INFINITY : Float::INFINITY + end + nth, jd, df, sf, of_sec, sg = old_to_new(ajd, vof, vsg) + + when 3 # Ruby 1.8 / 1.9.2 + ajd = array[0] + vof = array[1] + vsg = array[2] + nth, jd, df, sf, of_sec, sg = old_to_new(ajd, vof, vsg) + + when 6 # Current format + nth, jd, df, sf, of_sec, sg = array + + else + raise TypeError, "invalid size" + end + + @nth = nth + @jd = jd + @df = (!df || df == 0) ? nil : df + @sf = (!sf || sf == 0) ? nil : sf + @of = (!of_sec || of_sec == 0) ? nil : of_sec + @sg = sg + + @has_jd = true + @has_civil = false + @year = nil + @month = nil + @day = nil + end + + # call-seq: + # asctime -> string + # + # Equivalent to #strftime with argument '%a %b %e %T %Y' + # (or its {shorthand form}[rdoc-ref:language/strftime_formatting.rdoc@Shorthand+Conversion+Specifiers] + # '%c'): + # + # Date.new(2001, 2, 3).asctime # => "Sat Feb 3 00:00:00 2001" + # + # See {asctime}[https://linux.die.net/man/3/asctime]. + # + def asctime + strftime('%a %b %e %H:%M:%S %Y') + end + alias_method :ctime, :asctime + + # call-seq: + # iso8601 -> string + # + # Equivalent to #strftime with argument '%Y-%m-%d' + # (or its {shorthand form}[rdoc-ref:language/strftime_formatting.rdoc@Shorthand+Conversion+Specifiers] + # '%F'); + # + # Date.new(2001, 2, 3).iso8601 # => "2001-02-03" + def iso8601 + strftime('%Y-%m-%d') + end + alias_method :xmlschema, :iso8601 + + # call-seq: + # rfc3339 -> string + # + # Equivalent to #strftime with argument '%FT%T%:z'; + # see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: + # + # Date.new(2001, 2, 3).rfc3339 # => "2001-02-03T00:00:00+00:00" + def rfc3339 + strftime('%Y-%m-%dT%H:%M:%S%:z') + end + + # call-seq: + # rfc2822 -> string + # + # Equivalent to #strftime with argument '%a, %-d %b %Y %T %z'; + # see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: + # + # Date.new(2001, 2, 3).rfc2822 # => "Sat, 3 Feb 2001 00:00:00 +0000" + def rfc2822 + strftime('%a, %-d %b %Y %T %z') + end + alias_method :rfc822, :rfc2822 + + # call-seq: + # httpdate -> string + # + # Equivalent to #strftime with argument '%a, %d %b %Y %T GMT'; + # see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: + # + # Date.new(2001, 2, 3).httpdate # => "Sat, 03 Feb 2001 00:00:00 GMT" + # + def httpdate + # For Date objects, offset is always 0, so we can directly call strftime + strftime('%a, %d %b %Y %T GMT') + end + + # call-seq: + # jisx0301 -> string + # + # Returns a string representation of the date in +self+ + # in JIS X 0301 format. + # + # Date.new(2001, 2, 3).jisx0301 # => "H13.02.03" + # + def jisx0301 + jd = m_real_local_jd + y = m_real_year + + fmt = jisx0301_date_format(jd, y) + strftime(fmt) + end + + def to_s + s = sprintf("%04d-%02d-%02d", year, month, day) + s.force_encoding(Encoding::US_ASCII) + end + + # call-seq: + # inspect -> string + # + # Returns a string representation of +self+: + # + # Date.new(2001, 2, 3).inspect + # # => "#" + def inspect + s = if simple_dat_p? + inspect_raw + else + # In the case of complex, time information is also displayed. + strftime("%Y-%m-%d %H:%M:%S") + end + s.force_encoding(Encoding::US_ASCII) if s.ascii_only? + s + end + + # override + def freeze + # Force lazy computation before freezing so Ractor-shared objects work. + if simple_dat_p? + get_s_jd + get_s_civil + canonicalize_s_jd + else + get_c_jd + get_c_civil + get_c_df + get_c_time + canonicalize_c_jd + end + super + end + + private + + def inspect_raw + # If @sg is infinity + if @sg.infinite? + if @sg < 0 + return "#" + else + return "#" + end + end + + date_str = strftime("%Y-%m-%d") + jd_val = @jd || 0 + sg_val = @sg.infinite? ? (@sg < 0 ? "Inf" : "-Inf") : @sg.to_i + + "#" + end + + def valid_civil?(y, m, d) + return false if m < 1 || m > 12 + + last = last_day_of_month(y, m) + d >= 1 && d <= last + end + + def last_day_of_month(y, m) + last_day_of_month_gregorian(y, m) + end + + def civil_to_jd(y, m, d, sg) + self.class.send(:gregorian_civil_to_jd, y, m, d) + end + + def jd_to_civil(jd, sg) + decode_jd(jd) + self.class.send(:c_jd_to_civil, jd, sg) + end + + def extract_fraction(value) + self.class.send(:extract_fraction, value) + end + + def decode_year(year, style) + self.class.send(:decode_year, year, style) + end + + def valid_gregorian?(y, m, d) + return false if m < 1 || m > 12 + + # Handling negative months and days + m = m + 13 if m < 0 + return false if m < 1 || m > 12 + + last_day = last_day_of_month_gregorian(y, m) + d = last_day + d + 1 if d < 0 + + d >= 1 && d <= last_day + end + + def add_with_fraction(n) + int_part = n.floor + frac_part = n - int_part + + result = add_days(int_part) + + result = result.send(:add_fraction, frac_part) if frac_part.nonzero? + + result + end + + def add_days(days) + new_jd = @jd + days + new_nth = @nth + + while new_jd < 0 + new_nth -= 1 + new_jd += CM_PERIOD + end + + while new_jd >= CM_PERIOD + new_nth += 1 + new_jd -= CM_PERIOD + end + + obj = self.class.allocate + obj.instance_variable_set(:@nth, new_nth) + obj.instance_variable_set(:@jd, new_jd) + obj.instance_variable_set(:@sg, @sg) + obj.instance_variable_set(:@flags, HAVE_JD) + obj.instance_variable_set(:@year, nil) + obj.instance_variable_set(:@month, nil) + obj.instance_variable_set(:@day, nil) + + obj + end + + def add_fraction(frac) + # In the C implementation, Date.jd(2451944.5) becomes 2451945, + # so if there is a decimal point, it will be rounded up by one day. + if frac > 0 + add_days(1) + else + self + end + end + + def last_day_of_month_gregorian(y, m) + self.class.send(:last_day_of_month_gregorian, y, m) + end + + def last_day_of_month_julian(y, m) + self.class.send(:last_day_of_month_julian, y, m) + end + + def valid_civil_date?(year, month, day, sg) + self.class.send(:valid_civil_date?, year, month, day, sg) + end + + def canonicalize_jd(nth, jd) + if jd < 0 + nth = nth - 1 + jd += CM_PERIOD + end + if jd >= CM_PERIOD + nth = nth + 1 + jd -= CM_PERIOD + end + + [nth, jd] + end + + # If any of @df, @sf, or @of is not nil, it is considered complex. + def simple_dat_p? + @df.nil? && @sf.nil? && @of.nil? + end + + def complex_dat_p? + !simple_dat_p? + end + + def m_gregorian_p? + !m_julian_p? + end + + def m_julian_p? + # Divide the processing into simple and complex. + if simple_dat_p? + get_s_jd + jd = @jd + sg = s_virtual_sg + else + get_c_jd + jd = @jd + sg = c_virtual_sg + end + + return sg == JULIAN if sg.infinite? + + jd < sg + end + + def m_year + simple_dat_p? ? get_s_civil : get_c_civil + + @year + end + + def m_virtual_sg + simple_dat_p? ? s_virtual_sg : c_virtual_sg + end + + def get_s_jd + # For simple data, if JD has not yet been calculated. + return if @has_jd + + return unless simple_dat_p? + + return unless @has_civil + + # Calculate JD from civil. + jd, _ = self.class.send(:c_civil_to_jd, @year, @month, @day, s_virtual_sg) + @jd = jd + @has_jd = true + end + + def get_s_civil + # For simple data, if civil has not yet been calculated. + return if @has_civil + + # If not simple or there is no JD, do nothing. + return unless simple_dat_p? + return unless @has_jd + + # Calculate civil from JD. + y, m, d = self.class.send(:c_jd_to_civil, @jd, s_virtual_sg) + @year = y + @month = m + @day = d + @has_civil = true + end + + def get_c_jd + # For complex data, if JD has not yet been calculated. + return if @has_jd + + # Make sure you have civil data. + raise "No civil data" unless @has_civil + + # Calculate JD from civil. + jd, _ = self.class.send(:c_civil_to_jd, @year, @month, @day, c_virtual_sg) + + # Consider time data. + get_c_time + + # Convert from local to UTC. + @jd = jd_local_to_utc(jd, time_to_df(@hour || 0, @min || 0, @sec || 0), @of || 0) + @has_jd = true + end + + def get_c_civil + # For complex data, if civil has not yet been calculated. + return if @has_civil + + # Make sure you have a JD. + raise "No JD data" unless @has_jd + + get_c_df + + # Convert UTC to local. + jd = jd_utc_to_local(@jd, @df || 0, @of || 0) + + # Calculate civil from JD. + y, m, d = self.class.send(:c_jd_to_civil, jd, c_virtual_sg) + @year = y + @month = m + @day = d + @has_civil = true + end + + def get_c_df + # If df (day fraction) has not yet been calculated. + return if @df + + # Check that time data is available. + raise "No time data" if @hour.nil? && @min.nil? && @sec.nil? + + # Convert time to df + @df = df_local_to_utc(time_to_df(@hour, @min, @sec), @of || 0) + end + + def get_c_time + # If the time data has not yet been calculated. + return unless @hour.nil? + + # Make sure df exists. + raise "No df data" if @df.nil? + + # Convert df to time. + r = df_utc_to_local(@df, @of || 0) + + @hour, @min, @sec = df_to_time(r) + end + + # For SimpleDateData (effectively a common implementation) + def s_virtual_sg + return @sg if @sg.infinite? + return @sg if self.class.send(:f_zero_p?, @nth) + + @nth < 0 ? JULIAN : GREGORIAN + end + + # For ComplexDateData (effectively a common implementation) + def c_virtual_sg + return @sg if @sg.infinite? + return @sg if self.class.send(:f_zero_p?, @nth) + + @nth < 0 ? JULIAN : GREGORIAN + end + + def jd_local_to_utc(jd, df, of) + df -= of + if df < 0 + jd -= 1 + elsif df >= DAY_IN_SECONDS + jd += 1 + end + + jd + end + + def jd_utc_to_local(jd, df, of) + df += of + if df < 0 + jd -= 1 + elsif df >= DAY_IN_SECONDS + jd += 1 + end + + jd + end + + def df_local_to_utc(df, of) + df -= of + if df < 0 + df += DAY_IN_SECONDS + elsif df >= DAY_IN_SECONDS + df -= DAY_IN_SECONDS + end + + df + end + + def df_utc_to_local(df, of) + df += of + if df < 0 + df += DAY_IN_SECONDS + elsif df >= DAY_IN_SECONDS + df -= DAY_IN_SECONDS + end + + df + end + + def time_to_df(h, min, s) + h * HOUR_IN_SECONDS + min * MINUTE_IN_SECONDS + s + end + + def df_to_time(df) + h = df / HOUR_IN_SECONDS + df %= HOUR_IN_SECONDS + min = df / MINUTE_IN_SECONDS + s = df % MINUTE_IN_SECONDS + + [h, min, s] + end + + def minus_dd(other) + n = m_nth - other.send(:m_nth) + d = m_jd - other.send(:m_jd) + df = m_df - other.send(:m_df) + sf = m_sf - other.send(:m_sf) + + n, d = canonicalize_jd(n, d) + + # Canonicalize df + if df < 0 + d -= 1 + df += DAY_IN_SECONDS + elsif df >= DAY_IN_SECONDS + d += 1 + df -= DAY_IN_SECONDS + end + + # Canonicalize sf + if sf < 0 + df -= 1 + sf += SECOND_IN_NANOSECONDS + elsif sf >= SECOND_IN_NANOSECONDS + df += 1 + sf -= SECOND_IN_NANOSECONDS + end + + r = n.zero? ? 0 : n * CM_PERIOD + r = r + Rational(d, 1) if d.nonzero? + r = r + isec_to_day(df) if df.nonzero? + r = r + ns_to_day(sf) if sf.nonzero? + + r.is_a?(Rational) ? r : Rational(r, 1) + end + + def m_jd + simple_dat_p? ? get_s_jd : get_c_jd + + @jd + end + + def m_df + if simple_dat_p? + 0 + else + get_c_df + @df || 0 + end + end + + def m_sf + simple_dat_p? ? 0 : @sf || 0 + end + + def m_of + if simple_dat_p? + 0 + else + get_c_jd + @of || 0 + end + end + + def m_real_year + nth = @nth + year = m_year + + return year if self.class.send(:f_zero_p?, nth) + + encode_year(nth, year, gregorian? ? -1 : 1) + end + + def m_mon + simple_dat_p? ? get_s_civil : get_c_civil + + @month + end + + def m_mday + simple_dat_p? ? get_s_civil : get_c_civil + + @day + end + + def m_sg + get_c_jd unless simple_dat_p? + + @sg + end + + def encode_year(nth, y, style) + period = (style < 0) ? CM_PERIOD_GCY : CM_PERIOD_JCY + + self.class.send(:f_zero_p?, nth) ? y : period * nth + y + end + + def m_real_local_jd + nth = m_nth + jd = m_local_jd + + self.class.send(:encode_jd, nth, jd) + end + + def m_local_jd + if simple_dat_p? + get_s_jd + @jd + else + get_c_jd + get_c_df + local_jd + end + end + + def local_jd + jd = @jd + df = @df || 0 + of = @of || 0 + + df += of + if df < 0 + jd -= 1 + elsif df >= DAY_IN_SECONDS + jd += 1 + end + + jd + end + + def m_nth + # For complex, get civil data and then return nth. + get_c_civil unless simple_dat_p? + + @nth + end + + def equal_gen(other) + if other.is_a?(Numeric) + m_real_local_jd == other + elsif other.is_a?(Date) + m_real_local_jd == other.send(:m_real_local_jd) + else + begin + coerced = other.coerce(self) + coerced[0] == coerced[1] + rescue + false + end + end + end + + def m_canonicalize_jd + if simple_dat_p? + get_s_jd + canonicalize_s_jd + else + get_c_jd + canonicalize_c_jd + end + end + + # Simple + def canonicalize_s_jd + return if frozen? + + j = @jd + + @nth, @jd = canonicalize_jd(@nth, @jd) + + # Invalidate civil data if JD changes. + @has_civil = false if @jd != j + end + + # Complex + def canonicalize_c_jd + return if frozen? + + j = @jd + + @nth, @jd = canonicalize_jd(@nth, @jd) + + # Invalidate civil data if JD changes. + @has_civil = false if @jd != j + end + + def f_jd(other) + # Get JD from another Date object. + other.send(:m_real_local_jd) + end + + def dup_obj_with_new_start(sg) + dup = dup_obj + dup.send(:set_sg, sg) + + dup + end + + def dup_obj + if simple_dat_p? + # Simple data replication + new_obj = self.class.send(:d_lite_s_alloc_simple) + + new_obj.instance_variable_set(:@nth, canon(@nth)) + new_obj.instance_variable_set(:@jd, @jd) + new_obj.instance_variable_set(:@sg, @sg) + new_obj.instance_variable_set(:@year, @year) + new_obj.instance_variable_set(:@month, @month) + new_obj.instance_variable_set(:@day, @day) + new_obj.instance_variable_set(:@has_jd, @has_jd) + new_obj.instance_variable_set(:@has_civil, @has_civil) + new_obj.instance_variable_set(:@df, nil) + new_obj.instance_variable_set(:@sf, nil) + new_obj.instance_variable_set(:@of, nil) + + new_obj + else + # Complex data replication + new_obj = self.class.send(:d_lite_s_alloc_complex) + + new_obj.instance_variable_set(:@nth, canon(@nth)) + new_obj.instance_variable_set(:@jd, @jd) + new_obj.instance_variable_set(:@sg, @sg) + new_obj.instance_variable_set(:@year, @year) + new_obj.instance_variable_set(:@month, @month) + new_obj.instance_variable_set(:@day, @day) + new_obj.instance_variable_set(:@hour, @hour) + new_obj.instance_variable_set(:@min, @min) + new_obj.instance_variable_set(:@sec, @sec) + new_obj.instance_variable_set(:@df, @df) + new_obj.instance_variable_set(:@sf, canon(@sf)) + new_obj.instance_variable_set(:@of, @of) + new_obj.instance_variable_set(:@has_jd, @has_jd) + new_obj.instance_variable_set(:@has_civil, @has_civil) + + new_obj + end + end + + def set_sg(sg) + if simple_dat_p? + get_s_jd if @has_jd || @has_civil + else + get_c_jd + get_c_df + end + + clear_civil + + @sg = sg + end + + def clear_civil + @has_civil = false + @year = nil + @month = nil + @day = nil + end + + # If the argument is Rational and the denominator is 1, return the numerator. + def canon(x) + x.is_a?(Rational) && x.denominator == 1 ? x.numerator : x + end + + def val2sg(vsg) + # Convert to Number. + sg = vsg.to_f + + # Check for a valid start. + unless c_valid_start_p?(sg) + warn "invalid start is ignored" + sg = DEFAULT_SG + end + + sg + end + + def c_valid_start_p?(sg) + # Invalid for NaN. + return false if sg.respond_to?(:nan?) && sg.nan? + + # Valid for Infinity. + return true if sg.respond_to?(:infinite?) && sg.infinite? + + # If it is a finite value, check if it is within the range + # from REFORM_BEGIN_JD to REFORM_END_JD + return false if sg < REFORM_BEGIN_JD || sg > REFORM_END_JD + + true + end + + def m_wday + c_jd_to_wday(m_local_jd) + end + + def c_jd_to_wday(jd) + (jd + 1) % 7 + end + + def m_yday + jd = m_local_jd + sg = m_virtual_sg + + # proleptic gregorian or if more than 366 days have passed since the calendar change + return c_gregorian_to_yday(m_year, m_mon, m_mday) if m_proleptic_gregorian_p? || (jd - sg) > 366 + + # proleptic Julian + return c_julian_to_yday(m_year, m_mon, m_mday) if m_proleptic_julian_p? + + # Otherwise, convert from JD to ordinal. + _, rd = self.class.send(:c_jd_to_ordinal, jd, sg) + + rd + end + + def m_proleptic_gregorian_p? + sg = @sg + + sg.infinite? && sg < 0 + end + + def m_proleptic_julian_p? + sg = @sg + + sg.infinite? && sg > 0 + end + + def c_gregorian_to_yday(year, month, day) + leap = self.class.send(:c_gregorian_leap_p?, year) + + YEARTAB[leap ? 1 : 0][month] + day + end + + def c_julian_to_yday(year, month, day) + leap = self.class.send(:c_julian_leap_p?, year) + + YEARTAB[leap ? 1 : 0][month] + day + end + + def d_trunc_with_frac(value) + if value.is_a?(Integer) + [value, 0] + elsif value.is_a?(Float) + trunc = value.truncate + frac = value - trunc + + [trunc, frac] + elsif value.is_a?(Rational) + trunc = value.truncate + frac = value - trunc + + [trunc, frac] + else + [value.to_i, 0] + end + end + + def m_real_jd + # C: m_real_jd uses m_jd (raw/UTC JD), NOT m_local_jd + nth = m_nth + if simple_dat_p? + get_s_jd + else + get_c_jd + end + self.class.send(:encode_jd, nth, @jd) + end + + def m_fr + if simple_dat_p? + 0 + else + df = m_local_df + sf = m_sf + + fr = isec_to_day(df) + fr = fr + ns_to_day(sf) if sf.nonzero? + + fr + end + end + + def m_local_df + if simple_dat_p? + 0 + else + get_c_df + local_df + end + end + + def local_df + df_utc_to_local(@df || 0, @of || 0) + end + + def isec_to_day(s) + sec_to_day(s) + end + + def sec_to_day(s) + s.is_a?(Integer) ? Rational(s, DAY_IN_SECONDS) : s.quo(DAY_IN_SECONDS) + end + + def ns_to_day(n) + if n.is_a?(Integer) + Rational(n, DAY_IN_SECONDS * SECOND_IN_NANOSECONDS) + else + n.quo(DAY_IN_SECONDS * SECOND_IN_NANOSECONDS) + end + end + + def m_real_cwyear + nth = m_nth + year = m_cwyear + + nth.zero? ? year : encode_year(nth, year, m_gregorian_p? ? -1 : 1) + end + + def m_cwyear + jd = m_local_jd + sg = m_virtual_sg + + ry, _, _ = self.class.send(:c_jd_to_commercial, jd, sg) + + ry + end + + def m_cweek + jd = m_local_jd + sg = m_virtual_sg + + _, rw, _ = self.class.send(:c_jd_to_commercial, jd, sg) + + rw + end + + def m_cwday + w = m_wday + # ISO 8601 places Sunday at 7. + w.zero? ? 7 : w + end + + def m_ajd + if simple_dat_p? + # For simple date: + r = m_real_jd + + # Optimization: Integer operations within Fixnum range + if r.is_a?(Integer) && r <= (2**62 - 1) / 2 && r >= (-(2**62) + 1) / 2 + ir = r * 2 - 1 + return Rational(ir, 2) + else + return Rational(r * 2 - 1, 2) + end + end + + # For complex date: + r = m_real_jd + df = m_df + + # Subtract half a day (12 hours) from df. + df -= HALF_DAYS_IN_SECONDS + + # If df is not zero, add. + r = r + isec_to_day(df) if df != 0 + + # If sf is not zero, add. + sf = m_sf + r = r + ns_to_day(sf) if sf != 0 + + r + end + + def m_amjd + r = m_real_jd + + # Optimization: Integer operations within Fixnum range + if r.is_a?(Integer) && r >= (-(2**62) + 2400001) + ir = r - 2400001 + r = Rational(ir, 1) + else + r = Rational(m_real_jd - 2400001, 1) + end + + # For simple date, stop here. + return r if simple_dat_p? + + # For complex date, add df and sf. + df = m_df + r = r + isec_to_day(df) if df != 0 + + sf = m_sf + r = r + ns_to_day(sf) if sf != 0 + + r + end + + def m_wnumx(f) + _, rw, _ = c_jd_to_weeknum(m_local_jd, f, m_virtual_sg) + + rw + end + + def c_jd_to_weeknum(jd, f, sg) + ry, _, _ = self.class.send(:c_jd_to_civil, jd, sg) + rjd, _ = self.class.send(:c_find_fdoy, ry, sg) + + rjd += 6 + + mod_val = euclidean_mod((rjd - f) + 1, 7) + j = jd - (rjd - mod_val) + 7 + + rw = euclidean_div(j, 7) + rd = euclidean_mod(j, 7) + + [ry, rw, rd] + end + + # Euclidean division (equivalent to the DIV macro in C) + def euclidean_div(a, b) + q = a / b + r = a % b + # In Ruby, a remainder of a negative number is negative, so adjust it accordingly. + if r < 0 + if b > 0 + q -= 1 + else + q += 1 + end + end + + q + end + + # Euclidean modulo (equivalent to the MOD macro in C) + def euclidean_mod(a, b) + r = a % b + # In Ruby, a remainder of a negative number is negative, so adjust it accordingly. + if r < 0 + if b > 0 + r += b + else + r -= b + end + end + + r + end + + def jisx0301_date_format(jd, year) + # If jd is not a Fixnum (Integer in Ruby), use ISO format + return '%Y-%m-%d' unless jd.is_a?(Integer) + + # Determine the era based on Julian Day Number + if jd < 2405160 + # Before Meiji era (before 1868-01-25) + '%Y-%m-%d' + elsif jd < 2419614 + # Meiji era (M) 1868-01-25 to 1912-07-29 + era_char = 'M' + era_start = 1867 + format_era(era_char, year, era_start) + elsif jd < 2424875 + # Taisho era (T) 1912-07-30 to 1926-12-24 + era_char = 'T' + era_start = 1911 + format_era(era_char, year, era_start) + elsif jd < 2447535 + # Showa era (S) 1926-12-25 to 1989-01-07 + era_char = 'S' + era_start = 1925 + format_era(era_char, year, era_start) + elsif jd < 2458605 + # Heisei era (H) 1989-01-08 to 2019-04-30 + era_char = 'H' + era_start = 1988 + format_era(era_char, year, era_start) + else + # Reiwa era (R) 2019-05-01 onwards + era_char = 'R' + era_start = 2018 + format_era(era_char, year, era_start) + end + end + + def format_era(era_char, year, era_start) + era_year = year - era_start + "#{era_char}%02d.%%m.%%d" % era_year + end + + def zone + of = @parsed_offset || 0 + s = of < 0 ? '-' : '+' + a = of.abs + h = a / HOUR_IN_SECONDS + m = a % HOUR_IN_SECONDS / MINUTE_IN_SECONDS + "%c%02d:%02d" % [s, h, m] + end + + # C: old_to_new — converts old ajd/of/sg format to new nth/jd/df/sf/of/sg + def old_to_new(ajd, of, sg) + # C: decode_day(ajd + half_days_in_day, &jd, &df, &sf) + d = ajd + Rational(1, 2) + + # div_day: jd = floor(d), f = d mod 1 + jd_full = d.floor + f = d - jd_full + + # div_df: df = floor(f * DAY_IN_SECONDS), remainder + df_rational = f * 86400 + df = df_rational.floor + sf_frac = df_rational - df + + # sec_to_ns: sf = round(sf_frac * SECOND_IN_NANOSECONDS) + sf = (sf_frac * 1_000_000_000).round + + # C: day_to_sec(of) then round + of_sec = (of * 86400).round.to_i + + # C: decode_jd(jd, &nth, &rjd) + nth = jd_full.div(CM_PERIOD) + rjd = (jd_full % CM_PERIOD).to_i + + # Validations (C: old_to_new) + raise Error, "invalid day fraction" if df < 0 || df >= 86400 + if of_sec < -86400 || of_sec > 86400 + of_sec = 0 + warn "invalid offset is ignored" + end + + # Convert Infinity to Float (C: NUM2DBL(sg)) + if sg.is_a?(Infinity) + sg = case sg.send(:d) + when -1 then -Float::INFINITY + when 1 then Float::INFINITY + else DEFAULT_SG + end + end + + [nth, rjd, df, sf, of_sec, sg] + end +end diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb new file mode 100644 index 00000000..844447d6 --- /dev/null +++ b/lib/date/datetime.rb @@ -0,0 +1,826 @@ +# frozen_string_literal: true + +# Implementation of DateTime from ruby/date/ext/date/date_core.c +# DateTime is a subclass of Date that includes time-of-day and timezone. +class DateTime < Date + # call-seq: + # DateTime.new(year=-4712, month=1, day=1, hour=0, minute=0, second=0, offset=0, start=Date::ITALY) -> datetime + # + # Creates a new DateTime object. + def initialize(year = -4712, month = 1, day = 1, hour = 0, minute = 0, second = 0, offset = 0, start = ITALY) + y = year + m = month + d = day + h = hour + min = minute + s = second + fr2 = 0 + + # argument type checking + raise TypeError, "invalid year (not numeric)" unless y.is_a?(Numeric) + raise TypeError, "invalid month (not numeric)" unless m.is_a?(Numeric) + raise TypeError, "invalid day (not numeric)" unless d.is_a?(Numeric) + raise TypeError, "invalid hour (not numeric)" unless h.is_a?(Numeric) + raise TypeError, "invalid minute (not numeric)" unless min.is_a?(Numeric) + raise TypeError, "invalid second (not numeric)" unless s.is_a?(Numeric) + + # Handle fractional day (C: d_trunc) + d_trunc, fr = d_trunc_with_frac(d) + d = d_trunc + fr2 = fr if fr.nonzero? + + # Handle fractional hour (C: h_trunc via num2int_with_frac) + h_int = h.to_i + h_frac = h - h_int + if h_frac.nonzero? + fr2 = fr2 + Rational(h_frac) / 24 + h = h_int + end + + # Handle fractional minute (C: min_trunc) + min_int = min.to_i + min_frac = min - min_int + if min_frac.nonzero? + fr2 = fr2 + Rational(min_frac) / 1440 + min = min_int + end + + # Handle fractional second (C: s_trunc) + # C converts sub-second fraction to day fraction: fr2 = frac / DAY_IN_SECONDS + s_int = s.to_i + s_frac = s - s_int + if s_frac.nonzero? + fr2 = fr2 + Rational(s_frac) / DAY_IN_SECONDS + s = s_int + end + + # Convert offset to integer seconds (C: val2off → offset_to_sec) + rof = offset_to_sec(offset) + + sg = self.class.send(:valid_sg, start) + style = self.class.send(:guess_style, y, sg) + + # Validate time (C: c_valid_time_p) + h, min, s = validate_time(h, min, s) + + # Handle hour 24 (C: canon24oc) + if h == 24 + h = 0 + fr2 = fr2 + 1 + end + + if style < 0 + # gregorian calendar only + result = self.class.send(:valid_gregorian_p, y, m, d) + raise Error, "invalid date" unless result + + nth, ry = self.class.send(:decode_year, y, -1) + rm = result[:rm] + rd = result[:rd] + + rjd, _ = self.class.send(:c_civil_to_jd, ry, rm, rd, GREGORIAN) + rjd2 = jd_local_to_utc(rjd, time_to_df(h, min, s), rof) + + @nth = canon(nth) + @jd = rjd2 + @sg = sg + @year = ry + @month = rm + @day = rd + @has_jd = true + @has_civil = true + @hour = h + @min = min + @sec = s + @df = df_local_to_utc(time_to_df(h, min, s), rof) + @sf = 0 + @of = rof + else + # full validation + result = self.class.send(:valid_civil_p, y, m, d, sg) + raise Error, "invalid date" unless result + + nth = result[:nth] + ry = result[:ry] + rm = result[:rm] + rd = result[:rd] + rjd = result[:rjd] + + rjd2 = jd_local_to_utc(rjd, time_to_df(h, min, s), rof) + + @nth = canon(nth) + @jd = rjd2 + @sg = sg + @year = ry + @month = rm + @day = rd + @has_jd = true + @has_civil = true + @hour = h + @min = min + @sec = s + @df = df_local_to_utc(time_to_df(h, min, s), rof) + @sf = 0 + @of = rof + end + + # Add accumulated fractional parts (C: add_frac) + if fr2.nonzero? + new_date = self + fr2 + @nth = new_date.instance_variable_get(:@nth) + @jd = new_date.instance_variable_get(:@jd) + @sg = new_date.instance_variable_get(:@sg) + @year = new_date.instance_variable_get(:@year) + @month = new_date.instance_variable_get(:@month) + @day = new_date.instance_variable_get(:@day) + @has_jd = new_date.instance_variable_get(:@has_jd) + @has_civil = new_date.instance_variable_get(:@has_civil) + @hour = new_date.instance_variable_get(:@hour) + @min = new_date.instance_variable_get(:@min) + @sec = new_date.instance_variable_get(:@sec) + @df = new_date.instance_variable_get(:@df) || @df + @sf = new_date.instance_variable_get(:@sf) || @sf + @of = new_date.instance_variable_get(:@of) || @of + end + + self + end + + # --- DateTime accessors (C: d_lite_hour etc.) --- + + # call-seq: + # hour -> integer + # + # Returns the hour in range (0..23). + def hour + if simple_dat_p? + 0 + else + get_c_time + @hour || 0 + end + end + + # call-seq: + # min -> integer + # + # Returns the minute in range (0..59). + def min + if simple_dat_p? + 0 + else + get_c_time + @min || 0 + end + end + alias minute min + + # call-seq: + # sec -> integer + # + # Returns the second in range (0..59). + def sec + if simple_dat_p? + 0 + else + get_c_time + @sec || 0 + end + end + alias second sec + + # call-seq: + # sec_fraction -> rational + # + # Returns the fractional part of the second: + # + # DateTime.new(2001, 2, 3, 4, 5, 6.5).sec_fraction # => (1/2) + # + # C: m_sf_in_sec = ns_to_sec(m_sf) + def sec_fraction + ns = m_sf + ns.zero? ? Rational(0) : Rational(ns, SECOND_IN_NANOSECONDS) + end + alias second_fraction sec_fraction + + # call-seq: + # offset -> rational + # + # Returns the offset as a fraction of day: + # + # DateTime.parse('04pm+0730').offset # => (5/16) + # + # C: m_of_in_day = isec_to_day(m_of) + def offset + of = m_of + of.zero? ? Rational(0) : Rational(of, DAY_IN_SECONDS) + end + + # call-seq: + # zone -> string + # + # Returns the timezone as a string: + # + # DateTime.parse('04pm+0730').zone # => "+07:30" + # + # C: m_zone → of2str(m_of) + def zone + if simple_dat_p? + "+00:00".encode(Encoding::US_ASCII) + else + of = m_of + s = of < 0 ? '-' : '+' + a = of < 0 ? -of : of + h = a / HOUR_IN_SECONDS + m = a % HOUR_IN_SECONDS / MINUTE_IN_SECONDS + ("%c%02d:%02d" % [s, h, m]).encode(Encoding::US_ASCII) + end + end + + STRFTIME_DATETIME_DEFAULT_FMT = '%FT%T%:z'.encode(Encoding::US_ASCII) + private_constant :STRFTIME_DATETIME_DEFAULT_FMT + + # Override Date#strftime with DateTime default format + def strftime(format = STRFTIME_DATETIME_DEFAULT_FMT) + super(format) + end + + # Override Date#jisx0301 for DateTime (includes time) + def jisx0301(n = 0) + n = n.to_i + if n == 0 + jd_val = send(:m_real_local_jd) + y = send(:m_real_year) + fmt = jisx0301_date_format(jd_val, y) + 'T%T%:z' + strftime(fmt) + else + s = jisx0301(0) + # insert fractional seconds before timezone + tz = s[-6..] # "+00:00" + base = s[0...-6] + frac = sec_fraction + if frac != 0 + f = format("%.#{n}f", frac.to_f)[1..] + base += f + else + base += '.' + '0' * n + end + base + tz + end + end + + # DateTime instance method - overrides Date#iso8601 + def iso8601(n = 0) + n = n.to_i + if n == 0 + strftime('%FT%T%:z') + else + s = strftime('%FT%T') + frac = sec_fraction + if frac != 0 + f = format("%.#{n}f", frac.to_f)[1..] + s += f + else + s += '.' + '0' * n + end + s + strftime('%:z') + end + end + alias_method :xmlschema, :iso8601 + alias_method :rfc3339, :iso8601 + + # call-seq: + # deconstruct_keys(array_of_names_or_nil) -> hash + # + # Returns name/value pairs for pattern matching. + # Includes Date keys (:year, :month, :day, :wday, :yday) + # plus DateTime keys (:hour, :min, :sec, :sec_fraction, :zone). + # + # C: dt_lite_deconstruct_keys (is_datetime=true) + def deconstruct_keys(keys) + if keys.nil? + return { + year: year, + month: month, + day: day, + yday: yday, + wday: wday, + hour: hour, + min: min, + sec: sec, + sec_fraction: sec_fraction, + zone: zone + } + end + + raise TypeError, "wrong argument type #{keys.class} (expected Array or nil)" unless keys.is_a?(Array) + + h = {} + keys.each do |key| + case key + when :year then h[:year] = year + when :month then h[:month] = month + when :day then h[:day] = day + when :yday then h[:yday] = yday + when :wday then h[:wday] = wday + when :hour then h[:hour] = hour + when :min then h[:min] = min + when :sec then h[:sec] = sec + when :sec_fraction then h[:sec_fraction] = sec_fraction + when :zone then h[:zone] = zone + end + end + h + end + + # call-seq: + # to_s -> string + # + # Returns a string in ISO 8601 DateTime format: + # + # DateTime.new(2001, 2, 3, 4, 5, 6, '+7').to_s + # # => "2001-02-03T04:05:06+07:00" + def to_s + sprintf("%04d-%02d-%02dT%02d:%02d:%02d%s".encode(Encoding::US_ASCII), year, month, day, hour, min, sec, zone) + end + + # call-seq: + # new_offset(offset = 0) -> datetime + # + # Returns a new DateTime object with the same date and time, + # but with the given +offset+. + # + # C: d_lite_new_offset + def new_offset(of = 0) + if of.is_a?(String) + of = Rational(offset_to_sec(of), DAY_IN_SECONDS) + elsif of.is_a?(Integer) && of == 0 + of = Rational(0) + end + raise TypeError, "invalid offset" unless of.is_a?(Rational) || of.is_a?(Integer) || of.is_a?(Float) + of = Rational(of) unless of.is_a?(Rational) + self.class.new(year, month, day, hour, min, sec + sec_fraction, of, start) + end + + # call-seq: + # to_date -> date + # + # Returns a Date for this DateTime (time information is discarded). + # C: dt_lite_to_date → copy civil, reset time + def to_date + nth, ry = self.class.send(:decode_year, year, -1) + Date.send(:d_simple_new_internal, + nth, 0, + @sg, + ry, month, day, + 0x04) # HAVE_CIVIL + end + + # call-seq: + # to_datetime -> self + # + # Returns self. + def to_datetime + self + end + + # call-seq: + # to_time -> time + # + # Returns a Time for this DateTime. + # C: dt_lite_to_time + def to_time + # C: dt_lite_to_time — converts Julian dates to Gregorian for Time compatibility + d = julian? ? gregorian : self + Time.new(d.year, d.month, d.day, d.hour, d.min, d.sec + d.sec_fraction, d.send(:m_of)) + end + + class << self + # Same as DateTime.new + alias_method :civil, :new + + undef_method :today + + # call-seq: + # DateTime.jd(jd=0, hour=0, minute=0, second=0, offset=0, start=Date::ITALY) -> datetime + # + # Creates a new DateTime from a Julian Day Number. + # C: dt_lite_s_jd + def jd(jd = 0, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) + # Validate jd + raise TypeError, "invalid jd (not numeric)" unless jd.is_a?(Numeric) + raise TypeError, "invalid hour (not numeric)" unless hour.is_a?(Numeric) + raise TypeError, "invalid minute (not numeric)" unless minute.is_a?(Numeric) + raise TypeError, "invalid second (not numeric)" unless second.is_a?(Numeric) + + j, fr = value_trunc(jd) + nth, rjd = decode_jd(j) + + sg = valid_sg(start) + + # Validate time + h = hour.to_i + h_frac = hour - h + min_i = minute.to_i + min_frac = minute - min_i + s_i = second.to_i + s_frac = second - s_i + + fr2 = fr + fr2 = fr2 + Rational(h_frac) / 24 if h_frac.nonzero? + fr2 = fr2 + Rational(min_frac) / 1440 if min_frac.nonzero? + fr2 = fr2 + Rational(s_frac) / 86400 if s_frac.nonzero? + + rof = _offset_to_sec(offset) + + h += 24 if h < 0 + min_i += 60 if min_i < 0 + s_i += 60 if s_i < 0 + unless (0..24).cover?(h) && (0..59).cover?(min_i) && (0..59).cover?(s_i) && + !(h == 24 && (min_i > 0 || s_i > 0)) + raise Date::Error, "invalid date" + end + if h == 24 + h = 0 + fr2 = fr2 + 1 + end + + df = h * 3600 + min_i * 60 + s_i + df_utc = df - rof + jd_utc = rjd + if df_utc < 0 + jd_utc -= 1 + df_utc += 86400 + elsif df_utc >= 86400 + jd_utc += 1 + df_utc -= 86400 + end + + obj = new_with_jd_and_time(nth, jd_utc, df_utc, 0, rof, sg) + + obj = obj + fr2 if fr2.nonzero? + + obj + end + + # call-seq: + # DateTime.ordinal(year=-4712, yday=1, hour=0, minute=0, second=0, offset=0, start=Date::ITALY) -> datetime + # + # Creates a new DateTime from an ordinal date. + # C: dt_lite_s_ordinal + def ordinal(year = -4712, yday = 1, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) + raise TypeError, "invalid year (not numeric)" unless year.is_a?(Numeric) + raise TypeError, "invalid yday (not numeric)" unless yday.is_a?(Numeric) + raise TypeError, "invalid hour (not numeric)" unless hour.is_a?(Numeric) + raise TypeError, "invalid minute (not numeric)" unless minute.is_a?(Numeric) + raise TypeError, "invalid second (not numeric)" unless second.is_a?(Numeric) + + # Truncate fractional yday + yday_int = yday.to_i + yday_frac = yday.is_a?(Integer) ? 0 : yday - yday_int + + result = valid_ordinal_p(year, yday_int, start) + raise Date::Error, "invalid date" unless result + + nth = result[:nth] + rjd = result[:rjd] + sg = valid_sg(start) + + rof = _offset_to_sec(offset) + + h = hour.to_i + h_frac = hour - h + min_i = minute.to_i + min_frac = minute - min_i + s_i = second.to_i + s_frac = second - s_i + + fr2 = yday_frac.nonzero? ? Rational(yday_frac) : 0 + fr2 = fr2 + Rational(h_frac) / 24 if h_frac.nonzero? + fr2 = fr2 + Rational(min_frac) / 1440 if min_frac.nonzero? + fr2 = fr2 + Rational(s_frac) / 86400 if s_frac.nonzero? + + h += 24 if h < 0 + min_i += 60 if min_i < 0 + s_i += 60 if s_i < 0 + unless (0..24).cover?(h) && (0..59).cover?(min_i) && (0..59).cover?(s_i) && + !(h == 24 && (min_i > 0 || s_i > 0)) + raise Date::Error, "invalid date" + end + if h == 24 + h = 0 + fr2 = fr2 + 1 + end + + df = h * 3600 + min_i * 60 + s_i + df_utc = df - rof + jd_utc = rjd + if df_utc < 0 + jd_utc -= 1 + df_utc += 86400 + elsif df_utc >= 86400 + jd_utc += 1 + df_utc -= 86400 + end + + obj = new_with_jd_and_time(nth, jd_utc, df_utc, 0, rof, sg) + + obj = obj + fr2 if fr2.nonzero? + + obj + end + + # call-seq: + # DateTime.commercial(cwyear=-4712, cweek=1, cwday=1, hour=0, minute=0, second=0, offset=0, start=Date::ITALY) -> datetime + # + # Creates a new DateTime from a commercial date. + # C: dt_lite_s_commercial + def commercial(cwyear = -4712, cweek = 1, cwday = 1, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) + raise TypeError, "invalid cwyear (not numeric)" unless cwyear.is_a?(Numeric) + raise TypeError, "invalid cweek (not numeric)" unless cweek.is_a?(Numeric) + raise TypeError, "invalid cwday (not numeric)" unless cwday.is_a?(Numeric) + raise TypeError, "invalid hour (not numeric)" unless hour.is_a?(Numeric) + raise TypeError, "invalid minute (not numeric)" unless minute.is_a?(Numeric) + raise TypeError, "invalid second (not numeric)" unless second.is_a?(Numeric) + + # Truncate fractional cwday + cwday_int = cwday.to_i + cwday_frac = cwday.is_a?(Integer) ? 0 : cwday - cwday_int + + result = valid_commercial_p(cwyear, cweek, cwday_int, start) + raise Date::Error, "invalid date" unless result + + nth = result[:nth] + rjd = result[:rjd] + sg = valid_sg(start) + + rof = _offset_to_sec(offset) + + h = hour.to_i + h_frac = hour - h + min_i = minute.to_i + min_frac = minute - min_i + s_i = second.to_i + s_frac = second - s_i + + fr2 = cwday_frac.nonzero? ? Rational(cwday_frac) : 0 + fr2 = fr2 + Rational(h_frac) / 24 if h_frac.nonzero? + fr2 = fr2 + Rational(min_frac) / 1440 if min_frac.nonzero? + fr2 = fr2 + Rational(s_frac) / 86400 if s_frac.nonzero? + + h += 24 if h < 0 + min_i += 60 if min_i < 0 + s_i += 60 if s_i < 0 + unless (0..24).cover?(h) && (0..59).cover?(min_i) && (0..59).cover?(s_i) && + !(h == 24 && (min_i > 0 || s_i > 0)) + raise Date::Error, "invalid date" + end + if h == 24 + h = 0 + fr2 = fr2 + 1 + end + + df = h * 3600 + min_i * 60 + s_i + df_utc = df - rof + jd_utc = rjd + if df_utc < 0 + jd_utc -= 1 + df_utc += 86400 + elsif df_utc >= 86400 + jd_utc += 1 + df_utc -= 86400 + end + + obj = new_with_jd_and_time(nth, jd_utc, df_utc, 0, rof, sg) + + obj = obj + fr2 if fr2.nonzero? + + obj + end + + # call-seq: + # DateTime.strptime(string='-4712-01-01T00:00:00+00:00', format='%FT%T%z', start=Date::ITALY) -> datetime + # + # Parses +string+ according to +format+ and creates a DateTime. + # C: dt_lite_s_strptime + def strptime(string = '-4712-01-01T00:00:00+00:00', format = '%FT%T%z', start = Date::ITALY) + hash = _strptime(string, format) + dt_new_by_frags(hash, start) + end + + # Override Date._strptime default format for DateTime + def _strptime(string, format = '%FT%T%z') + super(string, format) + end + + # call-seq: + # DateTime.now(start = Date::ITALY) -> datetime + # + # Creates a DateTime for the current time. + # + # C: datetime_s_now + def now(start = Date::ITALY) + t = Time.now + sg = valid_sg(start) + + of = t.utc_offset # integer seconds + + new( + t.year, t.mon, t.mday, + t.hour, t.min, t.sec + Rational(t.nsec, 1_000_000_000), + Rational(of, 86400), + sg + ) + end + + # call-seq: + # DateTime.parse(string, comp = true, start = Date::ITALY, limit: 128) -> datetime + # + # Parses +string+ and creates a DateTime. + # + # C: date_parse → dt_new_by_frags + def parse(string = JULIAN_EPOCH_DATETIME, comp = true, start = Date::ITALY, limit: 128) + hash = _parse(string, comp, limit: limit) + dt_new_by_frags(hash, start) + end + + # Format-specific constructors delegate to _xxx + dt_new_by_frags + + def iso8601(string = JULIAN_EPOCH_DATETIME, start = Date::ITALY, limit: 128) + hash = _iso8601(string, limit: limit) + dt_new_by_frags(hash, start) + end + + def rfc3339(string = JULIAN_EPOCH_DATETIME, start = Date::ITALY, limit: 128) + hash = _rfc3339(string, limit: limit) + dt_new_by_frags(hash, start) + end + + def xmlschema(string = JULIAN_EPOCH_DATETIME, start = Date::ITALY, limit: 128) + hash = _xmlschema(string, limit: limit) + dt_new_by_frags(hash, start) + end + + def rfc2822(string = JULIAN_EPOCH_DATETIME_RFC2822, start = Date::ITALY, limit: 128) + hash = _rfc2822(string, limit: limit) + dt_new_by_frags(hash, start) + end + alias_method :rfc822, :rfc2822 + + def httpdate(string = JULIAN_EPOCH_DATETIME_HTTPDATE, start = Date::ITALY, limit: 128) + hash = _httpdate(string, limit: limit) + dt_new_by_frags(hash, start) + end + + def jisx0301(string = JULIAN_EPOCH_DATETIME, start = Date::ITALY, limit: 128) + hash = _jisx0301(string, limit: limit) + dt_new_by_frags(hash, start) + end + + private + + JULIAN_EPOCH_DATETIME = '-4712-01-01T00:00:00+00:00' + JULIAN_EPOCH_DATETIME_RFC2822 = 'Mon, 1 Jan -4712 00:00:00 +0000' + JULIAN_EPOCH_DATETIME_HTTPDATE = 'Mon, 01 Jan -4712 00:00:00 GMT' + + # C: offset_to_sec / val2off (class method version for use in class << self) + def _offset_to_sec(of) + case of + when Integer + of + when Rational + (of * 86400).to_i + when Float + (of * 86400).to_i + when String + if of.strip.upcase == 'Z' + 0 + elsif of =~ /\A([+-])(\d{1,2}):(\d{2})\z/ + sign = $1 == '-' ? -1 : 1 + sign * ($2.to_i * 3600 + $3.to_i * 60) + elsif of =~ /\A([+-])(\d{2})(\d{2})?\z/ + sign = $1 == '-' ? -1 : 1 + sign * ($2.to_i * 3600 + ($3 ? $3.to_i * 60 : 0)) + else + 0 + end + else + 0 + end + end + + # C: dt_new_by_frags (date_core.c:8434) + # + # Structure matches C exactly: + # 1. Fast path: year+mon+mday present, no jd/yday + # - Validate civil, default time to 0, clamp sec==60 → 59 + # 2. Slow path: rt_rewrite_frags → rt_complete_frags → rt__valid_date_frags_p + # 3. Validate time (c_valid_time_p), handle sec_fraction, offset + # 4. Construct DateTime + def dt_new_by_frags(hash, sg) + raise Date::Error, "invalid date" if hash.nil? || hash.empty? + + # --- Fast path (C: lines 8447-8466) --- + if !hash.key?(:jd) && !hash.key?(:yday) && + hash[:year] && hash[:mon] && hash[:mday] + + y = hash[:year]; m = hash[:mon]; d = hash[:mday] + raise Date::Error, "invalid date" unless valid_civil?(y, m, d, sg) + + # C: default time fields, clamp sec==60 + hash[:hour] = 0 unless hash.key?(:hour) + hash[:min] = 0 unless hash.key?(:min) + if !hash.key?(:sec) + hash[:sec] = 0 + elsif hash[:sec] == 60 + hash[:sec] = 59 + end + + # --- Slow path (C: lines 8467-8470) --- + # rt_complete_frags needs DateTime as klass for time-only fill-in. + # rt__valid_date_frags_p needs Date for validation (calls ordinal/new). + else + hash = Date.send(:rt_rewrite_frags, hash) + hash = Date.send(:rt_complete_frags, self, hash) + jd_val = Date.send(:rt__valid_date_frags_p, hash, sg) + raise Date::Error, "invalid date" unless jd_val + + # Convert JD to civil for constructor + y, m, d = Date.send(:c_jd_to_civil, jd_val, sg) + end + + # --- Time validation (C: c_valid_time_p, lines 8473-8480) --- + h = hash[:hour] || 0 + min = hash[:min] || 0 + s = hash[:sec] || 0 + + # C: c_valid_time_p normalizes negative values and validates range. + rh = h < 0 ? h + 24 : h + rmin = min < 0 ? min + 60 : min + rs = s < 0 ? s + 60 : s + unless (0..24).cover?(rh) && (0..59).cover?(rmin) && (0..59).cover?(rs) && + !(rh == 24 && (rmin > 0 || rs > 0)) + raise Date::Error, "invalid date" + end + + # --- sec_fraction (C: lines 8482-8486) --- + sf = hash[:sec_fraction] + s_with_frac = sf ? rs + sf : rs + + # --- offset (C: lines 8488-8495) --- + of_sec = hash[:offset] || 0 + if of_sec.abs > 86400 + warn "invalid offset is ignored" + of_sec = 0 + end + of = Rational(of_sec, 86400) + + # --- Construct DateTime --- + new(y, m, d, rh, rmin, s_with_frac, of, sg) + end + end + + private + + # Convert offset argument to integer seconds. + # Accepts: Integer (seconds), Rational (fraction of day), String ("+HH:MM"), 0 + # C: offset_to_sec / val2off + def offset_to_sec(of) + case of + when Integer + of + when Float + # Fraction of day to seconds + (of * DAY_IN_SECONDS).to_i + when Rational + # Fraction of day to seconds + (of * DAY_IN_SECONDS).to_i + when String + if of.strip.upcase == 'Z' + 0 + elsif of =~ /\A([+-])(\d{2}):(\d{2})\z/ + sign = $1 == '-' ? -1 : 1 + sign * ($2.to_i * HOUR_IN_SECONDS + $3.to_i * MINUTE_IN_SECONDS) + elsif of =~ /\A([+-])(\d{2})(\d{2})?\z/ + sign = $1 == '-' ? -1 : 1 + sign * ($2.to_i * HOUR_IN_SECONDS + ($3 ? $3.to_i * MINUTE_IN_SECONDS : 0)) + else + 0 + end + else + 0 + end + end + + # Validate time fields (C: c_valid_time_p) + def validate_time(h, min, s) + h += 24 if h < 0 + min += 60 if min < 0 + s += 60 if s < 0 + unless (0..24).cover?(h) && (0..59).cover?(min) && (0..59).cover?(s) && + !(h == 24 && (min > 0 || s > 0)) + raise Error, "invalid date" + end + [h, min, s] + end +end diff --git a/lib/date/parse.rb b/lib/date/parse.rb new file mode 100644 index 00000000..095a522f --- /dev/null +++ b/lib/date/parse.rb @@ -0,0 +1,2607 @@ +# frozen_string_literal: true + +require_relative "patterns" +require_relative "zonetab" + +# Implementation of ruby/date/ext/date/date_parse.c +class Date + class << self + # call-seq: + # Date.parse(string = '-4712-01-01', comp = true, start = Date::ITALY, limit: 128) -> date + # + # Returns a new \Date object with values parsed from +string+. + # + # If +comp+ is +true+ and the given year is in the range (0..99), + # the current century is supplied; otherwise, the year is taken as given. + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # See argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date._parse (returns a hash). + def parse(string = JULIAN_EPOCH_DATE, comp = true, start = DEFAULT_SG, limit: 128) + hash = _parse(string, comp, limit: limit) + new_by_frags(hash, start) + end + + # call-seq: + # Date._parse(string, comp = true, limit: 128) -> hash + # + # Returns a hash of values parsed from +string+. + # + # If +comp+ is +true+ and the given year is in the range (0..99), + # the current century is supplied; otherwise, the year is taken as given. + # + # See argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date.parse (returns a \Date object). + def _parse(string, comp = true, limit: 128) + string = string_value(string) + str = string.strip + + # Check limit + if limit && str.length > limit + raise ArgumentError, "string length (#{str.length}) exceeds the limit #{limit}" + end + + date__parse(str, comp) + end + + # call-seq: + # Date._iso8601(string, limit: 128) -> hash + # + # Returns a hash of values parsed from +string+, which should contain + # an {ISO 8601 formatted date}[rdoc-ref:language/strftime_formatting.rdoc@ISO+8601+Format+Specifications]: + # + # d = Date.new(2001, 2, 3) + # s = d.iso8601 # => "2001-02-03" + # Date._iso8601(s) # => {:mday=>3, :year=>2001, :mon=>2} + # + # See argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date.iso8601 (returns a \Date object). + def _iso8601(string, limit: 128) + return {} if string.nil? + string = string_value(string) + check_string_limit(string, limit) + + date__iso8601(string) + end + + # date__rfc3339 in date_parse.c + def _rfc3339(string, limit: 128) + return {} if string.nil? + string = string_value(string) + check_string_limit(string, limit) + + date__rfc3339(string) + end + + # date__xmlschema in date_parse.c + def _xmlschema(string, limit: 128) + return {} if string.nil? + string = string_value(string) + check_string_limit(string, limit) + + date__xmlschema(string) + end + + # date__rfc2822 in date_parse.c + def _rfc2822(string, limit: 128) + return {} if string.nil? + string = string_value(string) + check_string_limit(string, limit) + + date__rfc2822(string) + end + alias _rfc822 _rfc2822 + + # call-seq: + # Date._httpdate(string, limit: 128) -> hash + # + # Returns a hash of values parsed from +string+, which should be a valid + # {HTTP date format}[rdoc-ref:language/strftime_formatting.rdoc@HTTP+Format]: + # + # d = Date.new(2001, 2, 3) + # s = d.httpdate # => "Sat, 03 Feb 2001 00:00:00 GMT" + # Date._httpdate(s) + # # => {:wday=>6, :mday=>3, :mon=>2, :year=>2001, :hour=>0, :min=>0, :sec=>0, :zone=>"GMT", :offset=>0} + # + # Related: Date.httpdate (returns a \Date object). + def _httpdate(string, limit: 128) + return {} if string.nil? + string = string_value(string) + check_string_limit(string, limit) + + date__httpdate(string) + end + + # call-seq: + # Date._jisx0301(string, limit: 128) -> hash + # + # Returns a hash of values parsed from +string+, which should be a valid + # {JIS X 0301 date format}[rdoc-ref:language/strftime_formatting.rdoc@JIS+X+0301+Format]: + # + # d = Date.new(2001, 2, 3) + # s = d.jisx0301 # => "H13.02.03" + # Date._jisx0301(s) # => {:year=>2001, :mon=>2, :mday=>3} + # + # See argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date.jisx0301 (returns a \Date object). + def _jisx0301(string, limit: 128) + return {} if string.nil? + string = string_value(string) + check_string_limit(string, limit) + + date__jisx0301(string) + end + + # --- Constructor methods --- + + def iso8601(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) + hash = _iso8601(string, limit: limit) + + new_by_frags(hash, start) + end + + def rfc3339(string = JULIAN_EPOCH_DATETIME, start = DEFAULT_SG, limit: 128) + hash = _rfc3339(string, limit: limit) + + new_by_frags(hash, start) + end + + def xmlschema(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) + hash = _xmlschema(string, limit: limit) + + new_by_frags(hash, start) + end + + def rfc2822(string = JULIAN_EPOCH_DATETIME_RFC2822, start = DEFAULT_SG, limit: 128) + hash = _rfc2822(string, limit: limit) + + new_by_frags(hash, start) + end + alias rfc822 rfc2822 + + def httpdate(string = JULIAN_EPOCH_DATETIME_HTTPDATE, start = DEFAULT_SG, limit: 128) + hash = _httpdate(string, limit: limit) + + new_by_frags(hash, start) + end + + def jisx0301(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) + hash = _jisx0301(string, limit: limit) + + new_by_frags(hash, start) + end + + private + + def date__parse(str, comp) + hash = {} + + # Preprocessing: duplicate and replace non-allowed characters. + # Non-TIGHT: Replace [^-+',./:@[:alnum:]\[\]]+ with a single space + str = str.dup.gsub(%r{[^-+',./:@[:alnum:]\[\]]+}, ' ') + + hash[:_comp] = comp + + # Parser invocation (non-TIGHT order) + # Note: C's HAVE_ELEM_P calls check_class(str) every time because + # str is modified by subx after each successful parse. + + # parse_day and parse_time always run (no goto ok). + if have_elem_p?(str, HAVE_ALPHA) + parse_day(str, hash) + end + + if have_elem_p?(str, HAVE_DIGIT) + parse_time(str, hash) + end + + # Date parsers: first success skips the rest (C's "goto ok"). + # In C, all paths converge at ok: for post-processing. + catch(:date_parsed) do + if have_elem_p?(str, HAVE_ALPHA | HAVE_DIGIT) + throw :date_parsed if parse_eu(str, hash) + throw :date_parsed if parse_us(str, hash) + end + + if have_elem_p?(str, HAVE_DIGIT | HAVE_DASH) + throw :date_parsed if parse_iso(str, hash) + end + + if have_elem_p?(str, HAVE_DIGIT | HAVE_DOT) + throw :date_parsed if parse_jis(str, hash) + end + + if have_elem_p?(str, HAVE_ALPHA | HAVE_DIGIT | HAVE_DASH) + throw :date_parsed if parse_vms(str, hash) + end + + if have_elem_p?(str, HAVE_DIGIT | HAVE_SLASH) + throw :date_parsed if parse_sla(str, hash) + end + + if have_elem_p?(str, HAVE_DIGIT | HAVE_DOT) + throw :date_parsed if parse_dot(str, hash) + end + + if have_elem_p?(str, HAVE_DIGIT) + throw :date_parsed if parse_iso2(str, hash) + end + + if have_elem_p?(str, HAVE_DIGIT) + throw :date_parsed if parse_year(str, hash) + end + + if have_elem_p?(str, HAVE_ALPHA) + throw :date_parsed if parse_mon(str, hash) + end + + if have_elem_p?(str, HAVE_DIGIT) + throw :date_parsed if parse_mday(str, hash) + end + + if have_elem_p?(str, HAVE_DIGIT) + throw :date_parsed if parse_ddd(str, hash) + end + end + + # ok: (post-processing — always runs, matching C's ok: label) + if have_elem_p?(str, HAVE_ALPHA) + parse_bc(str, hash) + end + if have_elem_p?(str, HAVE_DIGIT) + parse_frag(str, hash) + end + + apply_comp(hash) + hash + end + + # asctime format with timezone: Sat Aug 28 02:29:34 JST 1999 + def parse_asctime_with_zone(str, hash) + return false unless str =~ /\b(sun|mon|tue|wed|thu|fri|sat)[[:space:]]+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[[:space:]]+(\d{1,2})[[:space:]]+(\d{2}):(\d{2}):(\d{2})[[:space:]]+(.*?)[[:space:]]+(-?\d+)[[:space:]]*$/i + + wday_str = $1 + mon_str = $2 + mday_str = $3 + hour_str = $4 + min_str = $5 + sec_str = $6 + zone_part = $7 + year_str = $8 + + hash[:wday] = day_num(wday_str) + hash[:mon] = mon_num(mon_str) + hash[:mday] = mday_str.to_i + hash[:hour] = hour_str.to_i + hash[:min] = min_str.to_i + hash[:sec] = sec_str.to_i + + zone_part = zone_part.strip + unless zone_part.empty? + zone = zone_part.gsub(/\s+/, ' ') + hash[:zone] = zone + hash[:offset] = parse_zone_offset(zone) + end + + hash[:_year_str] = year_str + hash[:year] = year_str.to_i + apply_comp(hash) + + true + end + + # asctime format without timezone: Sat Aug 28 02:55:50 1999 + def parse_asctime(str, hash) + return false unless str =~ /\b(sun|mon|tue|wed|thu|fri|sat)\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})\s+(-?\d+)\s*$/i + + wday_str = $1 + mon_str = $2 + mday_str = $3 + hour_str = $4 + min_str = $5 + sec_str = $6 + year_str = $7 + + hash[:wday] = day_num(wday_str) + hash[:mon] = mon_num(mon_str) + hash[:mday] = mday_str.to_i + hash[:hour] = hour_str.to_i + hash[:min] = min_str.to_i + hash[:sec] = sec_str.to_i + hash[:_year_str] = year_str + hash[:year] = year_str.to_i + apply_comp(hash) + + true + end + + # HTTP date type 1: "Sat, 03 Feb 2001 00:00:00 GMT" + def httpdate_type1(str, hash) + pattern = /\A\s*(#{ABBR_DAYS_PATTERN})\s*,\s+ + (\d{2})\s+ + (#{ABBR_MONTHS_PATTERN})\s+ + (-?\d{4})\s+ + (\d{2}):(\d{2}):(\d{2})\s+ + (gmt)\s*\z/ix + + match = pattern.match(str) + return false unless match + + hash[:wday] = day_num(match[1]) + hash[:mday] = match[2].to_i + hash[:mon] = mon_num(match[3]) + hash[:year] = match[4].to_i + hash[:hour] = match[5].to_i + hash[:min] = match[6].to_i + hash[:sec] = match[7].to_i + hash[:zone] = match[8] + hash[:offset] = 0 + + true + end + + # HTTP date type 2: "Saturday, 03-Feb-01 00:00:00 GMT" + def httpdate_type2(str, hash) + pattern = /\A\s*(#{DAYS_PATTERN})\s*,\s+ + (\d{2})\s*-\s* + (#{ABBR_MONTHS_PATTERN})\s*-\s* + (\d{2})\s+ + (\d{2}):(\d{2}):(\d{2})\s+ + (gmt)\s*\z/ix + + match = pattern.match(str) + return false unless match + + hash[:wday] = day_num(match[1]) + hash[:mday] = match[2].to_i + hash[:mon] = mon_num(match[3]) + + # Year completion for 2-digit year + year = match[4].to_i + year = comp_year69(year) if year >= 0 && year <= 99 + hash[:year] = year + + hash[:hour] = match[5].to_i + hash[:min] = match[6].to_i + hash[:sec] = match[7].to_i + hash[:zone] = match[8] + hash[:offset] = 0 + + true + end + + # HTTP date type 3: "Sat Feb 3 00:00:00 2001" + def httpdate_type3(str, hash) + pattern = /\A\s*(#{ABBR_DAYS_PATTERN})\s+ + (#{ABBR_MONTHS_PATTERN})\s+ + (\d{1,2})\s+ + (\d{2}):(\d{2}):(\d{2})\s+ + (\d{4})\s*\z/ix + + match = pattern.match(str) + return false unless match + + hash[:wday] = day_num(match[1]) + hash[:mon] = mon_num(match[2]) + hash[:mday] = match[3].to_i + hash[:hour] = match[4].to_i + hash[:min] = match[5].to_i + hash[:sec] = match[6].to_i + hash[:year] = match[7].to_i + + true + end + + # parse_day in date_parse.c. + # Non-TIGHT pattern: \b(sun|mon|tue|wed|thu|fri|sat)[^-/\d\s]* + # The [^-/\d\s]* part consumes trailing characters (e.g., "urday" + # in "Saturday") so they get replaced by subx, but only the + # abbreviation in $1 is used. + def parse_day(str, hash) + m = subx(str, PARSE_DAY_PAT) + return false unless m + + hash[:wday] = day_num(m[1]) + + true + end + + # parse_time in date_parse.c. + # Uses subx to replace the matched time portion with " " so + # subsequent parsers (parse_us, etc.) won't re-match it. + def parse_time(str, hash) + m = subx(str, TIME_PAT) + return false unless m + + time_str = m[1] + zone_str = m[2] + + parse_time_detail(time_str, hash) + + if zone_str && !zone_str.empty? + hash[:zone] = zone_str + hash[:offset] = date_zone_to_diff(zone_str) + end + + true + end + + # parse_ddd in date_parse.c. + def parse_ddd(str, hash) + m = subx(str, PARSE_DDD_PAT) + return false unless m + + sign = m[1] + digits = m[2] + time_digits = m[3] + fraction = m[4] + zone = m[5] + + l = digits.length + + # Branches based on the length of the main number string. + case l + when 2 + if time_digits.nil? && !fraction.nil? + hash[:sec] = digits[-2, 2].to_i + else + hash[:mday] = digits[0, 2].to_i + end + when 4 + if time_digits.nil? && !fraction.nil? + hash[:sec] = digits[-2, 2].to_i + hash[:min] = digits[-4, 2].to_i + else + hash[:mon] = digits[0, 2].to_i + hash[:mday] = digits[2, 2].to_i + end + when 6 + if time_digits.nil? && !fraction.nil? + hash[:sec] = digits[-2, 2].to_i + hash[:min] = digits[-4, 2].to_i + hash[:hour] = digits[-6, 2].to_i + else + y = digits[0, 2].to_i + y = -y if sign == '-' + hash[:year] = y + hash[:mon] = digits[2, 2].to_i + hash[:mday] = digits[4, 2].to_i + hash[:_year_str] = digits[0, 2] # year completion + end + when 8, 10, 12, 14 + if time_digits.nil? && !fraction.nil? + # Interpreted as time + hash[:sec] = digits[-2, 2].to_i + hash[:min] = digits[-4, 2].to_i + hash[:hour] = digits[-6, 2].to_i + hash[:mday] = digits[-8, 2].to_i + hash[:mon] = digits[-10, 2].to_i if l >= 10 + if l == 12 + y = digits[-12, 2].to_i + y = -y if sign == '-' + hash[:year] = y + hash[:_year_str] = digits[-12, 2] + elsif l == 14 + y = digits[-14, 4].to_i + y = -y if sign == '-' + hash[:year] = y + hash[:_comp] = false + end + else + # Interpret as date + y = digits[0, 4].to_i + y = -y if sign == '-' + hash[:year] = y + hash[:mon] = digits[4, 2].to_i + hash[:mday] = digits[6, 2].to_i + hash[:hour] = digits[8, 2].to_i if l >= 10 + hash[:min] = digits[10, 2].to_i if l >= 12 + hash[:sec] = digits[12, 2].to_i if l >= 14 + hash[:_comp] = false + end + when 3 + if time_digits.nil? && !fraction.nil? + hash[:sec] = digits[-2, 2].to_i + hash[:min] = digits[-3, 1].to_i + else + hash[:yday] = digits[0, 3].to_i + end + when 5 + if time_digits.nil? && !fraction.nil? + hash[:sec] = digits[-2, 2].to_i + hash[:min] = digits[-4, 2].to_i + hash[:hour] = digits[-5, 1].to_i + else + y = digits[0, 2].to_i + y = -y if sign == '-' + hash[:year] = y + hash[:yday] = digits[2, 3].to_i + hash[:_year_str] = digits[0, 2] + end + when 7 + if time_digits.nil? && !fraction.nil? + hash[:sec] = digits[-2, 2].to_i + hash[:min] = digits[-4, 2].to_i + hash[:hour] = digits[-6, 2].to_i + hash[:mday] = digits[-7, 1].to_i + else + y = digits[0, 4].to_i + y = -y if sign == '-' + hash[:year] = y + hash[:yday] = digits[4, 3].to_i + # No need to complete because it is a 4-digit year + end + end + + # Processing time portion + if time_digits && !time_digits.empty? + tl = time_digits.length + if !fraction.nil? + # Interpreted as time + case tl + when 2, 4, 6 + hash[:sec] = time_digits[-2, 2].to_i + hash[:min] = time_digits[-4, 2].to_i if tl >= 4 + hash[:hour] = time_digits[-6, 2].to_i if tl >= 6 + end + else + # Interpreted as time + case tl + when 2, 4, 6 + hash[:hour] = time_digits[0, 2].to_i + hash[:min] = time_digits[2, 2].to_i if tl >= 4 + hash[:sec] = time_digits[4, 2].to_i if tl >= 6 + end + end + end + + # Handling fractional seconds + if fraction && !fraction.empty? + hash[:sec_fraction] = Rational(fraction.to_i, 10 ** fraction.length) + end + + # Handling time zone + if zone && !zone.empty? + if zone[0] == '[' + # Bracket-enclosed zone: C's parse_ddd_cb special handling. + # Strip '[' and ']', then check for ':' separator. + inner = zone[1..-2] # content between [ and ] + colon_pos = inner.index(':') + if colon_pos + # e.g., "[-5:EST]" → zone_name="EST", offset_str="-5:" + # C: zone = part after ':', s5 = part from start to after ':' + zone_name = inner[(colon_pos + 1)..] + offset_str = inner[0, colon_pos + 1] # includes ':' + else + # e.g., "[-9]" → zone_name="-9", offset_str="-9" + # e.g., "[9]" → zone_name="9", offset_str="+9" (digit→prepend '+') + zone_name = inner + if inner[0] && inner[0] =~ /\d/ + offset_str = "+" + zone_name + else + offset_str = zone_name + end + end + hash[:zone] = zone_name + hash[:offset] = date_zone_to_diff(offset_str) + else + # Non-bracket zone: just set zone. + # Offset will be resolved in apply_comp if not already set. + hash[:zone] = zone + hash[:offset] = date_zone_to_diff(zone) + end + end + + true + end + + # Parse $1 (time string) further and set hash to hour/min/sec/sec_fraction. + # + # Internal pattern: + # $1 hour + # $2 min (colon format) + # $3 sec (colon format) + # $4 frac ([,.]\d*) + # $5 min (h format) + # $6 sec (h format) + # $7 am/pm (a or p) + def parse_time_detail(time_str, hash) + return unless time_str =~ TIME_DETAIL_PAT + + hour = $1.to_i + min_colon = $2 + sec_colon = $3 + frac = $4 # "[,.] number string" or nil + min_h = $5 + sec_h = $6 + ampm = $7 + + if min_colon + # Branch A: HH:MM[:SS[.frac]] + hash[:hour] = hour + hash[:min] = min_colon.to_i + if sec_colon + hash[:sec] = sec_colon.to_i + if frac && frac.length > 1 + # Since frac is a "[,.] number string", the first character (delimiter) is omitted. + frac_digits = frac[1..] + hash[:sec_fraction] = Rational(frac_digits.to_i, 10 ** frac_digits.length) + end + end + elsif min_h + # Branch B: HHh[MMm[SSs]](with min) + hash[:hour] = hour + hash[:min] = min_h.to_i + hash[:sec] = sec_h.to_i if sec_h + elsif time_str.match?(/h/i) + # Branch B: Only HHh (no min/sec) + hash[:hour] = hour + elsif ampm + # Branch C: Only AM/PM => Set only hour (converted to AM/PM below) + hash[:hour] = hour + end + + # AM/PM conversion + if ampm + h = hash[:hour] || hour + if ampm.downcase == 'p' && h != 12 + hash[:hour] = h + 12 + elsif ampm.downcase == 'a' && h == 12 + hash[:hour] = 0 + end + end + end + + # parse_era in date_parse.c. + def parse_era(str, hash) + if str =~ ERA1_PAT + hash[:bc] = false + return true + end + + if str =~ ERA2_PAT + hash[:bc] = $1.downcase.delete('.') != 'ce' + return true + end + + false + end + + # parse_eu in date_parse.c. + def parse_eu(str, hash) + m = subx(str, PARSE_EU_PAT) + return false unless m + + mday_str = m[1] + mon_str = m[2] + era_str = m[3] + year_str = m[4] + + # Determine bc flag from era. + # AD/A.D./CE/C.E. => false, BC/B.C./BCE/B.C.E. => true + bc = if era_str + era_str.downcase.delete('.') !~ /\A(ad|ce)\z/ + else + false + end + + # Normalize y/m/d and set to hash in s3e. + # 'mon' is converted to an Integer using 'mon_num' and then passed. + s3e(hash, year_str, mon_num(mon_str), mday_str, bc) + + true + end + + # parse_us in date_parse.c. + def parse_us(str, hash) + m = subx(str, PARSE_US_PAT) + return false unless m + + mon_str = m[1] + mday_str = m[2] + era_str = m[3] + year_str = m[4] + + # Determine bc flag from era (same logic as parse_eu). + bc = if era_str + era_str.downcase.delete('.') !~ /\A(ad|ce)\z/ + else + false + end + + # Normalize y/m/d and set to hash using s3e. + # Difference from parse_eu: mon=$1, mday=$2 (only the $ numbers are swapped). + s3e(hash, year_str, mon_num(mon_str), mday_str, bc) + + true + end + + # parse_iso in date_parse.c + def parse_iso(str, hash) + m = subx(str, PARSE_ISO_PAT) + return false unless m + + # Normalize y/m/d and set to hash in s3e. + # bc is always false (there is no era symbol in ISO format). + s3e(hash, m[1], m[2], m[3], false) + + true + end + + # parse_iso2 in date_parse.c + def parse_iso2(str, hash) + return true if parse_iso21(str, hash) + return true if parse_iso22(str, hash) + return true if parse_iso23(str, hash) + return true if parse_iso24(str, hash) + return true if parse_iso25(str, hash) + return true if parse_iso26(str, hash) + + false + end + + def parse_iso21(str, hash) + m = subx(str, PARSE_ISO21_PAT) + return false unless m + + hash[:cwyear] = m[1].to_i if m[1] + hash[:cweek] = m[2].to_i + hash[:cwday] = m[3].to_i if m[3] + + true + end + + def parse_iso22(str, hash) + m = subx(str, PARSE_ISO22_PAT) + return false unless m + + hash[:cwday] = m[1].to_i + + true + end + + def parse_iso23(str, hash) + m = subx(str, PARSE_ISO23_PAT) + return false unless m + + hash[:mon] = m[1].to_i if m[1] + hash[:mday] = m[2].to_i + + true + end + + def parse_iso24(str, hash) + m = subx(str, PARSE_ISO24_PAT) + return false unless m + + hash[:mon] = m[1].to_i + hash[:mday] = m[2].to_i if m[2] + + true + end + + def parse_iso25(str, hash) + # Skip if exclude pattern matches (uses match, not subx). + return false if str =~ PARSE_ISO25_PAT0 + + m = subx(str, PARSE_ISO25_PAT) + return false unless m + + hash[:year] = m[1].to_i + hash[:yday] = m[2].to_i + + true + end + + def parse_iso26(str, hash) + # Skip if exclude pattern matches (uses match, not subx). + return false if str =~ PARSE_ISO26_PAT0 + + m = subx(str, PARSE_ISO26_PAT) + return false unless m + + hash[:yday] = m[1].to_i + + true + end + + # parse_jis in date_parse.c + def parse_jis(str, hash) + m = subx(str, PARSE_JIS_PAT) + return false unless m + + era = m[1].upcase + year = m[2].to_i + mon = m[3].to_i + mday = m[4].to_i + + # Convert the era symbol and year number to Gregorian calendar + # and set it to hash. + hash[:year] = gengo(era) + year + hash[:mon] = mon + hash[:mday] = mday + + true + end + + # parse_vms in date_parse.c + def parse_vms(str, hash) + return true if parse_vms11(str, hash) + return true if parse_vms12(str, hash) + + false + end + + def parse_vms11(str, hash) + m = subx(str, PARSE_VMS11_PAT) + return false unless m + + mday_str = m[1] + mon_str = m[2] + year_str = m[3] + + # Normalize y/m/d and set to hash in s3e. + s3e(hash, year_str, mon_num(mon_str), mday_str, false) + + true + end + + def parse_vms12(str, hash) + m = subx(str, PARSE_VMS12_PAT) + return false unless m + + mon_str = m[1] + mday_str = m[2] + year_str = m[3] + + # Normalize y/m/d and set to hash in s3e. + s3e(hash, year_str, mon_num(mon_str), mday_str, false) + + true + end + + # parse_sla in date_parse.c + def parse_sla(str, hash) + m = subx(str, PARSE_SLA_PAT) + return false unless m + + # Normalize y/m/d and set to hash in s3e. + # bc is always false. + s3e(hash, m[1], m[2], m[3], false) + + true + end + + # parse_dot in date_parse.c + def parse_dot(str, hash) + m = subx(str, PARSE_DOT_PAT) + return false unless m + + # Normalize y/m/d and set to hash in s3e. + # bc is always false. + s3e(hash, m[1], m[2], m[3], false) + + true + end + + # parse_year in date_parse.c + def parse_year(str, hash) + m = subx(str, PARSE_YEAR_PAT) + return false unless m + + hash[:year] = m[1].to_i + + true + end + + # parse_mon in date_parse.c + def parse_mon(str, hash) + m = subx(str, PARSE_MON_PAT) + return false unless m + + hash[:mon] = mon_num(m[1]) + + true + end + + # parse_mday in date_parse.c + def parse_mday(str, hash) + m = subx(str, PARSE_MDAY_PAT) + return false unless m + + hash[:mday] = m[1].to_i + + true + end + + # parse_bc in date_parse.c (non-TIGHT post-processing). + # Matches standalone BC/BCE/B.C./B.C.E. and sets _bc flag. + def parse_bc(str, hash) + m = subx(str, PARSE_BC_PAT) + return false unless m + + hash[:_bc] = true + + true + end + + # parse_frag in date_parse.c (non-TIGHT post-processing). + # If the remaining string (after all other parsers have consumed + # their portions) is a standalone 1-2 digit number: + # - If we have hour but no mday, and the number is 1-31, set mday + # - If we have mday but no hour, and the number is 0-24, set hour + def parse_frag(str, hash) + m = subx(str, PARSE_FRAG_PAT) + return false unless m + + n = m[1].to_i + + if hash.key?(:hour) && !hash.key?(:mday) + hash[:mday] = n if n >= 1 && n <= 31 + end + if hash.key?(:mday) && !hash.key?(:hour) + hash[:hour] = n if n >= 0 && n <= 24 + end + + true + end + + # Helper: Convert day name to number (0=Sunday, 6=Saturday) + def day_num(day_name) + abbr_days = %w[sun mon tue wed thu fri sat] + abbr_days.index(day_name[0, 3].downcase) || 0 + end + + # Helper: Convert month name to number (1=January, 12=December) + def mon_num(month_name) + abbr_months = %w[jan feb mar apr may jun jul aug sep oct nov dec] + (abbr_months.index(month_name[0, 3].downcase) || 0) + 1 + end + + # ISO 8601 extended datetime: 2001-02-03T04:05:06+09:00 + def iso8601_ext_datetime(str, hash) + pattern = /\A\s* + (?: + ([-+]?\d{2,}|-)-(\d{2})?(?:-(\d{2}))?| # YYYY-MM-DD or --MM-DD + ([-+]?\d{2,})?-(\d{3})| # YYYY-DDD + (\d{4}|\d{2})?-w(\d{2})-(\d)| # YYYY-Www-D + -w-(\d) # -W-D + ) + (?:t + (\d{2}):(\d{2})(?::(\d{2})(?:[,.](\d+))?)? # HH:MM:SS.fraction + (z|[-+]\d{2}(?::?\d{2})?)? # timezone + )? + \s*\z/ix + + match = pattern.match(str) + return false unless match + + # Calendar date (YYYY-MM-DD) + if match[1] + unless match[1] == '-' + year = match[1].to_i + # Complete 2-digit year + year = comp_year69(year) if match[1].length < 4 + hash[:year] = year + end + hash[:mon] = match[2].to_i if match[2] + hash[:mday] = match[3].to_i if match[3] + # Ordinal date (YYYY-DDD) + elsif match[5] + if match[4] + year = match[4].to_i + year = comp_year69(year) if match[4].length < 4 + hash[:year] = year + end + hash[:yday] = match[5].to_i + # Week date (YYYY-Www-D) + elsif match[8] + if match[6] + year = match[6].to_i + year = comp_year69(year) if match[6].length < 4 + hash[:cwyear] = year + end + hash[:cweek] = match[7].to_i + hash[:cwday] = match[8].to_i + # Week day only (-W-D) + elsif match[9] + hash[:cwday] = match[9].to_i + end + + # Time + if match[10] + hash[:hour] = match[10].to_i + hash[:min] = match[11].to_i + hash[:sec] = match[12].to_i if match[12] + hash[:sec_fraction] = parse_fraction(match[13]) if match[13] + end + + # Timezone + if match[14] + hash[:zone] = match[14] + hash[:offset] = parse_zone_offset(match[14]) + end + + true + end + + # ISO 8601 basic datetime: 20010203T040506 + def iso8601_bas_datetime(str, hash) + # Try full basic datetime: YYYYMMDD or YYMMDD + pattern = /\A\s* + ([-+]?(?:\d{4}|\d{2})|--) # Year (YYYY, YY, --, or signed) + (\d{2}|-) # Month (MM or -) + (\d{2}) # Day (DD) + (?:t? + (\d{2})(\d{2}) # Hour and minute (HHMM) + (?:(\d{2}) # Second (SS) + (?:[,.](\d+))? # Fraction + )? + (z|[-+]\d{2}(?:\d{2})?)? # Timezone + )? + \s*\z/ix + + match = pattern.match(str) + if match + # Calendar date + unless match[1] == '--' + year = match[1].to_i + year = comp_year69(year) if match[1].length == 2 && match[1] !~ /^[-+]/ + hash[:year] = year + end + hash[:mon] = match[2].to_i unless match[2] == '-' + hash[:mday] = match[3].to_i + + # Time + if match[4] + hash[:hour] = match[4].to_i + hash[:min] = match[5].to_i + hash[:sec] = match[6].to_i if match[6] + hash[:sec_fraction] = parse_fraction(match[7]) if match[7] + end + + # Timezone + if match[8] + hash[:zone] = match[8] + hash[:offset] = parse_zone_offset(match[8]) + end + + return true + end + + # Try ordinal date: YYYYDDD or YYDDD + pattern = /\A\s* + ([-+]?(?:\d{4}|\d{2})) # Year + (\d{3}) # Day of year + (?:t? + (\d{2})(\d{2}) # Hour and minute + (?:(\d{2}) # Second + (?:[,.](\d+))? # Fraction + )? + (z|[-+]\d{2}(?:\d{2})?)? # Timezone + )? + \s*\z/ix + + match = pattern.match(str) + if match + year = match[1].to_i + year = comp_year69(year) if match[1].length == 2 && match[1] !~ /^[-+]/ + hash[:year] = year + hash[:yday] = match[2].to_i + + # Time + if match[3] + hash[:hour] = match[3].to_i + hash[:min] = match[4].to_i + hash[:sec] = match[5].to_i if match[5] + hash[:sec_fraction] = parse_fraction(match[6]) if match[6] + end + + # Timezone + if match[7] + hash[:zone] = match[7] + hash[:offset] = parse_zone_offset(match[7]) + end + + return true + end + + # Try -DDD (ordinal without year) + pattern = /\A\s* + -(\d{3}) # Day of year + (?:t? + (\d{2})(\d{2}) # Hour and minute + (?:(\d{2}) # Second + (?:[,.](\d+))? # Fraction + )? + (z|[-+]\d{2}(?:\d{2})?)? # Timezone + )? + \s*\z/ix + + match = pattern.match(str) + if match + hash[:yday] = match[1].to_i + + # Time + if match[2] + hash[:hour] = match[2].to_i + hash[:min] = match[3].to_i + hash[:sec] = match[4].to_i if match[4] + hash[:sec_fraction] = parse_fraction(match[5]) if match[5] + end + + # Timezone + if match[6] + hash[:zone] = match[6] + hash[:offset] = parse_zone_offset(match[6]) + end + + return true + end + + # Try week date: YYYYWwwD or YYWwwD + pattern = /\A\s* + (\d{4}|\d{2}) # Year + w(\d{2}) # Week + (\d) # Day of week + (?:t? + (\d{2})(\d{2}) # Hour and minute + (?:(\d{2}) # Second + (?:[,.](\d+))? # Fraction + )? + (z|[-+]\d{2}(?:\d{2})?)? # Timezone + )? + \s*\z/ix + + match = pattern.match(str) + if match + year = match[1].to_i + year = comp_year69(year) if match[1].length == 2 + hash[:cwyear] = year + hash[:cweek] = match[2].to_i + hash[:cwday] = match[3].to_i + + # Time + if match[4] + hash[:hour] = match[4].to_i + hash[:min] = match[5].to_i + hash[:sec] = match[6].to_i if match[6] + hash[:sec_fraction] = parse_fraction(match[7]) if match[7] + end + + # Timezone + if match[8] + hash[:zone] = match[8] + hash[:offset] = parse_zone_offset(match[8]) + end + + return true + end + + # Try -WwwD (week date without year) + pattern = /\A\s* + -w(\d{2}) # Week + (\d) # Day of week + (?:t? + (\d{2})(\d{2}) # Hour and minute + (?:(\d{2}) # Second + (?:[,.](\d+))? # Fraction + )? + (z|[-+]\d{2}(?:\d{2})?)? # Timezone + )? + \s*\z/ix + + match = pattern.match(str) + if match + hash[:cweek] = match[1].to_i + hash[:cwday] = match[2].to_i + + # Time + if match[3] + hash[:hour] = match[3].to_i + hash[:min] = match[4].to_i + hash[:sec] = match[5].to_i if match[5] + hash[:sec_fraction] = parse_fraction(match[6]) if match[6] + end + + # Timezone + if match[7] + hash[:zone] = match[7] + hash[:offset] = parse_zone_offset(match[7]) + end + + return true + end + + # Try -W-D (day of week only) + pattern = /\A\s* + -w-(\d) # Day of week + (?:t? + (\d{2})(\d{2}) # Hour and minute + (?:(\d{2}) # Second + (?:[,.](\d+))? # Fraction + )? + (z|[-+]\d{2}(?:\d{2})?)? # Timezone + )? + \s*\z/ix + + match = pattern.match(str) + if match + hash[:cwday] = match[1].to_i + + # Time + if match[2] + hash[:hour] = match[2].to_i + hash[:min] = match[3].to_i + hash[:sec] = match[4].to_i if match[4] + hash[:sec_fraction] = parse_fraction(match[5]) if match[5] + end + + # Timezone + if match[6] + hash[:zone] = match[6] + hash[:offset] = parse_zone_offset(match[6]) + end + + return true + end + + false + end + + # ISO 8601 extended time: 04:05:06+09:00 + def iso8601_ext_time(str, hash) + # Pattern: HH:MM:SS.fraction or HH:MM:SS,fraction + pattern = /\A\s*(\d{2}):(\d{2})(?::(\d{2})(?:[,.](\d+))?)?(z|[-+]\d{2}(?::?\d{2})?)?\s*\z/ix + + match = pattern.match(str) + return false unless match + + hash[:hour] = match[1].to_i + hash[:min] = match[2].to_i + hash[:sec] = match[3].to_i if match[3] + hash[:sec_fraction] = parse_fraction(match[4]) if match[4] + + if match[5] + hash[:zone] = match[5] + hash[:offset] = parse_zone_offset(match[5]) + end + + true + end + + # ISO 8601 basic time: 040506 + def iso8601_bas_time(str, hash) + # Pattern: HHMMSS.fraction or HHMMSS,fraction + pattern = /\A\s*(\d{2})(\d{2})(?:(\d{2})(?:[,.](\d+))?)?(z|[-+]\d{2}(?:\d{2})?)?\s*\z/ix + + match = pattern.match(str) + return false unless match + + hash[:hour] = match[1].to_i + hash[:min] = match[2].to_i + hash[:sec] = match[3].to_i if match[3] + hash[:sec_fraction] = parse_fraction(match[4]) if match[4] + + if match[5] + hash[:zone] = match[5] + hash[:offset] = parse_zone_offset(match[5]) + end + + true + end + + # Parse fractional seconds + def parse_fraction(frac_str) + return nil unless frac_str + Rational(frac_str.to_i, 10 ** frac_str.length) + end + + # Parse timezone offset (Z, +09:00, -0500, etc.) + def parse_zone_offset(zone_str) + return nil if zone_str.nil? || zone_str.empty? + + zone = zone_str.strip + + # Handle [+9] or [-9] or [9 ] format (brackets around offset) + if zone =~ /^\[(.*)\]$/ + zone = $1.strip + end + + # Handle Z (UTC) + return 0 if zone.upcase == 'Z' + + # Handle unsigned numeric offset: 9, 09 (assume positive) + if zone =~ /^(\d{1,2})$/ + hours = $1.to_i + return hours * HOUR_IN_SECONDS + end + + # Handle simple numeric offsets with sign: +9, -9, +09, -05, etc. + if zone =~ /^([-+])(\d{1,2})$/ + sign = $1 == '-' ? -1 : 1 + hours = $2.to_i + return sign * (hours * HOUR_IN_SECONDS) + end + + # Handle +09:00, -05:30 format (with colon) + if zone =~ /^([-+])(\d{2}):(\d{2})$/ + sign = $1 == '-' ? -1 : 1 + hours = $2.to_i + minutes = $3.to_i + return sign * (hours * HOUR_IN_SECONDS + minutes * MINUTE_IN_SECONDS) + end + + # Handle +0900, -0500 format (4 digits, no colon) + if zone =~ /^([-+])(\d{4})$/ + sign = $1 == '-' ? -1 : 1 + hours = $2[0, 2].to_i + minutes = $2[2, 2].to_i + return sign * (hours * HOUR_IN_SECONDS + minutes * MINUTE_IN_SECONDS) + end + + # Handle +0900 format (4 digits without colon) + if zone =~ /^([-+])(\d{4})$/ + sign = $1 == '-' ? -1 : 1 + hours = $2[0, 2].to_i + minutes = $2[2, 2].to_i + return sign * (hours * HOUR_IN_SECONDS + minutes * MINUTE_IN_SECONDS) + end + + # Handle fractional hours: +9.5, -5.5 + if zone =~ /^([-+])(\d+)[.,](\d+)$/ + sign = $1 == '-' ? -1 : 1 + hours = $2.to_i + fraction = "0.#{$3}".to_f + return sign * ((hours + fraction) * HOUR_IN_SECONDS).to_i + end + + # Handle GMT+9, GMT-5, etc. + if zone =~ /^(?:gmt|utc)?([-+])(\d{1,2})(?::?(\d{2}))?(?::?(\d{2}))?$/i + sign = $1 == '-' ? -1 : 1 + hours = $2.to_i + minutes = $3 ? $3.to_i : 0 + seconds = $4 ? $4.to_i : 0 + return sign * (hours * HOUR_IN_SECONDS + minutes * MINUTE_IN_SECONDS + seconds) + end + + # Known timezone abbreviations + zone_offsets = { + 'JST' => 9 * HOUR_IN_SECONDS, + 'GMT' => 0, + 'UTC' => 0, + 'UT' => 0, + 'EST' => -5 * HOUR_IN_SECONDS, + 'EDT' => -4 * HOUR_IN_SECONDS, + 'CST' => -6 * HOUR_IN_SECONDS, + 'CDT' => -5 * HOUR_IN_SECONDS, + 'MST' => -7 * HOUR_IN_SECONDS, + 'MDT' => -6 * HOUR_IN_SECONDS, + 'PST' => -8 * HOUR_IN_SECONDS, + 'PDT' => -7 * HOUR_IN_SECONDS, + 'AEST' => 10 * HOUR_IN_SECONDS, + 'MET DST' => 2 * HOUR_IN_SECONDS, + 'GMT STANDARD TIME' => 0, + 'MOUNTAIN STANDARD TIME' => -7 * HOUR_IN_SECONDS, + 'MOUNTAIN DAYLIGHT TIME' => -6 * HOUR_IN_SECONDS, + 'MEXICO STANDARD TIME' => -6 * HOUR_IN_SECONDS, + 'E. AUSTRALIA STANDARD TIME' => 10 * HOUR_IN_SECONDS, + 'W. CENTRAL AFRICA STANDARD TIME' => 1 * HOUR_IN_SECONDS, + } + + # Handle military timezones (single letters A-Z except J) + if zone =~ /^([A-Z])$/i + letter = zone.upcase + return 0 if letter == 'Z' + return nil if letter == 'J' # J is not used + + if letter <= 'I' + # A-I: +1 to +9 + offset = letter.ord - 'A'.ord + 1 + elsif letter >= 'K' && letter <= 'M' + # K-M: +10 to +12 (skip J) + offset = letter.ord - 'A'.ord # K is 10th letter (ord-'A'=10) + elsif letter >= 'N' && letter <= 'Y' + # N-Y: -1 to -12 + offset = -(letter.ord - 'N'.ord + 1) + else + return nil + end + + return offset * HOUR_IN_SECONDS + end + + # Normalize zone string for lookup + zone_upper = zone.gsub(/\s+/, ' ').upcase + zone_offsets[zone_upper] + end + + # JIS X 0301 format: H13.02.03 or H13.02.03T04:05:06 + def parse_jisx0301_fmt(str, hash) + # Pattern: [Era]YY.MM.DD[T]HH:MM:SS[.fraction][timezone] + # Era initials: M, T, S, H, R (or none for ISO 8601 fallback) + pattern = /\A\s* + ([#{JISX0301_ERA_INITIALS}])? # Era (optional) + (\d{2})\.(\d{2})\.(\d{2}) # YY.MM.DD + (?:t # Time separator (optional) + (?: + (\d{2}):(\d{2}) # HH:MM + (?::(\d{2}) # :SS (optional) + (?:[,.](\d*))? # .fraction (optional) + )? + (z|[-+]\d{2}(?::?\d{2})?)? # timezone (optional) + )? + )? + \s*\z/ix + + match = pattern.match(str) + return false unless match + + # Parse era and year + era_char = match[1] ? match[1].upcase : JISX0301_DEFAULT_ERA + era_year = match[2].to_i + + # Convert era year to gregorian year + era_start = gengo(era_char) + hash[:year] = era_start + era_year + + # Parse month and day + hash[:mon] = match[3].to_i + hash[:mday] = match[4].to_i + + # Parse time (if present) + if match[5] + hash[:hour] = match[5].to_i + hash[:min] = match[6].to_i if match[6] + hash[:sec] = match[7].to_i if match[7] + hash[:sec_fraction] = parse_fraction(match[8]) if match[8] + end + + # Parse timezone (if present) + if match[9] + hash[:zone] = match[9] + hash[:offset] = parse_zone_offset(match[9]) + end + + true + end + + # Convert era character to year offset + def gengo(era_char) + case era_char.upcase + when 'M' then 1867 # Meiji + when 'T' then 1911 # Taisho + when 'S' then 1925 # Showa + when 'H' then 1988 # Heisei + when 'R' then 2018 # Reiwa + else 0 + end + end + + # Post-processing: matches C's date__parse post-processing after ok: label. + # + # 1. _bc handling: negate year and cwyear (year = 1 - year) + # 2. _comp handling: complete 2-digit year/cwyear to 4-digit (69-99 → 1900s, 0-68 → 2000s) + # 3. zone → offset conversion + # 4. Clean up internal keys + def apply_comp(hash) + # _bc: del_hash("_bc") — read and delete + bc = hash.delete(:_bc) + if bc + if hash.key?(:cwyear) + hash[:cwyear] = 1 - hash[:cwyear] + end + if hash.key?(:year) + hash[:year] = 1 - hash[:year] + end + end + + # _comp: del_hash("_comp") — read and delete + comp = hash.delete(:_comp) + if comp + if hash.key?(:cwyear) + y = hash[:cwyear] + if y >= 0 && y <= 99 + hash[:cwyear] = y >= 69 ? y + 1900 : y + 2000 + end + end + if hash.key?(:year) + y = hash[:year] + if y >= 0 && y <= 99 + hash[:year] = y >= 69 ? y + 1900 : y + 2000 + end + end + end + + # zone → offset conversion + if hash.key?(:zone) && !hash.key?(:offset) + hash[:offset] = date_zone_to_diff(hash[:zone]) + end + + # Clean up internal keys + hash.delete(:_year_str) + end + + # s3e in date_parse.c. + # y, m, and d are Strings or nil. m can also be an Integer (convert with to_s). + # bc is a Boolean. + # + # This method normalizes the year, mon, and mday from the combination of y, m, and + # d and writes them to a hash. + # The sorting logic operates in the following order of priority: + # + # Phase 1: Argument rotation and promotion + # - y and m are available, but d is nil => Rotate because it is a pair (mon, mday) + # - y is nil and d is long (>2 digits) or starts with an apostrophe => Promote d to y + # - If y has a leading character other than a digit, extract only the numeric portion, and if there is a remainder, add it to d + # + # Phase 2: Sort m and d + # - m starts with an apostrophe or its length is >2 => US->BE sort (y,m,d)=(m,d,y) + # - d starts with an apostrophe or its length is >2 => Swap (y,d) + # + # Phase 3: Write to hash + # - Extract the sign and digits from y and set them to year + # If signed or the number of digits is >2, write _comp = false + # - Extract the number from m and set it to mon + # - Extract the number from d and set it to mday + # - If bc is true, write _bc = true + def s3e(hash, y, m, d, bc) + # Candidates for _comp. If nil, do not write. + c = nil + + # If m is not a string, use to_s (parse_eu/parse_us passes the Integer returned by mon_num) + m = m.to_s unless m.nil? || m.is_a?(String) + + # ---------------------------------------------------------- + # Phase 1: Argument reordering + # ---------------------------------------------------------- + + # If we have y and m, but d is nil, it's actually a (mon, mday) pair, so we rotate it. + # (y, m, d) = (nil, y, m) + if !y.nil? && !m.nil? && d.nil? + y, m, d = nil, y, m + end + + # If y is nil and d exists, if d is long or begins with an apostrophe, it is promoted to y + if y.nil? + if !d.nil? && d.length > 2 + y = d + d = nil + end + if !d.nil? && d.length > 0 && d[0] == "'" + y = d + d = nil + end + end + + # If y has a leading character other than a sign or a number, skip it and + # extract only the numeric part. If there are any characters remaining after + # the extracted numeric string, swap y and d, and set the numeric part to d. + unless y.nil? + pos = 0 + pos += 1 while pos < y.length && !issign?(y[pos]) && !y[pos].match?(/\d/) + + unless pos >= y.length # no_date + bp = pos + pos += 1 if pos < y.length && issign?(y[pos]) + span = digit_span(y[pos..]) + ep = pos + span + + if ep < y.length + # There is a letter after the number string => exchange (y, d) + y, d = d, y[bp...ep] + end + end + end + + # ---------------------------------------------------------- + # Phase 2: Rearrange m and d + # ---------------------------------------------------------- + + # m starts with an apostrophe or length > 2 => US => BE sort + # (y, m, d) = (m, d, y) + if !m.nil? && (m[0] == "'" || m.length > 2) + y, m, d = m, d, y + end + + # d begins with an apostrophe or length > 2 => exchange (y, d) + if !d.nil? && (d[0] == "'" || d.length > 2) + y, d = d, y + end + + # ---------------------------------------------------------- + # Phase 3: Write to hash + # ---------------------------------------------------------- + + # year: Extract the sign and digit from y and set + unless y.nil? + pos = 0 + pos += 1 while pos < y.length && !issign?(y[pos]) && !y[pos].match?(/\d/) + + unless pos >= y.length # no_year + bp = pos + sign = false + if pos < y.length && issign?(y[pos]) + sign = true + pos += 1 + end + + c = false if sign # Signed => _comp = false + span = digit_span(y[pos..]) + c = false if span > 2 # Number of digits > 2 => _comp = false + + num_str = y[bp, (pos - bp) + span] # sign + number part + hash[:year] = num_str.to_i + end + end + + hash[:_bc] = true if bc + + # mon: Extract and set a number from m + unless m.nil? + pos = 0 + pos += 1 while pos < m.length && !m[pos].match?(/\d/) + + unless pos >= m.length # no_month + span = digit_span(m[pos..]) + hash[:mon] = m[pos, span].to_i + end + end + + # mday: Extract and set numbers from d + unless d.nil? + pos = 0 + pos += 1 while pos < d.length && !d[pos].match?(/\d/) + + unless pos >= d.length # no_mday + span = digit_span(d[pos..]) + hash[:mday] = d[pos, span].to_i + end + end + + # _comp is written only if it is explicitly false + hash[:_comp] = false unless c.nil? + end + + # issign macro in date_parse.c. + def issign?(c) + c == '-' || c == '+' + end + + # digit_span in date_parse.c. + # Returns the length of the first consecutive digit in the string 's'. + def digit_span(s) + i = 0 + i += 1 while i < s.length && s[i].match?(/\d/) + + i + end + + # date_zone_to_diff in date_parse.c. + # Returns the number of seconds since UTC from a time zone name or offset string. + # Returns nil if no match occurs. + # + # Supported input types: + # 1. Zone names: "EST", "JST", "Eastern", "Central Pacific", ... + # 2. Suffixes: "Eastern standard time", "EST dst", ... + # "standard time" => As is + # "daylight time" / "dst" => Set offset to +3600 + # 3. Numeric offset: "+09:00", "-0530", "+9", "GMT+09:00", ... + # 4. Fractional time offset: "+9.5" (=+09:30), "+5.50" (=+05:30), ... + def date_zone_to_diff(str) + return nil if str.nil? || str.empty? + + s = str.dup + dst = false + + # Suffix removal: "time", "standard", "daylight", "dst" + w = str_end_with_word(s, "time") + if w > 0 + s = s[0, s.length - w] + + w2 = str_end_with_word(s, "standard") + if w2 > 0 + s = s[0, s.length - w2] + else + w2 = str_end_with_word(s, "daylight") + if w2 > 0 + s = s[0, s.length - w2] + dst = true + else + # "time" alone is not enough, so return + s = str.dup + end + end + else + w = str_end_with_word(s, "dst") + if w > 0 + s = s[0, s.length - w] + dst = true + end + end + + # --- zonetab search --- + # Normalize consecutive spaces into a single space before searching + zn = shrink_space(s) + z_offset = ZONE_TABLE[zn.downcase] + + if z_offset + z_offset += 3600 if dst + return z_offset + end + + # --- Parse numeric offsets --- + # Remove "GMT" and "UTC" prefixes + if zn.length > 3 && zn[0, 3].downcase =~ /\A(gmt|utc)\z/ + zn = zn[3..] + end + + # If there is no sign, it is not treated as a numeric offset + return nil if zn.empty? || (zn[0] != '+' && zn[0] != '-') + + sign = zn[0] == '-' ? -1 : 1 + zn = zn[1..] + return nil if zn.empty? + + # ':' separator: HH:MM or HH:MM:SS + if zn.include?(':') + return parse_colon_offset(zn, sign) + end + + # '.' or ',' separator: HH.fraction + if zn.include?('.') || zn.include?(',') + return parse_fractional_offset(zn, sign) + end + + # Others: HH or HHMM or HHMMSS + parse_compact_offset(zn, sign) + end + + # str_end_with_word in date_parse.c. + # If the string 's' ends with "" (a word plus a space), + # Returns the length of that "" (including leading spaces). + # Otherwise, returns 0. + def str_end_with_word(s, word) + n = word.length + return 0 if s.length <= n + + # The last n characters match word (ignoring case) + return 0 unless s[-n..].casecmp?(word) + + # Is there a space just before it? + return 0 unless s[-(n + 1)].match?(/\s/) + + # Include consecutive spaces + count = n + 1 + count += 1 while count < s.length && s[-(count + 1)].match?(/\s/) + + count + end + + # shrink_space in date_parse.c. + # Combines consecutive spaces into a single space. + # If the length is the same as the original (normalization unnecessary), + # return it as is. + def shrink_space(s) + result = [] + prev_space = false + s.each_char do |ch| + if ch.match?(/\s/) + result << ' ' unless prev_space + prev_space = true + else + result << ch + prev_space = false + end + end + result.join + end + + # parse_colon_offset + # Parse "+HH:MM" or "+HH:MM:SS" and return the number of seconds. + # Range checking: hour 0-23, min 0-59, sec 0-59 + def parse_colon_offset(zn, sign) + parts = zn.split(':') + hour = parts[0].to_i + return nil if hour < 0 || hour > 23 + + min = parts.length > 1 ? parts[1].to_i : 0 + return nil if min < 0 || min > 59 + + sec = parts.length > 2 ? parts[2].to_i : 0 + return nil if sec < 0 || sec > 59 + + sign * (sec + min * 60 + hour * 3600) + end + + # Parse "+HH.fraction" or "+HH,fraction" and return the number of seconds. + # + # C logic: + # Read the fraction string up to 7 digits. + # sec = (read value) * 36 + # If n <= 2: + # If n == 1, sec *= 10 (treat HH.n as HH.n0) + # Return value = sec + hour * 3600 (Integer) + # If n > 2: + # Return value = Rational(sec, 10**(n-2)) + hour * 3600 + # Convert to an Integer if the denominator is 1. + # + # Reason for the 36 factor: + # 1 hour = 3600 seconds. Each decimal point is 1/10. Time = 360 seconds. + # However, since the implementation handles it in two-digit units, multiply + # by 36 before dividing by 10^2. + # (3600 / 100 = 36) + def parse_fractional_offset(zn, sign) + sep = zn.include?('.') ? '.' : ',' + hh_str, frac_str = zn.split(sep, 2) + hour = hh_str.to_i + return nil if hour < 0 || hour > 23 + + # Up to 7 digits (C: "no over precision for offset") + max_digits = 7 + frac_str = frac_str[0, max_digits] + n = frac_str.length + return sign * (hour * 3600) if n == 0 + + sec = frac_str.to_i * 36 # Convert to seconds by factor 36 + + if sign == -1 + hour = -hour + sec = -sec + end + + if n <= 2 + sec *= 10 if n == 1 # HH.n => HH.n0 + sec + hour * 3600 + else + # Rational for precise calculations + denom = 10 ** (n - 2) + offset = Rational(sec, denom) + (hour * 3600) + offset.denominator == 1 ? offset.to_i : offset + end + end + + # parse_compact_offset + # Parse consecutive numeric offsets without colons. + # HH (2 digits or less) + # HHM (3 digits: 1 digit for hour, 2 digits for min) + # HHMM (4 digits) + # HHMMM (5 digits: 2 digits for hour, 2 digits for min, 1 digit for sec) ... Rare in practical use + # HHMMSS (6 digits) + # + # C adjusts the leading padding width with "2 - l % 2". + # Ruby does the same calculation with length. + def parse_compact_offset(zn, sign) + l = zn.length + + # Only HH + return sign * zn.to_i * 3600 if l <= 2 + + # C: hour = scan_digits(&s[0], 2 - l % 2) + # min = scan_digits(&s[2 - l % 2], 2) + # sec = scan_digits(&s[4 - l % 2], 2) + # + # l=3 => hw=1 => hour=zn[0,1], min=zn[1,2] + # l=4 => hw=2 => hour=zn[0,2], min=zn[2,2] + # l=5 => hw=1 => hour=zn[0,1], min=zn[1,2], sec=zn[3,2] + # l=6 => hw=2 => hour=zn[0,2], min=zn[2,2], sec=zn[4,2] + hw = 2 - l % 2 # hour width: 2 for even, 1 for odd + hour = zn[0, hw].to_i + min = l >= 3 ? zn[hw, 2].to_i : 0 + sec = l >= 5 ? zn[hw + 2, 2].to_i : 0 + + sign * (sec + min * 60 + hour * 3600) + end + + # subx in date_parse.c. + # Matches pat against str. If it matches, replaces the matched + # portion of str (in-place) with rep (default: " ") and returns + # the MatchData. Returns nil on no match. + # + # This is the core mechanism C uses (via the SUBS macro) to + # prevent later parsers from re-matching already-consumed text. + def subx(str, pat, rep = " ") + m = pat.match(str) + return nil unless m + + str[m.begin(0), m.end(0) - m.begin(0)] = rep + m + end + + def check_class(str) + flags = 0 + str.each_char do |c| + flags |= HAVE_ALPHA if c =~ /[a-zA-Z]/ + flags |= HAVE_DIGIT if c =~ /\d/ + flags |= HAVE_DASH if c == '-' + flags |= HAVE_DOT if c == '.' + flags |= HAVE_SLASH if c == '/' + end + + flags + end + + # C macro HAVE_ELEM_P(x) in date_parse.c. + # Note: C calls check_class(str) every time because str is + # modified by subx. We do the same here. + def have_elem_p?(str, required) + (check_class(str) & required) == required + end + + # --- String type conversion (C's StringValue macro) --- + def string_value(str) + return str if str.is_a?(String) + if str.respond_to?(:to_str) + s = str.to_str + raise TypeError, "can't convert #{str.class} to String (#{str.class}#to_str gives #{s.class})" unless s.is_a?(String) + return s + end + raise TypeError, "no implicit conversion of #{str.class} into String" + end + + def check_string_limit(str, limit) + if limit && str.length > limit + raise ArgumentError, "string length (#{str.length}) exceeds the limit #{limit}" + end + end + + # C: d_new_by_frags + # Date-only fragment-based constructor. + # Time fields in hash are ignored — use dt_new_by_frags (in datetime.rb) for DateTime. + def new_by_frags(hash, sg) + raise Error, "invalid date" if hash.nil? || hash.empty? + + y = hash[:year] + m = hash[:mon] + d = hash[:mday] + + # Fast path: year+mon+mday present, no jd/yday + if !hash.key?(:jd) && !hash.key?(:yday) && y && m && d + raise Error, "invalid date" unless valid_civil?(y, m, d, sg) + obj = new(y, m, d, sg) + # Store parsed offset for deconstruct_keys([:zone]) without + # affecting JD calculations (don't use @of which triggers UTC conversion) + of = hash[:offset] + obj.instance_variable_set(:@parsed_offset, of) if of && of != 0 + return obj + end + + # Slow path — uses self (Date), so time-only patterns + # (e.g. '23:55') correctly fail: rt_complete_frags with Date class + # does not set :jd for :time pattern → rt__valid_date_frags_p returns nil. + hash = rt_rewrite_frags(hash) + hash = rt_complete_frags(self, hash) + jd = rt__valid_date_frags_p(hash, sg) + + raise Error, "invalid date" unless jd + + self.jd(jd, sg) + end + + # C: rt_rewrite_frags + # Converts :seconds (from %s/%Q) into jd/hour/min/sec/sec_fraction fields. + # + # C implementation (date_core.c:4033): + # seconds = del_hash("seconds"); + # if (!NIL_P(seconds)) { + # if (!NIL_P(offset)) seconds = f_add(seconds, offset); + # d = f_idiv(seconds, DAY_IN_SECONDS); + # fr = f_mod(seconds, DAY_IN_SECONDS); + # h = f_idiv(fr, HOUR_IN_SECONDS); fr = f_mod(fr, HOUR_IN_SECONDS); + # min= f_idiv(fr, MINUTE_IN_SECONDS); fr = f_mod(fr, MINUTE_IN_SECONDS); + # s = f_idiv(fr, 1); fr = f_mod(fr, 1); + # set jd = UNIX_EPOCH_IN_CJD + d, hour, min, sec, sec_fraction + # } + # + # Ruby's .div() and % match C's f_idiv (rb_intern("div")) and f_mod ('%'). + # Both use floor semantics, correctly handling negative and Rational values. + def rt_rewrite_frags(hash) + seconds = hash.delete(:seconds) + return hash unless seconds + + offset = hash[:offset] + seconds = seconds + offset if offset + + # Day count from Unix epoch + # C: d = f_idiv(seconds, DAY_IN_SECONDS) + d = seconds.div(DAY_IN_SECONDS) + fr = seconds % DAY_IN_SECONDS + + # Decompose remainder into h:min:s.frac + h = fr.div(HOUR_IN_SECONDS) + fr = fr % HOUR_IN_SECONDS + + min = fr.div(MINUTE_IN_SECONDS) + fr = fr % MINUTE_IN_SECONDS + + s = fr.div(1) + fr = fr % 1 + + # C: UNIX_EPOCH_IN_CJD = 2440588 (1970-01-01 in Chronological JD) + hash[:jd] = 2440588 + d + hash[:hour] = h + hash[:min] = min + hash[:sec] = s + hash[:sec_fraction] = fr + hash + end + + # C: rt_complete_frags (date_core.c:4071) + # + # Algorithm: + # 1. Score each of 11 field-set patterns against hash, pick highest match count. + # 2. For the winning named pattern, fill leading missing date fields from Date.today + # and set defaults for trailing date fields. + # 3. Special case: "time" pattern + DateTime class → set :jd from today. + # 4. Default :hour/:min/:sec to 0; clamp :sec to 59. + # + # Pattern table (C's static tab): + # [name, [fields...]] + # ────────────────────────── + # [:time, [:hour, :min, :sec]] + # [nil, [:jd]] + # [:ordinal, [:year, :yday, :hour, :min, :sec]] + # [:civil, [:year, :mon, :mday, :hour, :min, :sec]] + # [:commercial, [:cwyear, :cweek, :cwday, :hour, :min, :sec]] + # [:wday, [:wday, :hour, :min, :sec]] + # [:wnum0, [:year, :wnum0, :wday, :hour, :min, :sec]] + # [:wnum1, [:year, :wnum1, :wday, :hour, :min, :sec]] + # [nil, [:cwyear, :cweek, :wday, :hour, :min, :sec]] + # [nil, [:year, :wnum0, :cwday, :hour, :min, :sec]] + # [nil, [:year, :wnum1, :cwday, :hour, :min, :sec]] + # + def rt_complete_frags(klass, hash) + # Step 1: Find best matching pattern + # C: for each tab entry, count how many fields exist in hash; pick max. + # First match wins on tie (strict >). + best_key = nil + best_fields = nil + best_count = 0 + + COMPLETE_FRAGS_TABLE.each do |key, fields| + count = fields.count { |f| hash.key?(f) } + if count > best_count + best_count = count + best_key = key + best_fields = fields + end + end + + # Step 2: Complete missing fields for named patterns + # C: if (!NIL_P(k) && (RARRAY_LEN(a) > e)) + d = nil # lazy Date.today + + if best_key && best_fields && best_fields.length > best_count + case best_key + + when :ordinal + # C: fill year from today if missing, default yday=1 + unless hash.key?(:year) + d ||= today + hash[:year] = d.year + end + hash[:yday] ||= 1 + + when :civil + # C: fill leading missing fields from today, stop at first present field. + # Then default mon=1, mday=1. + # + # The loop iterates [:year, :mon, :mday, :hour, :min, :sec]. + # For each field, if it's already in hash → break. + # Otherwise fill from today via d.send(field). + # In practice, the loop only reaches date fields (:year/:mon/:mday) + # because at least one date field must be present for civil to win. + best_fields.each do |f| + break if hash.key?(f) + d ||= today + hash[f] = d.send(f) + end + hash[:mon] ||= 1 + hash[:mday] ||= 1 + + when :commercial + # C: same leading-fill pattern, then default cweek=1, cwday=1 + best_fields.each do |f| + break if hash.key?(f) + d ||= today + hash[f] = d.send(f) + end + hash[:cweek] ||= 1 + hash[:cwday] ||= 1 + + when :wday + # C: set_hash("jd", d_lite_jd(f_add(f_sub(d, d_lite_wday(d)), ref_hash("wday")))) + # → jd of (today - today.wday + parsed_wday) + d ||= today + hash[:jd] = (d - d.wday + hash[:wday]).jd + + when :wnum0 + # C: leading-fill from today, then default wnum0=0, wday=0 + best_fields.each do |f| + break if hash.key?(f) + d ||= today + # :year is the only field that can be missing before :wnum0 in practice + hash[f] = d.send(f) if d.respond_to?(f) + end + hash[:wnum0] ||= 0 + hash[:wday] ||= 0 + + when :wnum1 + # C: leading-fill from today, then default wnum1=0, wday=1 + best_fields.each do |f| + break if hash.key?(f) + d ||= today + hash[f] = d.send(f) if d.respond_to?(f) + end + hash[:wnum1] ||= 0 + hash[:wday] ||= 1 + end + end + + # Step 3: "time" pattern special case + # C: if (k == sym("time")) { if (f_le_p(klass, cDateTime)) { ... } } + # For DateTime (or subclass), time-only input gets :jd from today. + # For Date, time-only input will fail validation (no date fields). + if best_key == :time + if defined?(DateTime) && klass <= DateTime + d ||= today + hash[:jd] ||= d.jd + end + end + + # Step 4: Default time fields, clamp sec + # C: if (NIL_P(ref_hash("hour"))) set_hash("hour", 0); + # if (NIL_P(ref_hash("min"))) set_hash("min", 0); + # if (NIL_P(ref_hash("sec"))) set_hash("sec", 0); + # else if (ref_hash("sec") > 59) set_hash("sec", 59); + hash[:hour] ||= 0 + hash[:min] ||= 0 + if !hash.key?(:sec) + hash[:sec] = 0 + elsif hash[:sec] > 59 + hash[:sec] = 59 + end + + hash + end + + # C: rt__valid_date_frags_p (date_core.c:4379) + # Tries 6 strategies to produce a valid JD from hash fragments: + # jd → ordinal → civil → commercial → wnum0 → wnum1 + def rt__valid_date_frags_p(hash, sg) + # 1. Try jd (C: rt__valid_jd_p just returns jd) + if hash[:jd] + return hash[:jd] + end + + # 2. Try ordinal: year + yday + if hash[:yday] && hash[:year] + y = hash[:year] + yd = hash[:yday] + if valid_ordinal?(y, yd, sg) + return ordinal(y, yd, sg).jd + end + end + + # 3. Try civil: year + mon + mday + if hash[:mday] && hash[:mon] && hash[:year] + y = hash[:year] + m = hash[:mon] + d = hash[:mday] + if valid_civil?(y, m, d, sg) + return new(y, m, d, sg).jd + end + end + + # 4. Try commercial: cwyear + cweek + cwday/wday + # C: wday = ref_hash("cwday"); + # if (NIL_P(wday)) { wday = ref_hash("wday"); if wday==0 → wday=7; } + begin + wday = hash[:cwday] + if wday.nil? + wday = hash[:wday] + wday = 7 if wday && wday == 0 # Sunday: wday 0 → cwday 7 + end + + if wday && hash[:cweek] && hash[:cwyear] + jd = rt__valid_commercial_p(hash[:cwyear], hash[:cweek], wday, sg) + return jd if jd + end + end + + # 5. Try wnum0: year + wnum0 + wday (Sunday-first week, %U) + # C: wday = ref_hash("wday"); + # if (NIL_P(wday)) { wday = ref_hash("cwday"); if cwday==7 → wday=0; } + begin + wday = hash[:wday] + if wday.nil? + wday = hash[:cwday] + wday = 0 if wday && wday == 7 # Sunday: cwday 7 → wday 0 + end + + if wday && hash[:wnum0] && hash[:year] + jd = rt__valid_weeknum_p(hash[:year], hash[:wnum0], wday, 0, sg) + return jd if jd + end + end + + # 6. Try wnum1: year + wnum1 + wday (Monday-first week, %W) + # C: wday = ref_hash("wday"); if NIL → wday = ref_hash("cwday"); + # if wday → wday = (wday - 1) % 7 + begin + wday = hash[:wday] + wday = hash[:cwday] if wday.nil? + if wday + wday = (wday - 1) % 7 # Convert: 0(Sun)→6, 1(Mon)→0, ..., 7(Sun)→6 + end + + if wday && hash[:wnum1] && hash[:year] + jd = rt__valid_weeknum_p(hash[:year], hash[:wnum1], wday, 1, sg) + return jd if jd + end + end + + nil + end + + # C: rt__valid_commercial_p (date_core.c:4347) + # Validates commercial date and returns JD, or nil. + def rt__valid_commercial_p(y, w, d, sg) + if valid_commercial?(y, w, d, sg) + return commercial(y, w, d, sg).jd + end + nil + end + + # C: rt__valid_weeknum_p → valid_weeknum_p → c_valid_weeknum_p (date_core.c:1009) + # Validates weeknum-based date and returns JD, or nil. + # f=0 for Sunday-first (%U), f=1 for Monday-first (%W). + def rt__valid_weeknum_p(y, w, d, f, sg) + # C: if (d < 0) d += 7; + d += 7 if d < 0 + # C: if (w < 0) { ... normalize via next year ... } + if w < 0 + rjd2 = c_weeknum_to_jd(y + 1, 1, f, f, sg) + ry2, rw2, _ = c_jd_to_weeknum(rjd2 + w * 7, f, sg) + return nil if ry2 != y + w = rw2 + end + jd = c_weeknum_to_jd(y, w, d, f, sg) + ry, rw, rd = c_jd_to_weeknum(jd, f, sg) + return nil if y != ry || w != rw || d != rd + jd + end + + # C: c_weeknum_to_jd (date_core.c:663) + # Converts (year, week_number, day_in_week, first_day_flag, sg) → JD. + # + # C formula: + # c_find_fdoy(y, sg, &rjd2, &ns2); + # rjd2 += 6; + # *rjd = (rjd2 - MOD(((rjd2 - f) + 1), 7) - 7) + 7 * w + d; + def c_weeknum_to_jd(y, w, d, f, sg) + fdoy_jd, _ = c_find_fdoy(y, sg) + fdoy_jd += 6 + (fdoy_jd - ((fdoy_jd - f + 1) % 7) - 7) + 7 * w + d + end + + # C: c_jd_to_weeknum (date_core.c:674) + # Converts JD → [year, week_number, day_in_week]. + # Class-method version (the instance method in core.rb calls self.class.send). + # + # C formula: + # c_jd_to_civil(jd, sg, &ry, ...); + # c_find_fdoy(ry, sg, &rjd, ...); + # rjd += 6; + # j = jd - (rjd - MOD((rjd - f) + 1, 7)) + 7; + # rw = DIV(j, 7); + # rd = MOD(j, 7); + def c_jd_to_weeknum(jd, f, sg) + ry, _, _ = c_jd_to_civil(jd, sg) + fdoy_jd, _ = c_find_fdoy(ry, sg) + fdoy_jd += 6 + + j = jd - (fdoy_jd - ((fdoy_jd - f + 1) % 7)) + 7 + rw = j.div(7) + rd = j % 7 + + [ry, rw, rd] + end + + # --- comp_year helpers (C's comp_year69, comp_year50) --- + def comp_year69(y) + y >= 69 ? y + 1900 : y + 2000 + end + + def comp_year50(y) + y >= 50 ? y + 1900 : y + 2000 + end + + # --- sec_fraction helper --- + def sec_fraction(frac_str) + Rational(frac_str.to_i, 10 ** frac_str.length) + end + + # ================================================================ + # Format-specific parsers (date_parse.c) + # ================================================================ + + # --- ISO 8601 --- + + def date__iso8601(str) + hash = {} + return hash if str.nil? || str.empty? + + if (m = ISO8601_EXT_DATETIME_PAT.match(str)) + iso8601_ext_datetime_cb(m, hash) + elsif (m = ISO8601_BAS_DATETIME_PAT.match(str)) + iso8601_bas_datetime_cb(m, hash) + elsif (m = ISO8601_EXT_TIME_PAT.match(str)) + iso8601_time_cb(m, hash) + elsif (m = ISO8601_BAS_TIME_PAT.match(str)) + iso8601_time_cb(m, hash) + end + hash + end + + def iso8601_ext_datetime_cb(m, hash) + if m[1] + hash[:mday] = m[3].to_i if m[3] + if m[1] != '-' + y = m[1].to_i + y = comp_year69(y) if m[1].length < 4 + hash[:year] = y + end + if m[2].nil? + return false if m[1] != '-' + else + hash[:mon] = m[2].to_i + end + elsif m[5] + hash[:yday] = m[5].to_i + if m[4] + y = m[4].to_i + y = comp_year69(y) if m[4].length < 4 + hash[:year] = y + end + elsif m[8] + hash[:cweek] = m[7].to_i + hash[:cwday] = m[8].to_i + if m[6] + y = m[6].to_i + y = comp_year69(y) if m[6].length < 4 + hash[:cwyear] = y + end + elsif m[9] + hash[:cwday] = m[9].to_i + end + + if m[10] + hash[:hour] = m[10].to_i + hash[:min] = m[11].to_i + hash[:sec] = m[12].to_i if m[12] + end + hash[:sec_fraction] = sec_fraction(m[13]) if m[13] + if m[14] + hash[:zone] = m[14] + hash[:offset] = date_zone_to_diff(m[14]) + end + true + end + + def iso8601_bas_datetime_cb(m, hash) + if m[3] + hash[:mday] = m[3].to_i + if m[1] != '--' + y = m[1].to_i + y = comp_year69(y) if m[1].length < 4 + hash[:year] = y + end + if m[2][0] == '-' + return false if m[1] != '--' + else + hash[:mon] = m[2].to_i + end + elsif m[5] + hash[:yday] = m[5].to_i + y = m[4].to_i + y = comp_year69(y) if m[4].length < 4 + hash[:year] = y + elsif m[6] + hash[:yday] = m[6].to_i + elsif m[9] + hash[:cweek] = m[8].to_i + hash[:cwday] = m[9].to_i + y = m[7].to_i + y = comp_year69(y) if m[7].length < 4 + hash[:cwyear] = y + elsif m[11] + hash[:cweek] = m[10].to_i + hash[:cwday] = m[11].to_i + elsif m[12] + hash[:cwday] = m[12].to_i + end + + if m[13] + hash[:hour] = m[13].to_i + hash[:min] = m[14].to_i + hash[:sec] = m[15].to_i if m[15] + end + hash[:sec_fraction] = sec_fraction(m[16]) if m[16] + if m[17] + hash[:zone] = m[17] + hash[:offset] = date_zone_to_diff(m[17]) + end + true + end + + def iso8601_time_cb(m, hash) + hash[:hour] = m[1].to_i + hash[:min] = m[2].to_i + hash[:sec] = m[3].to_i if m[3] + hash[:sec_fraction] = sec_fraction(m[4]) if m[4] + if m[5] + hash[:zone] = m[5] + hash[:offset] = date_zone_to_diff(m[5]) + end + true + end + + # --- RFC 3339 --- + + def date__rfc3339(str) + hash = {} + return hash if str.nil? || str.empty? + + m = RFC3339_PAT.match(str) + return hash unless m + + hash[:year] = m[1].to_i + hash[:mon] = m[2].to_i + hash[:mday] = m[3].to_i + hash[:hour] = m[4].to_i + hash[:min] = m[5].to_i + hash[:sec] = m[6].to_i + hash[:zone] = m[8] + hash[:offset] = date_zone_to_diff(m[8]) + hash[:sec_fraction] = sec_fraction(m[7]) if m[7] + hash + end + + # --- XML Schema --- + + def date__xmlschema(str) + hash = {} + return hash if str.nil? || str.empty? + + if (m = XMLSCHEMA_DATETIME_PAT.match(str)) + hash[:year] = m[1].to_i + hash[:mon] = m[2].to_i if m[2] + hash[:mday] = m[3].to_i if m[3] + hash[:hour] = m[4].to_i if m[4] + hash[:min] = m[5].to_i if m[5] + hash[:sec] = m[6].to_i if m[6] + hash[:sec_fraction] = sec_fraction(m[7]) if m[7] + if m[8] + hash[:zone] = m[8] + hash[:offset] = date_zone_to_diff(m[8]) + end + elsif (m = XMLSCHEMA_TIME_PAT.match(str)) + hash[:hour] = m[1].to_i + hash[:min] = m[2].to_i + hash[:sec] = m[3].to_i if m[3] + hash[:sec_fraction] = sec_fraction(m[4]) if m[4] + if m[5] + hash[:zone] = m[5] + hash[:offset] = date_zone_to_diff(m[5]) + end + elsif (m = XMLSCHEMA_TRUNC_PAT.match(str)) + hash[:mon] = m[1].to_i if m[1] + hash[:mday] = m[2].to_i if m[2] + hash[:mday] = m[3].to_i if m[3] + if m[4] + hash[:zone] = m[4] + hash[:offset] = date_zone_to_diff(m[4]) + end + end + hash + end + + # --- RFC 2822 --- + + def date__rfc2822(str) + hash = {} + return hash if str.nil? || str.empty? + + m = PARSE_RFC2822_PAT.match(str) + return hash unless m + + hash[:wday] = day_num(m[1]) if m[1] + hash[:mday] = m[2].to_i + hash[:mon] = mon_num(m[3]) + y = m[4].to_i + y = comp_year50(y) if m[4].length < 4 + hash[:year] = y + hash[:hour] = m[5].to_i + hash[:min] = m[6].to_i + hash[:sec] = m[7].to_i if m[7] + hash[:zone] = m[8] + hash[:offset] = date_zone_to_diff(m[8]) + hash + end + + # --- HTTP date --- + + def date__httpdate(str) + hash = {} + return hash if str.nil? || str.empty? + + if (m = PARSE_HTTPDATE_TYPE1_PAT.match(str)) + hash[:wday] = day_num(m[1]) + hash[:mday] = m[2].to_i + hash[:mon] = mon_num(m[3]) + hash[:year] = m[4].to_i + hash[:hour] = m[5].to_i + hash[:min] = m[6].to_i + hash[:sec] = m[7].to_i + hash[:zone] = m[8] + hash[:offset] = 0 + elsif (m = PARSE_HTTPDATE_TYPE2_PAT.match(str)) + hash[:wday] = day_num(m[1]) + hash[:mday] = m[2].to_i + hash[:mon] = mon_num(m[3]) + y = m[4].to_i + y = comp_year69(y) if y >= 0 && y <= 99 + hash[:year] = y + hash[:hour] = m[5].to_i + hash[:min] = m[6].to_i + hash[:sec] = m[7].to_i + hash[:zone] = m[8] + hash[:offset] = 0 + elsif (m = PARSE_HTTPDATE_TYPE3_PAT.match(str)) + hash[:wday] = day_num(m[1]) + hash[:mon] = mon_num(m[2]) + hash[:mday] = m[3].to_i + hash[:hour] = m[4].to_i + hash[:min] = m[5].to_i + hash[:sec] = m[6].to_i + hash[:year] = m[7].to_i + end + hash + end + + # --- JIS X 0301 --- + + def date__jisx0301(str) + hash = {} + return hash if str.nil? || str.empty? + + m = PARSE_JISX0301_PAT.match(str) + if m + era = m[1] || JISX0301_DEFAULT_ERA + ep = gengo(era) + hash[:year] = ep + m[2].to_i + hash[:mon] = m[3].to_i + hash[:mday] = m[4].to_i + if m[5] + hash[:hour] = m[5].to_i + hash[:min] = m[6].to_i if m[6] + hash[:sec] = m[7].to_i if m[7] + end + hash[:sec_fraction] = sec_fraction(m[8]) if m[8] && !m[8].empty? + if m[9] + hash[:zone] = m[9] + hash[:offset] = date_zone_to_diff(m[9]) + end + else + # Fallback to iso8601 + hash = date__iso8601(str) + end + hash + end + end +end diff --git a/lib/date/patterns.rb b/lib/date/patterns.rb new file mode 100644 index 00000000..b8437b25 --- /dev/null +++ b/lib/date/patterns.rb @@ -0,0 +1,403 @@ +# frozen_string_literal: true + +class Date + # TIME_PAT + # Regular expression pattern for C's parse_time. + # $1: entire time portion + # $2: time zone portion (optional) + # + # In the zone portion, [A-Za-z] is used for case-sensitive alphabetic characters. + TIME_PAT = / + ( # $1: whole time + \d+\s* # hour (required) + (?: + (?: # Branch A: colon-separated + :\s*\d+ # :min + (?: + \s*:\s*\d+(?:[,.]\d*)? # :sec[.frac] + )? + | # Branch B: h m s separated + h(?:\s*\d+m? + (?:\s*\d+s?)? + )? + ) + (?: # AM PM suffix (optional) + \s*[ap](?:m\b|\.m\.) + )? + | # Branch C: Only AM PM + [ap](?:m\b|\.m\.) + ) + ) + (?: # Time Zone (optional) + \s* + ( # $2: time zone + (?:gmt|utc?)?[-+]\d+ + (?:[,.:]\d+(?::\d+)?)? + | + [[:alpha:].\s]+ + (?:standard|daylight)\stime\b + | + [[:alpha:]]+(?:\sdst)?\b + ) + )? + /xi + private_constant :TIME_PAT + + # TIME_DETAIL_PAT + # Pattern for detailed parsing of time portion + TIME_DETAIL_PAT = / + \A(\d+)\s* # $1 hour + (?: + :\s*(\d+) # $2 min (colon) + (?:\s*:\s*(\d+)([,.]\d*)?)? # $3 sec, $4 frac (colon) + | + h(?:\s*(\d+)m? # $5 min (h) + (?:\s*(\d+)s?)? # $6 sec (h) + )? + )? + (?:\s*([ap])(?:m\b|\.m\.))? # $7 am pm + /xi + private_constant :TIME_DETAIL_PAT + + # PARSE_DAY_PAT + # Non-TIGHT pattern for parse_day. + # Matches abbreviated day name and consumes trailing characters + # (e.g., "urday" in "Saturday") so they get replaced by subx. + PARSE_DAY_PAT = /\b(sun|mon|tue|wed|thu|fri|sat)[^-\/\d\s]*/i + private_constant :PARSE_DAY_PAT + + # ERA1_PAT + # Pattern for AD, A.D. + ERA1_PAT = /\b(a(?:d\b|\.d\.))(?!(? string + # + # Returns a string representation of the date in +self+, + # formatted according the given +format+: + # + # Date.new(2001, 2, 3).strftime # => "2001-02-03" + # + # For other formats, see + # {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]. + def strftime(format = STRFTIME_DEFAULT_FMT) + # If format is not a string, convert it to a string. + format = format.to_str unless format.is_a?(String) + + # Check for ASCII compatible encoding. + raise ArgumentError, "format should have ASCII compatible encoding" unless format.encoding.ascii_compatible? + + # Empty format returns empty string + return '' if format.empty? + + # What to do if format string contains a "\0". + if format.include?("\0") + result = String.new + parts = format.split("\0", -1) + + parts.each_with_index do |part, i| + result << strftime_format(part) unless part.empty? + result << "\0" if i < parts.length - 1 + end + + result.force_encoding(format.encoding) + + return result + end + + # Normal processing without "\0" in format string. + result = strftime_format(format) + result.force_encoding(format.encoding) + + result + end + + private + + def tmx_year + m_real_year + end + + def tmx_mon + mon + end + + def tmx_mday + mday + end + + def tmx_yday + yday + end + + def tmx_cwyear + m_real_cwyear + end + + def tmx_cweek + cweek + end + + def tmx_cwday + cwday + end + + def tmx_wday + wday + end + + def tmx_wnum0 + # Week number (Sunday start, 00-53) + m_wnumx(0) + end + + def tmx_wnum1 + # Week number (Monday start, 00-53) + m_wnumx(1) + end + + def tmx_hour + if simple_dat_p? + 0 + else + df = df_utc_to_local(m_df, m_of) + (df / 3600).floor + end + end + + def tmx_min + if simple_dat_p? + 0 + else + df = df_utc_to_local(m_df, m_of) + ((df % 3600) / 60).floor + end + end + + def tmx_sec + if simple_dat_p? + 0 + else + df = df_utc_to_local(m_df, m_of) + df % 60 + end + end + + def tmx_sec_fraction + if simple_dat_p? + Rational(0, 1) + else + # (Decimal part of df) + sf + df_frac = m_df - m_df.floor + sf_frac = m_sf == 0 ? 0 : Rational(m_sf, SECOND_IN_NANOSECONDS) + df_frac + sf_frac + end + end + + def tmx_secs + # C: tmx_m_secs (date_core.c:7306) + # s = day_to_sec(m_real_jd - UNIX_EPOCH_IN_CJD) + # if complex: s += m_df + s = jd_to_unix_time(m_real_jd) + return s if simple_dat_p? + df = m_df + s += df if df != 0 + s + end + + def tmx_msecs + # C: tmx_m_msecs (date_core.c:7322) + # s = tmx_m_secs * 1000 + # if complex: s += m_sf / MILLISECOND_IN_NANOSECONDS + s = tmx_secs * SECOND_IN_MILLISECONDS + return s if simple_dat_p? + sf = m_sf + s += (sf / (SECOND_IN_NANOSECONDS / SECOND_IN_MILLISECONDS)).to_i if sf != 0 + s + end + + def tmx_offset + simple_dat_p? ? 0 : m_of + end + + def tmx_zone + if simple_dat_p? || tmx_offset.zero? + "+00:00" + else + of2str(m_of) + end + end + + def of2str(of) + s, h, m = decode_offset(of) + sprintf('%c%02d:%02d', s, h, m) + end + + def decode_offset(of) + s = (of < 0) ? '-' : '+' + a = of.abs + h = a / HOUR_IN_SECONDS + m = (a % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS + [s, h, m] + end + + # Processing format strings. + def strftime_format(format) + result = String.new + i = 0 + + while i < format.length + if format[i] == '%' && i + 1 < format.length + # Skip '%' + i += 1 + + # C: Parse all modifiers in a flat loop (flags, width, colons, E/O) + flags = String.new + width = String.new + modifier = nil + colons = 0 + + while i < format.length + c = format[i] + case c + when 'E', 'O' + modifier = c + i += 1 + when ':' + colons += 1 + i += 1 + when '-', '_', '^', '#' + flags << c + i += 1 + when '0' + # '0' is a flag only when width is still empty + if width.empty? + flags << c + i += 1 + else + width << c + i += 1 + end + when /[1-9]/ + width << c + i += 1 + # Continue reading remaining digits + while i < format.length && format[i] =~ /[0-9]/ + width << format[i] + i += 1 + end + else + break + end + end + + # Invalid if both E/O and colon modifiers are present. + if modifier && colons > 0 + if i < format.length + spec = format[i] + result << "%#{modifier}#{':' * colons}#{spec}" + i += 1 + end + next + end + + # Width specifier overflow check + unless width.empty? + if width.length > 10 || (width.length == 10 && width > '2147483647') + raise Errno::ERANGE, "Result too large" + end + if width.to_i >= 1024 + raise Errno::ERANGE, "Result too large" + end + end + + if i < format.length + spec = format[i] + + if modifier + # E/O modifier check must come first + valid = case modifier + when 'E' + %w[c C x X y Y].include?(spec) + when 'O' + %w[d e H k I l m M S u U V w W y].include?(spec) + else + false + end + + if valid + formatted = format_spec(spec, flags, width) + result << formatted + else + result << "%#{modifier}#{flags}#{width}#{spec}" + end + elsif spec == 'z' + # %z with any combination of colons/width/flags + formatted = format_z(tmx_offset, width, flags, colons) + result << formatted + elsif colons > 0 + # Colon modifier is only valid for 'z'. + result << "%#{':' * colons}#{flags}#{width}#{spec}" + else + formatted = format_spec(spec, flags, width) + result << formatted + end + + i += 1 + end + else + result << format[i] + i += 1 + end + end + + result.force_encoding('US-ASCII') if result.ascii_only? + + result + end + + def format_spec(spec, flags = '', width = '') + # N/L: width controls precision (number of fractional digits) + if spec == 'N' || spec == 'L' + precision = if !width.empty? + width.to_i + elsif spec == 'L' + 3 + else + 9 + end + frac = tmx_sec_fraction + digits = (frac * (10 ** precision)).floor + return sprintf("%0#{precision}d", digits) + end + + # Get basic formatting results. + base_result = get_base_format(spec, flags) + + # Apply case change flags (before width/precision) + base_result = apply_case_flags(base_result, spec, flags) + + # Apply width specifier. + if !width.empty? + width_num = width.to_i + default_pad = if NUMERIC_SPECS.include?(spec) + '0' + elsif SPACE_PAD_SPECS.include?(spec) + ' ' + else + ' ' + end + apply_width(base_result, width_num, flags, default_pad) + else + base_result + end + end + + # C: Apply ^ (UPPER) and # (CHCASE) flags + def apply_case_flags(str, spec, flags) + if flags.include?('^') + str.upcase + elsif flags.include?('#') + if CHCASE_UPPER_SPECS.include?(spec) + str.upcase + elsif CHCASE_LOWER_SPECS.include?(spec) + str.downcase + else + str.swapcase + end + else + str + end + end + + # format specifiers + def get_base_format(spec, flags = '') + case spec + when 'Y' # 4-digit year + y = tmx_year + raise Errno::ERANGE, "Result too large" if y.is_a?(Integer) && y.bit_length > 128 + # C: FMT('0', y >= 0 ? 4 : 5, "ld", y) + prec = y < 0 ? 5 : 4 + if flags.include?('-') + y.to_s + elsif flags.include?('_') + sprintf("%#{prec}d", y) + else + sprintf("%0#{prec}d", y) + end + when 'C' # Century + sprintf('%02d', tmx_year / 100) + when 'y' # Two-digit year + sprintf('%02d', tmx_year % 100) + when 'm' # Month (01-12) + sprintf('%02d', tmx_mon) + when 'B' # Full month name + MONTHNAMES[tmx_mon] || '?' + when 'b', 'h' # Abbreviated month name + (ABBR_MONTHNAMES[tmx_mon] || '?')[0, 3] + when 'd' # Day (01-31) + if flags.include?('-') + # Left-justified (no padding) + tmx_mday.to_s + elsif flags.include?('_') + # Space-padded + sprintf('%2d', tmx_mday) + else + # Zero-padded (default) + sprintf('%02d', tmx_mday) + end + when 'e' # Day (1-31) blank filled + if flags.include?('-') + tmx_mday.to_s + elsif flags.include?('0') + sprintf('%02d', tmx_mday) + else + sprintf('%2d', tmx_mday) + end + when 'j' # Day of the year (001-366) + if flags.include?('-') + tmx_yday.to_s + else + sprintf('%03d', tmx_yday) + end + when 'H' # Hour (00-23) + if flags.include?('-') + tmx_hour.to_s + elsif flags.include?('_') + sprintf('%2d', tmx_hour) + else + sprintf('%02d', tmx_hour) + end + when 'k' # Hour (0-23) blank-padded + sprintf('%2d', tmx_hour) + when 'I' # Hour (01-12) + h = tmx_hour % 12 + h = 12 if h.zero? + if flags.include?('-') + h.to_s + elsif flags.include?('_') + sprintf('%2d', h) + else + sprintf('%02d', h) + end + when 'l' # Hour (1-12) blank filled + h = tmx_hour % 12 + h = 12 if h.zero? + sprintf('%2d', h) + when 'M' # Minutes (00-59) + if flags.include?('-') + tmx_min.to_s + elsif flags.include?('_') + sprintf('%2d', tmx_min) + else + sprintf('%02d', tmx_min) + end + when 'S' # Seconds (00-59) + if flags.include?('-') + tmx_sec.to_s + elsif flags.include?('_') + sprintf('%2d', tmx_sec) + else + sprintf('%02d', tmx_sec) + end + when 'L' # Milliseconds (000-999) + sprintf('%09d', (tmx_sec_fraction * 1_000_000_000).floor) + when 'N' # Fractional seconds digits + # C: width controls precision (number of digits), default 9. + # %3N → 3 digits (milliseconds), %6N → 6 digits (microseconds), + # %9N → 9 digits (nanoseconds), %12N → 12 digits (picoseconds, zero-padded). + # The 'width' variable is handled specially in format_spec for 'N'. + sprintf('%09d', (tmx_sec_fraction * 1_000_000_000).floor) + when 'P' # am/pm + tmx_hour < 12 ? 'am' : 'pm' + when 'p' # AM/PM + tmx_hour < 12 ? 'AM' : 'PM' + when 'A' # Full name of the day of the week + DAYNAMES[tmx_wday] || '?' + when 'a' # Abbreviated day of the week + (ABBR_DAYNAMES[tmx_wday] || '?')[0, 3] + when 'w' # Day of the week (0-6, Sunday is 0) + tmx_wday.to_s + when 'u' # Day of the week (1-7, Monday is 1) + tmx_cwday.to_s + when 'U' # Week number (00-53, Sunday start) + sprintf('%02d', tmx_wnum0) + when 'W' # Week number (00-53, Monday start) + sprintf('%02d', tmx_wnum1) + when 'V' # ISO week number (01-53) + sprintf('%02d', tmx_cweek) + when 'G' # ISO week year + y = tmx_cwyear + prec = y < 0 ? 5 : 4 + if flags.include?('-') + y.to_s + elsif flags.include?('_') + sprintf("%#{prec}d", y) + else + sprintf("%0#{prec}d", y) + end + when 'g' # ISO week year (2 digits) + sprintf('%02d', tmx_cwyear % 100) + when 'z' # Time Zone Offset (+0900) — handled by format_z in format_spec + format_z(tmx_offset, '', '', 0) + when 'Z' # Time Zone Name + tmx_zone || '' + when 's' # Number of seconds since the Unix epoch + tmx_secs.to_s + when 'Q' # Milliseconds since the Unix epoch + tmx_msecs.to_s + when 'n' # Line breaks + "\n" + when 't' # Tab + "\t" + when '%' # % symbol + '%' + when 'F' # %Y-%m-%d + strftime_format('%Y-%m-%d') + when 'D' # %m/%d/%y + strftime_format('%m/%d/%y') + when 'x' # %m/%d/%y + strftime_format('%m/%d/%y') + when 'T', 'X' # %H:%M:%S + strftime_format('%H:%M:%S') + when 'R' # %H:%M + strftime_format('%H:%M') + when 'r' # %I:%M:%S %p + strftime_format('%I:%M:%S %p') + when 'c' # %a %b %e %H:%M:%S %Y + strftime_format('%a %b %e %H:%M:%S %Y') + when 'v' # %e-%^b-%Y (3-FEB-2001 format) + day_str = sprintf('%2d', tmx_mday) + month_str = (ABBR_MONTHNAMES[tmx_mon] || '?')[0, 3].upcase + year_str = sprintf('%04d', tmx_year) + "#{day_str}-#{month_str}-#{year_str}" + when '+' # %a %b %e %H:%M:%S %Z %Y + strftime_format('%a %b %e %H:%M:%S %Z %Y') + else + # Unknown specifiers are output as is. + "%#{spec}" + end + end + + def apply_width(str, width, flags, default_pad = ' ') + # '-' flag means no padding at all + return str if flags.include?('-') + return str if str.length >= width + + # Determine a padding character. + padding = + if flags.include?('0') + '0' + elsif flags.include?('_') + ' ' + else + default_pad + end + + str.rjust(width, padding) + end + + # C: format %z with width/flags/colons support + # Matches date_strftime.c case 'z' logic exactly. + def format_z(offset, width_str, flags, colons) + sign = offset < 0 ? '-' : '+' + aoff = offset.abs + hours = aoff / 3600 + minutes = (aoff % 3600) / 60 + seconds = aoff % 60 + + hl = hours < 10 ? 1 : 2 # actual digits needed for hours + hw = 2 # default hour width + hw = 1 if flags.include?('-') && hl == 1 + + precision = width_str.empty? ? -1 : width_str.to_i + + # Calculate fixed chars (everything except hour digits) per colons variant + fixed = case colons + when 0 then 3 # sign(1) + mm(2) + when 1 then 4 # sign(1) + :(1) + mm(2) + when 2 then 7 # sign(1) + :(1) + mm(2) + :(1) + ss(2) + when 3 + if (aoff % 3600).zero? + 1 # sign(1) only + elsif (aoff % 60).zero? + 4 # sign(1) + :(1) + mm(2) + else + 7 # sign(1) + :(1) + mm(2) + :(1) + ss(2) + end + else + 3 + end + + # C: hour_precision = precision <= (fixed + hw) ? hw : precision - fixed + hp = precision <= (fixed + hw) ? hw : precision - fixed + + result = String.new + + # C: space padding — print spaces before sign, reduce hour precision + if flags.include?('_') && hp > hl + result << ' ' * (hp - hl) + hp = hl + end + + result << sign + result << sprintf("%0#{hp}d", hours) + + # Append minutes/seconds based on colons + case colons + when 0 + result << sprintf('%02d', minutes) + when 1 + result << sprintf(':%02d', minutes) + when 2 + result << sprintf(':%02d:%02d', minutes, seconds) + when 3 + unless (aoff % 3600).zero? + result << sprintf(':%02d', minutes) + unless (aoff % 60).zero? + result << sprintf(':%02d', seconds) + end + end + end + + result + end + + def jd_to_unix_time(jd) + unix_epoch_jd = 2440588 + (jd - unix_epoch_jd) * DAY_IN_SECONDS + end +end diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb new file mode 100644 index 00000000..e73bfc55 --- /dev/null +++ b/lib/date/strptime.rb @@ -0,0 +1,769 @@ +# frozen_string_literal: true + +# Implementation of ruby/date/ext/date/date_strptime.c +class Date + class << self + # call-seq: + # Date._strptime(string, format = '%F') -> hash + # + # Returns a hash of values parsed from +string+ + # according to the given +format+: + # + # Date._strptime('2001-02-03', '%Y-%m-%d') # => {:year=>2001, :mon=>2, :mday=>3} + # + # For other formats, see + # {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]. + # (Unlike Date.strftime, does not support flags and width.) + # + # See also {strptime(3)}[https://man7.org/linux/man-pages/man3/strptime.3.html]. + # + # Related: Date.strptime (returns a \Date object). + def _strptime(string, format = '%F') + str = string.dup + pos = 0 + hash = {} + + i = 0 + while i < format.length + if format[i] == '%' && i + 1 < format.length + i += 1 + + # Parse modifier (E, O) + modifier = nil + if i < format.length && (format[i] == 'E' || format[i] == 'O') + modifier = format[i] + i += 1 + end + + # Parse colons for %:z, %::z, %:::z + colons = 0 + while i < format.length && format[i] == ':' + colons += 1 + i += 1 + end + + # Parse width + width_str = String.new + while i < format.length && format[i] =~ /[0-9]/ + width_str << format[i] + i += 1 + end + + break if i >= format.length + + spec = format[i] + i += 1 + + # Handle E/O modifier validity + if modifier + valid = case modifier + when 'E' + %w[c C x X y Y].include?(spec) + when 'O' + %w[d e H I m M S u U V w W y].include?(spec) + else + false + end + unless valid + # Invalid modifier - try to match literal + literal = "%#{modifier}#{':' * colons}#{width_str}#{spec}" + if str[pos, literal.length] == literal + pos += literal.length + else + return nil + end + next + end + end + + # Handle colon+z + if colons > 0 && spec == 'z' + result = _strptime_zone_colon(str, pos, colons) + return nil unless result + pos = result[:pos] + hash[:zone] = result[:zone] + hash[:offset] = result[:offset] + next + elsif colons > 0 + # Invalid colon usage + return nil + end + + # Determine field width + field_width = width_str.empty? ? nil : width_str.to_i + + # C: NUM_PATTERN_P() - check if next format element is a digit-consuming pattern. + # Used by %C, %G, %L, %N, %Y to limit digit consumption when adjacent. + next_is_num = num_pattern_p(format, i) + + result = _strptime_spec(str, pos, spec, field_width, hash, next_is_num) + return nil unless result + pos = result[:pos] + hash.merge!(result[:hash]) if result[:hash] + elsif format[i] == '%' && i + 1 == format.length + # Trailing % - match literal + if pos < str.length && str[pos] == '%' + pos += 1 + else + return nil + end + i += 1 + elsif format[i] =~ /\s/ + # Whitespace in format matches zero or more whitespace in input + i += 1 + pos += 1 while pos < str.length && str[pos] =~ /\s/ + else + # Literal match + if pos < str.length && str[pos] == format[i] + pos += 1 + else + return nil + end + i += 1 + end + end + + # Store leftover if any + if pos < str.length + hash[:leftover] = str[pos..] + end + + # --- Post-processing (C: date__strptime, date_strptime.c:524-546) --- + + # C: cent = del_hash("_cent"); + # Apply _cent to both cwyear and year. + # Note: The inline _century approach in %C/%y/%g handlers covers most + # cases, but this post-processing ensures correctness for all orderings + # and applies century to both year and cwyear simultaneously. + # We delete _century and _century_set here to keep the hash clean, + # matching C's del_hash("_cent") behavior. + hash.delete(:_century) + hash.delete(:_century_set) + + # C: merid = del_hash("_merid"); + # Apply _merid to hour: hour = (hour % 12) + merid + # This handles both %I (12-hour) and %H (24-hour) correctly: + # %I=12 + AM(0) → (12 % 12) + 0 = 0 + # %I=12 + PM(12) → (12 % 12) + 12 = 12 + # %I=4 + PM(12) → (4 % 12) + 12 = 16 + # %I=4 + AM(0) → (4 % 12) + 0 = 4 + merid = hash.delete(:_merid) + if merid + hour = hash[:hour] + if hour + hash[:hour] = (hour % 12) + merid + end + end + + hash + end + + # call-seq: + # Date.strptime(string = '-4712-01-01', format = '%F', start = Date::ITALY) -> date + # + # Returns a new \Date object with values parsed from +string+, + # according to the given +format+: + # + # Date.strptime('2001-02-03', '%Y-%m-%d') # => # + # Date.strptime('03-02-2001', '%d-%m-%Y') # => # + # Date.strptime('2001-034', '%Y-%j') # => # + # Date.strptime('2001-W05-6', '%G-W%V-%u') # => # + # Date.strptime('2001 04 6', '%Y %U %w') # => # + # Date.strptime('2001 05 6', '%Y %W %u') # => # + # Date.strptime('sat3feb01', '%a%d%b%y') # => # + # + # For other formats, see + # {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]. + # (Unlike Date.strftime, does not support flags and width.) + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # + # See also {strptime(3)}[https://man7.org/linux/man-pages/man3/strptime.3.html]. + # + # Related: Date._strptime (returns a hash). + def strptime(string = JULIAN_EPOCH_DATE, format = '%F', start = DEFAULT_SG) + hash = _strptime(string, format) + raise Error, "invalid strptime format - `#{format}'" unless hash + + # Apply comp for 2-digit year + if hash[:year] && !hash[:_century_set] + # If year came from %y (2-digit), comp_year69 was already applied + end + + new_by_frags(hash, start) + end + + private + + # C: num_pattern_p (date_strptime.c:48) + # Returns true if the format string at position `i` starts with a + # digit-consuming pattern (a literal digit or a %-specifier that reads digits). + def num_pattern_p(format, i) + return false if i >= format.length + c = format[i] + return true if c =~ /\d/ + if c == '%' + i += 1 + return false if i >= format.length + # Skip E/O modifier + if format[i] == 'E' || format[i] == 'O' + i += 1 + return false if i >= format.length + end + s = format[i] + return true if s =~ /\d/ || NUM_PATTERN_SPECS.include?(s) + end + false + end + + def _strptime_spec(str, pos, spec, width, context_hash, next_is_num = false) + h = {} + + case spec + when 'Y' # Full year (possibly negative) + # C: if (NUM_PATTERN_P()) READ_DIGITS(n, 4); else READ_DIGITS_MAX(n); + if width + w = width + elsif next_is_num + w = 4 + else + w = 40 # effectively unlimited + end + m = str[pos..].match(/\A([+-]?\d{1,#{w}})/) + return nil unless m + h[:year] = m[1].to_i + { pos: pos + m[0].length, hash: h } + + when 'C' # Century + # C: if (NUM_PATTERN_P()) READ_DIGITS(n, 2); else READ_DIGITS_MAX(n); + if width + w = width + elsif next_is_num + w = 2 + else + w = 40 + end + m = str[pos..].match(/\A([+-]?\d{1,#{w}})/) + return nil unless m + century = m[1].to_i + h[:_century] = century + if context_hash[:year] && !context_hash[:_century_set] + h[:year] = century * 100 + (context_hash[:year] % 100) + h[:_century_set] = true + end + { pos: pos + m[0].length, hash: h } + + when 'y' # 2-digit year + w = width || 2 + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + y = m[1].to_i + if context_hash[:_century] + h[:year] = context_hash[:_century] * 100 + y + h[:_century_set] = true + else + h[:year] = y >= 69 ? y + 1900 : y + 2000 + end + { pos: pos + m[0].length, hash: h } + + when 'm' # Month (01-12) + w = width || 2 + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + mon = m[1].to_i + return nil if mon < 1 || mon > 12 + h[:mon] = mon + { pos: pos + m[0].length, hash: h } + + when 'd', 'e' # Day of month + # C: if (str[si] == ' ') { si++; READ_DIGITS(n, 1); } else { READ_DIGITS(n, 2); } + if str[pos] == ' ' + m = str[pos + 1..].match(/\A(\d)/) + return nil unless m + day = m[1].to_i + return nil if day < 1 || day > 31 + h[:mday] = day + { pos: pos + 1 + m[0].length, hash: h } + else + w = width || 2 + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + day = m[1].to_i + return nil if day < 1 || day > 31 + h[:mday] = day + { pos: pos + m[0].length, hash: h } + end + + when 'j' # Day of year (001-366) + w = width || 3 + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + yday = m[1].to_i + return nil if yday < 1 || yday > 366 + h[:yday] = yday + { pos: pos + m[0].length, hash: h } + + when 'H', 'k' # Hour (00-24) + # C: if (str[si] == ' ') { si++; READ_DIGITS(n, 1); } else { READ_DIGITS(n, 2); } + if str[pos] == ' ' + m = str[pos + 1..].match(/\A(\d)/) + return nil unless m + hour = m[1].to_i + return nil if hour > 24 + h[:hour] = hour + { pos: pos + 1 + m[0].length, hash: h } + else + w = width || 2 + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + hour = m[1].to_i + return nil if hour > 24 + h[:hour] = hour + { pos: pos + m[0].length, hash: h } + end + + when 'I', 'l' # Hour (01-12) + # C: if (str[si] == ' ') { si++; READ_DIGITS(n, 1); } else { READ_DIGITS(n, 2); } + if str[pos] == ' ' + m = str[pos + 1..].match(/\A(\d)/) + return nil unless m + hour = m[1].to_i + return nil if hour < 1 || hour > 12 + h[:hour] = hour + { pos: pos + 1 + m[0].length, hash: h } + else + w = width || 2 + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + hour = m[1].to_i + return nil if hour < 1 || hour > 12 + h[:hour] = hour # C stores raw value; _merid post-processing applies % 12 + { pos: pos + m[0].length, hash: h } + end + + when 'M' # Minute (00-59) + w = width || 2 + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + min = m[1].to_i + return nil if min > 59 + h[:min] = min + { pos: pos + m[0].length, hash: h } + + when 'S' # Second (00-60) + w = width || 2 + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + sec = m[1].to_i + return nil if sec > 60 + h[:sec] = sec + { pos: pos + m[0].length, hash: h } + + when 'L' # Milliseconds + # C: if (NUM_PATTERN_P()) READ_DIGITS(n, 3); else READ_DIGITS_MAX(n); + if width + w = width + elsif next_is_num + w = 3 + else + w = 40 + end + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + frac_str = m[1].ljust(3, '0')[0, 3] + h[:sec_fraction] = Rational(frac_str.to_i, 1000) + { pos: pos + m[0].length, hash: h } + + when 'N' # Nanoseconds + # C: if (NUM_PATTERN_P()) READ_DIGITS(n, 9); else READ_DIGITS_MAX(n); + if width + w = width + elsif next_is_num + w = 9 + else + w = 40 + end + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + frac_str = m[1].ljust(9, '0')[0, 9] + h[:sec_fraction] = Rational(frac_str.to_i, 1_000_000_000) + { pos: pos + m[0].length, hash: h } + + when 'p', 'P' # AM/PM + # C: set_hash("_merid", INT2FIX(hour)); + # Store _merid value (0 for AM, 12 for PM) for post-processing. + # This avoids order-dependency: %p can appear before or after %I/%H. + m = str[pos..].match(/\A(a\.?m\.?|p\.?m\.?)/i) + return nil unless m + ampm = m[1].delete('.').upcase + h[:_merid] = (ampm == 'PM') ? 12 : 0 + { pos: pos + m[0].length, hash: h } + + when 'A', 'a' # Day name (full or abbreviated) + DAYNAMES.each_with_index do |name, idx| + next unless name + # Try full name first, then abbreviated + [name, ABBR_DAYNAMES[idx]].each do |n| + next unless n + if str[pos, n.length]&.downcase == n.downcase + h[:wday] = idx + return { pos: pos + n.length, hash: h } + end + end + end + return nil + + when 'B', 'b', 'h' # Month name (full or abbreviated) + MONTHNAMES.each_with_index do |name, idx| + next unless name + # Try full name first, then abbreviated + [name, ABBR_MONTHNAMES[idx]].each do |n| + next unless n + if str[pos, n.length]&.downcase == n.downcase + h[:mon] = idx + return { pos: pos + n.length, hash: h } + end + end + end + return nil + + when 'w' # Weekday number (0-6, Sunday=0) + m = str[pos..].match(/\A(\d)/) + return nil unless m + wday = m[1].to_i + return nil if wday > 6 + h[:wday] = wday + { pos: pos + m[0].length, hash: h } + + when 'u' # Weekday number (1-7, Monday=1) + m = str[pos..].match(/\A(\d)/) + return nil unless m + cwday = m[1].to_i + return nil if cwday < 1 || cwday > 7 + h[:cwday] = cwday + { pos: pos + m[0].length, hash: h } + + when 'U' # Week number (Sunday start, 00-53) + w = width || 2 + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + wnum = m[1].to_i + return nil if wnum > 53 + h[:wnum0] = wnum + { pos: pos + m[0].length, hash: h } + + when 'W' # Week number (Monday start, 00-53) + w = width || 2 + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + wnum = m[1].to_i + return nil if wnum > 53 + h[:wnum1] = wnum + { pos: pos + m[0].length, hash: h } + + when 'V' # ISO week number (01-53) + w = width || 2 + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + cweek = m[1].to_i + return nil if cweek < 1 || cweek > 53 + h[:cweek] = cweek + { pos: pos + m[0].length, hash: h } + + when 'G' # ISO week year + # C: if (NUM_PATTERN_P()) READ_DIGITS(n, 4); else READ_DIGITS_MAX(n); + if width + w = width + elsif next_is_num + w = 4 + else + w = 40 + end + m = str[pos..].match(/\A([+-]?\d{1,#{w}})/) + return nil unless m + h[:cwyear] = m[1].to_i + { pos: pos + m[0].length, hash: h } + + when 'g' # ISO week year (2-digit) + w = width || 2 + m = str[pos..].match(/\A(\d{1,#{w}})/) + return nil unless m + y = m[1].to_i + if context_hash[:_century] + h[:cwyear] = context_hash[:_century] * 100 + y + h[:_century_set] = true + else + h[:cwyear] = y >= 69 ? y + 1900 : y + 2000 + end + { pos: pos + m[0].length, hash: h } + + when 'Z', 'z' # Timezone + result = _strptime_zone(str, pos) + return nil unless result + h[:zone] = result[:zone] + h[:offset] = result[:offset] unless result[:offset].nil? + { pos: result[:pos], hash: h } + + when 's' # Seconds since epoch + m = str[pos..].match(/\A([+-]?\d+)/) + return nil unless m + h[:seconds] = m[1].to_i + { pos: pos + m[0].length, hash: h } + + when 'Q' # Milliseconds since epoch + m = str[pos..].match(/\A([+-]?\d+)/) + return nil unless m + h[:seconds] = Rational(m[1].to_i, 1000) + { pos: pos + m[0].length, hash: h } + + when 'n' # Newline + m = str[pos..].match(/\A\s+/) + if m + { pos: pos + m[0].length, hash: h } + else + { pos: pos, hash: h } + end + + when 't' # Tab + m = str[pos..].match(/\A\s+/) + if m + { pos: pos + m[0].length, hash: h } + else + { pos: pos, hash: h } + end + + when '%' # Literal % + if pos < str.length && str[pos] == '%' + { pos: pos + 1, hash: h } + else + return nil + end + + when 'F' # %Y-%m-%d + result = _strptime_composite(str, pos, '%Y-%m-%d', context_hash) + return nil unless result + { pos: result[:pos], hash: result[:hash] } + + when 'D', 'x' # %m/%d/%y + result = _strptime_composite(str, pos, '%m/%d/%y', context_hash) + return nil unless result + { pos: result[:pos], hash: result[:hash] } + + when 'T', 'X' # %H:%M:%S + result = _strptime_composite(str, pos, '%H:%M:%S', context_hash) + return nil unless result + { pos: result[:pos], hash: result[:hash] } + + when 'R' # %H:%M + result = _strptime_composite(str, pos, '%H:%M', context_hash) + return nil unless result + { pos: result[:pos], hash: result[:hash] } + + when 'r' # %I:%M:%S %p + result = _strptime_composite(str, pos, '%I:%M:%S %p', context_hash) + return nil unless result + { pos: result[:pos], hash: result[:hash] } + + when 'c' # %a %b %e %H:%M:%S %Y + result = _strptime_composite(str, pos, '%a %b %e %H:%M:%S %Y', context_hash) + return nil unless result + { pos: result[:pos], hash: result[:hash] } + + when 'v' # %e-%b-%Y + result = _strptime_composite(str, pos, '%e-%b-%Y', context_hash) + return nil unless result + { pos: result[:pos], hash: result[:hash] } + + when '+' # %a %b %e %H:%M:%S %Z %Y + result = _strptime_composite(str, pos, '%a %b %e %H:%M:%S %Z %Y', context_hash) + return nil unless result + { pos: result[:pos], hash: result[:hash] } + + else + # Unknown specifier - try to match literal + literal = "%#{spec}" + if str[pos, literal.length] == literal + { pos: pos + literal.length, hash: h } + else + return nil + end + end + end + + def _strptime_composite(str, pos, format, context_hash) + merged_hash = context_hash.dup + i = 0 + while i < format.length + if format[i] == '%' && i + 1 < format.length + i += 1 + spec = format[i] + i += 1 + result = _strptime_spec(str, pos, spec, nil, merged_hash) + return nil unless result + pos = result[:pos] + merged_hash.merge!(result[:hash]) if result[:hash] + elsif format[i] =~ /\s/ + i += 1 + pos += 1 while pos < str.length && str[pos] =~ /\s/ + else + if pos < str.length && str[pos] == format[i] + pos += 1 + else + return nil + end + i += 1 + end + end + # Return only newly parsed keys + new_hash = {} + merged_hash.each { |k, v| new_hash[k] = v unless context_hash.key?(k) && context_hash[k] == v } + # Ensure updated values are included + merged_hash.each { |k, v| new_hash[k] = v if context_hash[k] != v } + { pos: pos, hash: new_hash } + end + + def _strptime_zone(str, pos) + remaining = str[pos..] + return nil if remaining.nil? || remaining.empty? + + # Try numeric timezone: +HH:MM, -HH:MM, +HH:MM:SS, -HH:MM:SS, +HHMM, -HHMM, +HH, -HH + # Also: GMT+HH, GMT-HH:MM, etc. and decimal offsets + # Colon-separated pattern (requires colon) tried first, then plain digits. + m = remaining.match(/\A( + (?:GMT|UTC)? + [+-] + (?:\d{1,2}:\d{2}(?::\d{2})? + | + \d+(?:[.,]\d+)?) + )/xi) + + if m + zone_str = m[1] + offset = _parse_zone_offset(zone_str) + return { pos: pos + zone_str.length, zone: zone_str, offset: offset } + end + + # Try named timezone (multi-word: "E. Australia Standard Time", "Mountain Daylight Time") + # Match alphabetic words with dots and spaces + m = remaining.match(/\A([A-Za-z][A-Za-z.]*(?:\s+[A-Za-z][A-Za-z.]*)*)/i) + if m + zone_candidate = m[1] + # Try progressively shorter matches (longest first) + words = zone_candidate.split(/\s+/) + (words.length).downto(1) do |n| + try_zone = words[0, n].join(' ') + offset = _zone_name_to_offset(try_zone) + if offset + # Compute actual consumed length preserving original spacing + if n == words.length + actual_zone = zone_candidate + else + # Find end of nth word in original string + end_pos = 0 + n.times do |wi| + end_pos = zone_candidate.index(words[wi], end_pos) + end_pos += words[wi].length + end + actual_zone = zone_candidate[0, end_pos] + end + return { pos: pos + actual_zone.length, zone: actual_zone, offset: offset } + end + end + # Unknown timezone - return full match with nil offset + # (Military single-letter zones like 'z' are already in ZONE_TABLE + # and handled by the loop above) + return { pos: pos + zone_candidate.length, zone: zone_candidate, offset: nil } + end + + nil + end + + def _strptime_zone_colon(str, pos, colons) + remaining = str[pos..] + return nil if remaining.nil? || remaining.empty? + + case colons + when 1 # %:z -> +HH:MM + m = remaining.match(/\A([+-])(\d{2}):(\d{2})/) + return nil unless m + sign = m[1] == '-' ? -1 : 1 + offset = sign * (m[2].to_i * 3600 + m[3].to_i * 60) + zone = m[0] + { pos: pos + zone.length, zone: zone, offset: offset } + when 2 # %::z -> +HH:MM:SS + m = remaining.match(/\A([+-])(\d{2}):(\d{2}):(\d{2})/) + return nil unless m + sign = m[1] == '-' ? -1 : 1 + offset = sign * (m[2].to_i * 3600 + m[3].to_i * 60 + m[4].to_i) + zone = m[0] + { pos: pos + zone.length, zone: zone, offset: offset } + when 3 # %:::z -> +HH[:MM[:SS]] + m = remaining.match(/\A([+-])(\d{2})(?::(\d{2})(?::(\d{2}))?)?/) + return nil unless m + sign = m[1] == '-' ? -1 : 1 + offset = sign * (m[2].to_i * 3600 + (m[3] ? m[3].to_i * 60 : 0) + (m[4] ? m[4].to_i : 0)) + zone = m[0] + { pos: pos + zone.length, zone: zone, offset: offset } + else + nil + end + end + + def _parse_zone_offset(zone_str) + # Strip GMT/UTC prefix + s = zone_str.sub(/\A(?:GMT|UTC)/i, '') + return 0 if s.empty? + + m = s.match(/\A([+-])(\d+(?:[.,]\d+)?)$/) + if m + sign = m[1] == '-' ? -1 : 1 + num = m[2].tr(',', '.') + if num.include?('.') + # Decimal hours + hours = num.to_f + return nil if hours.abs >= 24 + return sign * (hours * 3600).to_i + else + # Could be HH, HHMM, or HHMMSS + digits = num + case digits.length + when 1, 2 + h = digits.to_i + return nil if h >= 24 + return sign * h * 3600 + when 3, 4 + h = digits[0, 2].to_i + min = digits[2, 2].to_i + return nil if h >= 24 || min >= 60 + return sign * (h * 3600 + min * 60) + when 5, 6 + h = digits[0, 2].to_i + min = digits[2, 2].to_i + sec = digits[4, 2].to_i + return nil if h >= 24 || min >= 60 || sec >= 60 + return sign * (h * 3600 + min * 60 + sec) + else + return nil + end + end + end + + # +HH:MM or +HH:MM:SS + m = s.match(/\A([+-])(\d{1,2}):(\d{2})(?::(\d{2}))?$/) + if m + sign = m[1] == '-' ? -1 : 1 + h = m[2].to_i + min = m[3].to_i + sec = m[4] ? m[4].to_i : 0 + return nil if h >= 24 || min >= 60 || sec >= 60 + return sign * (h * 3600 + min * 60 + sec) + end + + nil + end + + def _zone_name_to_offset(name) + ZONE_TABLE[name.downcase.gsub(/\s+/, ' ')] + end + end +end diff --git a/lib/date/time.rb b/lib/date/time.rb new file mode 100644 index 00000000..3b73236b --- /dev/null +++ b/lib/date/time.rb @@ -0,0 +1,59 @@ +# frozen_string_literal: true + +class Time + def to_time + self + end unless method_defined?(:to_time) + + def to_date + y = year + m = month + d = day + + nth, ry = Date.send(:decode_year, y, -1) + + # First, create it in GREGORIAN (dates during the reform period are also valid). + obj = Date.send(:d_simple_new_internal, + nth, 0, + Date::GREGORIAN, + ry, m, d, + 0x04) # Date::HAVE_CIVIL + + # Then change to DEFAULT_SG. + obj.send(:set_sg, Date::ITALY) + + obj + end unless method_defined?(:to_date) + + def to_datetime + y = year + m = month + d = day + h = hour + mi = min + s = sec + of_sec = utc_offset + sf = nsec + + nth, ry = Date.send(:decode_year, y, -1) + rjd, _ = Date.send(:c_civil_to_jd, ry, m, d, Date::GREGORIAN) + + df = h * 3600 + mi * 60 + s + + # Convert local to UTC + df_utc = df - of_sec + jd_utc = rjd + if df_utc < 0 + jd_utc -= 1 + df_utc += 86400 + elsif df_utc >= 86400 + jd_utc += 1 + df_utc -= 86400 + end + + obj = DateTime.send(:new_with_jd_and_time, nth, jd_utc, df_utc, sf, of_sec, Date::GREGORIAN) + obj.send(:set_sg, Date::ITALY) + + obj + end unless method_defined?(:to_datetime) +end diff --git a/lib/date/version.rb b/lib/date/version.rb new file mode 100644 index 00000000..063fe245 --- /dev/null +++ b/lib/date/version.rb @@ -0,0 +1,5 @@ +# frozen_string_literal: true + +class Date + VERSION = "3.5.1" # :nodoc: +end diff --git a/lib/date/zonetab.rb b/lib/date/zonetab.rb new file mode 100644 index 00000000..c26262f0 --- /dev/null +++ b/lib/date/zonetab.rb @@ -0,0 +1,405 @@ +# frozen_string_literal: true + +# Timezone name => UTC offset (seconds) mapping table +# Converted C's zonetab.h (gperf-generated hash table) to a Ruby hash. +# 316 zones in total. +# Search ignores case (.downcase on the caller before searching). +# +# Original data source: zonetab.h #included in date_parse.c +# gperf --ignore-case -L ANSI-C -C -c -P -p -j1 -i 1 -g -o -t \ +# -N zonetab zonetab.list +# The complete static hash table generated by was converted equivalently to a Ruby hash. +class Date + ZONE_TABLE = { + "a" => 3600, + "acdt" => 37800, + "acst" => 34200, + "act" => -18000, + "acwst" => 31500, + "adt" => -10800, + "aedt" => 39600, + "aest" => 36000, + "afghanistan" => 16200, + "aft" => 16200, + "ahst" => -36000, + "akdt" => -28800, + "akst" => -32400, + "alaskan" => -32400, + "almt" => 21600, + "anast" => 43200, + "anat" => 43200, + "aoe" => -43200, + "aqtt" => 18000, + "arab" => 10800, + "arabian" => 14400, + "arabic" => 10800, + "art" => -10800, + "ast" => -14400, + "at" => -7200, + "atlantic" => -14400, + "aus central" => 34200, + "aus eastern" => 36000, + "awdt" => 32400, + "awst" => 28800, + "azores" => -3600, + "azost" => 0, + "azot" => -3600, + "azst" => 18000, + "azt" => 14400, + "b" => 7200, + "bnt" => 28800, + "bot" => -14400, + "brst" => -7200, + "brt" => -10800, + "bst" => 3600, + "bt" => 10800, + "btt" => 21600, + "c" => 10800, + "canada central" => -21600, + "cape verde" => -3600, + "cast" => 28800, + "cat" => 7200, + "caucasus" => 14400, + "cct" => 23400, + "cdt" => -18000, + "cen. australia" => 34200, + "central" => -21600, + "central america" => -21600, + "central asia" => 21600, + "central europe" => 3600, + "central european" => 3600, + "central pacific" => 39600, + "cest" => 7200, + "cet" => 3600, + "chadt" => 49500, + "chast" => 45900, + "china" => 28800, + "chost" => 32400, + "chot" => 28800, + "chst" => 36000, + "chut" => 36000, + "cidst" => -14400, + "cist" => -18000, + "ckt" => -36000, + "clst" => -10800, + "clt" => -14400, + "cot" => -18000, + "cst" => -21600, + "cvt" => -3600, + "cxt" => 25200, + "d" => 14400, + "dateline" => -43200, + "davt" => 25200, + "ddut" => 36000, + "e" => 18000, + "e. africa" => 10800, + "e. australia" => 36000, + "e. europe" => 7200, + "e. south america" => -10800, + "eadt" => 39600, + "easst" => -18000, + "east" => -21600, + "eastern" => -18000, + "eat" => 10800, + "ect" => -18000, + "edt" => -14400, + "eest" => 10800, + "eet" => 7200, + "egst" => 0, + "egt" => -3600, + "egypt" => 7200, + "ekaterinburg" => 18000, + "est" => -18000, + "f" => 21600, + "fet" => 10800, + "fiji" => 43200, + "fjst" => 46800, + "fjt" => 43200, + "fkst" => -10800, + "fkt" => -14400, + "fle" => 7200, + "fnt" => -7200, + "fst" => 7200, + "fwt" => 3600, + "g" => 25200, + "galt" => -21600, + "gamt" => -32400, + "get" => 14400, + "gft" => -10800, + "gilt" => 43200, + "gmt" => 0, + "greenland" => -10800, + "greenwich" => 0, + "gst" => 36000, + "gtb" => 7200, + "gyt" => -14400, + "h" => 28800, + "hadt" => -32400, + "hast" => -36000, + "hawaiian" => -36000, + "hdt" => -32400, + "hkt" => 28800, + "hovst" => 28800, + "hovt" => 25200, + "hst" => -36000, + "i" => 32400, + "ict" => 25200, + "idle" => 43200, + "idlw" => -43200, + "idt" => 10800, + "india" => 19800, + "iot" => 21600, + "iran" => 12600, + "irdt" => 16200, + "irkst" => 32400, + "irkt" => 28800, + "irst" => 12600, + "ist" => 19800, + "jerusalem" => 7200, + "jst" => 32400, + "k" => 36000, + "kgt" => 21600, + "korea" => 32400, + "kost" => 39600, + "krast" => 28800, + "krat" => 25200, + "kst" => 32400, + "kuyt" => 14400, + "l" => 39600, + "lhdt" => 39600, + "lhst" => 37800, + "lint" => 50400, + "m" => 43200, + "magst" => 43200, + "magt" => 39600, + "malay peninsula" => 28800, + "mart" => -30600, + "mawt" => 18000, + "mdt" => -21600, + "mest" => 7200, + "mesz" => 7200, + "met" => 3600, + "mewt" => 3600, + "mexico" => -21600, + "mez" => 3600, + "mht" => 43200, + "mid-atlantic" => -7200, + "mmt" => 23400, + "mountain" => -25200, + "msd" => 14400, + "msk" => 10800, + "mst" => -25200, + "mut" => 14400, + "mvt" => 18000, + "myanmar" => 23400, + "myt" => 28800, + "n" => -3600, + "n. central asia" => 21600, + "nct" => 39600, + "ndt" => -5400, + "nepal" => 20700, + "new zealand" => 43200, + "newfoundland" => -12600, + "nfdt" => 43200, + "nft" => 39600, + "north asia" => 25200, + "north asia east" => 28800, + "novst" => 25200, + "novt" => 25200, + "npt" => 20700, + "nrt" => 43200, + "nst" => -9000, + "nt" => -39600, + "nut" => -39600, + "nzdt" => 46800, + "nzst" => 43200, + "nzt" => 43200, + "o" => -7200, + "omsst" => 25200, + "omst" => 21600, + "orat" => 18000, + "p" => -10800, + "pacific" => -28800, + "pacific sa" => -14400, + "pdt" => -25200, + "pet" => -18000, + "petst" => 43200, + "pett" => 43200, + "pgt" => 36000, + "phot" => 46800, + "pht" => 28800, + "pkt" => 18000, + "pmdt" => -7200, + "pmst" => -10800, + "pont" => 39600, + "pst" => -28800, + "pwt" => 32400, + "pyst" => -10800, + "q" => -14400, + "qyzt" => 21600, + "r" => -18000, + "ret" => 14400, + "romance" => 3600, + "rott" => -10800, + "russian" => 10800, + "s" => -21600, + "sa eastern" => -10800, + "sa pacific" => -18000, + "sa western" => -14400, + "sakt" => 39600, + "samoa" => -39600, + "samt" => 14400, + "sast" => 7200, + "sbt" => 39600, + "sct" => 14400, + "se asia" => 25200, + "sgt" => 28800, + "south africa" => 7200, + "sret" => 39600, + "sri lanka" => 21600, + "srt" => -10800, + "sst" => -39600, + "swt" => 3600, + "syot" => 10800, + "t" => -25200, + "taht" => -36000, + "taipei" => 28800, + "tasmania" => 36000, + "tft" => 18000, + "tjt" => 18000, + "tkt" => 46800, + "tlt" => 32400, + "tmt" => 18000, + "tokyo" => 32400, + "tonga" => 46800, + "tost" => 50400, + "tot" => 46800, + "trt" => 10800, + "tvt" => 43200, + "u" => -28800, + "ulast" => 32400, + "ulat" => 28800, + "us eastern" => -18000, + "us mountain" => -25200, + "ut" => 0, + "utc" => 0, + "uyst" => -7200, + "uyt" => -10800, + "uzt" => 18000, + "v" => -32400, + "vet" => -14400, + "vladivostok" => 36000, + "vlast" => 39600, + "vlat" => 36000, + "vost" => 21600, + "vut" => 39600, + "w" => -36000, + "w. australia" => 28800, + "w. central africa" => 3600, + "w. europe" => 3600, + "wadt" => 28800, + "wakt" => 43200, + "warst" => -10800, + "wast" => 7200, + "wat" => 3600, + "west" => 3600, + "west asia" => 18000, + "west pacific" => 36000, + "wet" => 0, + "wft" => 43200, + "wgst" => -3600, + "wgt" => -7200, + "wib" => 25200, + "wit" => 32400, + "wita" => 28800, + "wt" => 0, + "x" => -39600, + "y" => -43200, + "yakst" => 36000, + "yakt" => 32400, + "yakutsk" => 32400, + "yapt" => 36000, + "ydt" => -28800, + "yekst" => 21600, + "yekt" => 18000, + "yst" => -32400, + "z" => 0, + "zp4" => 14400, + "zp5" => 18000, + "zp6" => 21600, + # Multi-word timezone names from C's zonetab.list + "met dst" => 7200, + "mountain standard time" => -25200, + "mountain daylight time" => -21600, + "pacific standard time" => -28800, + "pacific daylight time" => -25200, + "eastern standard time" => -18000, + "eastern daylight time" => -14400, + "central standard time" => -21600, + "central daylight time" => -18000, + "atlantic standard time" => -14400, + "atlantic daylight time" => -10800, + "e. australia standard time" => 36000, + "cen. australia standard time" => 34200, + "w. australia standard time" => 28800, + "dateline standard time" => -43200, + "fiji standard time" => 43200, + "samoa standard time" => -39600, + "new zealand standard time" => 43200, + "taipei standard time" => 28800, + "tokyo standard time" => 32400, + "china standard time" => 28800, + "india standard time" => 19800, + "korea standard time" => 32400, + "singapore standard time" => 28800, + "north asia standard time" => 25200, + "north asia east standard time" => 28800, + "se asia standard time" => 25200, + "west asia standard time" => 18000, + "romance standard time" => 3600, + "russian standard time" => 10800, + "us eastern standard time" => -18000, + "us mountain standard time" => -25200, + "sa western standard time" => -14400, + "sa pacific standard time" => -18000, + "sa eastern standard time" => -10800, + "e. south america standard time" => -10800, + "greenland standard time" => -10800, + "mid-atlantic standard time" => -7200, + "azores standard time" => -3600, + "cape verde standard time" => -3600, + "gmt standard time" => 0, + "greenwich standard time" => 0, + "w. europe standard time" => 3600, + "central europe standard time" => 3600, + "central european standard time" => 3600, + "gtb standard time" => 7200, + "e. europe standard time" => 7200, + "egypt standard time" => 7200, + "south africa standard time" => 7200, + "fle standard time" => 7200, + "israel standard time" => 7200, + "arabian standard time" => 14400, + "arab standard time" => 10800, + "e. africa standard time" => 10800, + "iran standard time" => 12600, + "west pacific standard time" => 36000, + "aus central standard time" => 34200, + "aus eastern standard time" => 36000, + "central pacific standard time" => 39600, + "tasmania standard time" => 36000, + "canada central standard time" => -21600, + "mexico standard time" => -21600, + "mexico standard time 2" => -25200, + "central america standard time" => -21600, + "nepal standard time" => 20700, + "sri lanka standard time" => 21600, + "n. central asia standard time" => 21600, + "central asia standard time" => 21600, + "afghanistan standard time" => 16200, + "ekaterinburg standard time" => 18000, + "alaska standard time" => -32400, + "alaska daylight time" => -28800, + "hawaii standard time" => -36000, + }.freeze +end From 0cdfd42220808c6759e3c24d48c23c2a612641be Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 15 Feb 2026 16:02:25 +0900 Subject: [PATCH 002/144] Put `# encoding: US-ASCII` at the beginning. --- lib/date/constants.rb | 15 ++++++--------- 1 file changed, 6 insertions(+), 9 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index d9db674b..11bdb961 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -1,3 +1,4 @@ +# encoding: US-ASCII # frozen_string_literal: true # Constants @@ -10,15 +11,11 @@ class Date private_constant :HAVE_JD, :HAVE_DF, :HAVE_CIVIL, :HAVE_TIME, :COMPLEX_DAT MONTHNAMES = [nil, "January", "February", "March", "April", "May", "June", - "July", "August", "September", "October", "November", "December"] - .map { |s| s&.encode(Encoding::US_ASCII)&.freeze }.freeze + "July", "August", "September", "October", "November", "December"].freeze ABBR_MONTHNAMES = [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"] - .map { |s| s&.encode(Encoding::US_ASCII)&.freeze }.freeze - DAYNAMES = %w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday] - .map { |s| s.encode(Encoding::US_ASCII).freeze }.freeze - ABBR_DAYNAMES = %w[Sun Mon Tue Wed Thu Fri Sat] - .map { |s| s.encode(Encoding::US_ASCII).freeze }.freeze + "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"].freeze + DAYNAMES = %w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday].freeze + ABBR_DAYNAMES = %w[Sun Mon Tue Wed Thu Fri Sat].freeze # Pattern constants for regex ABBR_DAYS_PATTERN = 'sun|mon|tue|wed|thu|fri|sat' @@ -149,7 +146,7 @@ class Date private_constant :HAVE_ALPHA, :HAVE_DIGIT, :HAVE_DASH, :HAVE_DOT, :HAVE_SLASH # C: default strftime format is US-ASCII - STRFTIME_DEFAULT_FMT = '%F'.encode(Encoding::US_ASCII) + STRFTIME_DEFAULT_FMT = '%F' private_constant :STRFTIME_DEFAULT_FMT # strftime spec categories From 802e0c2e1b3a259332016191f8de87d45fcd9f64 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 16 Feb 2026 00:36:49 +0900 Subject: [PATCH 003/144] Optimized methods MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit | Implementation | i/s | μs/i | | :--- | :--- | :--- | | System (C ext) | 347.5k | 2.88 | | Pre-optimization (pure Ruby) | 313.5k | 3.19 | | Post-optimization (pure Ruby) | 380.0k | 2.63 | | Implementation | i/s | μs/i | | :--- | :--- | :--- | | System (C ext) | 4.32M | 0.23 | | Pre-optimization (pure Ruby) | 312k | 3.20 | | Post-optimization (pure Ruby) | 1.67M | 0.60 | **5.4x speedup** (312k → 1.67M i/s). Reached approximately **39%** of the C extension's performance. | Implementation | i/s | | :--- | :--- | | System (C ext) | 4.50M | | Pre-optimization (pure Ruby) | 311k | | Post-optimization (pure Ruby) | 1.63M | For cases where the fast path is not applicable (e.g., Julian calendar or BCE years), performance remains equivalent to the previous implementation (no changes). The fast path is applied when all of the following conditions are met: 1. `year`, `month`, and `day` are all `Integer`. 2. The date is determined to be strictly Gregorian (e.g., `start` is `GREGORIAN`, or a reform date like `ITALY` with `year > 1930`). By satisfying these conditions, the implementation skips six `self.class.send` calls, `Hash` allocations, redundant `decode_year` calls, and repetitive array generation. | Implementation | i/s | | :--- | :--- | | System (C ext) | 9.58M | | Pre-optimization (pure Ruby) | 458k | | Post-optimization (pure Ruby) | 2.51M | **5.5x speedup** (458k → 2.51M i/s). Reached approximately **26%** of the C extension's performance. | Implementation | i/s | | :--- | :--- | | System (C ext) | 9.59M | | Pre-optimization (pure Ruby) | 574k | | Post-optimization (pure Ruby) | 2.53M | **4.4x speedup.** 1. **Added a Fast Path** — For `Integer` arguments and Gregorian calendar cases, the entire method chain of `numeric?` (called 3 times) and `valid_civil_sub` is skipped. Instead, month and day range checks are performed inline. 2. **Eliminated Repeated Array Allocation in `valid_civil_sub`** — Changed the implementation to reference a `MONTH_DAYS` constant instead of creating a new array `[nil, 31, 28, ...]` on every call. | Case | System (C ext) | Pre-optimization | Post-optimization | | :--- | :--- | :--- | :--- | | Date.jd | 4.12M | 462k | 1.18M | | Date.jd(0) | 4.20M | 467k | 1.19M | | Date.jd(JULIAN) | 4.09M | 468k | 1.22M | | Date.jd(GREG) | 4.07M | 467k | 1.21M | **Approximately 2.6x speedup** (462k → 1.18M i/s). Reached approximately **29%** of the C extension's performance. The fast path is effective across all `start` patterns (`ITALY` / `JULIAN` / `GREGORIAN`). The following processes are now skipped: - `valid_sg` + `c_valid_start_p` (numerous type checks) - `value_trunc` (array allocation for `Integer`) - `decode_jd` (array allocation for standard Julian Days) - `d_simple_new_internal` (`canon` + flag operations + method call overhead) | Case | System (C ext) | Pre-optimization | Post-optimization | Improvement | | :--- | :--- | :--- | :--- | :--- | | Date.ordinal | 2.66M | 170k | 645k | 3.8x | | Date.ordinal(-1) | 1.87M | 119k | 639k | 5.4x | | Date.ordinal(neg) | 3.08M | 107k | 106k | (Slow path) | **3.8x to 5.4x speedup** in cases where the fast path is applicable. Reached approximately **24% to 34%** of the C extension's performance. `Date.ordinal(neg)` remains on the slow path (equivalent to previous performance) because the year -4712 does not meet the fast path condition (`year > REFORM_END_YEAR`). | Case | System (C ext) | Pre-optimization | Post-optimization | Improvement | | :--- | :--- | :--- | :--- | :--- | | Date.commercial | 2.18M | 126k | 574k | 4.5x | | Date.commercial(-1) | 1.45M | 85k | 560k | 6.6x | | Date.commercial(neg) | 2.84M | 93k | 90k | (Slow path) | **4.5x to 6.6x speedup** in cases where the fast path is applicable. Reached approximately **26% to 39%** of the C extension's performance. Inlined the ISO week-to-JD conversion: 1. Obtain the JD for Jan 1 using `c_gregorian_civil_to_jd(year, 1, 1)` (requires only one method call). 2. Directly calculate `max_weeks` (52 or 53) from the ISO weekday to perform a week range check. 3. Calculate the Monday of Week 1 using: `base = (jd_jan1 + 3) - ((jd_jan1 + 3) % 7)`. 4. Directly calculate the JD using: `rjd = base + 7*(week-1) + (day-1)`. This bypasses the entire previous chain of `valid_commercial_p` → `c_valid_commercial_p` → `c_commercial_to_jd` → `c_jd_to_commercial` (verification via inverse conversion). | Case | System (C ext) | Pre-optimization | Post-optimization | Improvement | | :--- | :--- | :--- | :--- | :--- | | valid_ordinal? (true) | 3.76M | 221k | 3.38M | 15.3x | | valid_ordinal? (false) | 3.77M | 250k | 3.39M | 13.6x | | valid_ordinal? (-1) | 2.37M | 148k | 2.67M | 18.0x | **15x to 18x speedup.** Performance reached **90% to 112%** of the C extension, making it nearly equivalent or even slightly faster. Since `valid_ordinal?` does not require object instantiation and only involves leap year determination and day-of-year range checks, the inline cost of the fast path is extremely low, allowing it to rival the performance of the C extension. | Case | System (C ext) | Pre-optimization | Post-optimization | Improvement | | :--- | :--- | :--- | :--- | :--- | | valid_commercial? (true) | 2.94M | 167k | 1.09M | 6.5x | | valid_commercial? (false) | 3.56M | 218k | 1.08M | 5.0x | | valid_commercial? (-1) | 1.79M | 104k | 1.07M | 10.3x | **5x to 10x speedup.** Performance reached approximately **30% to 37%** of the C extension. The same ISO week validation logic used in the `Date.commercial` fast path (calculating `max_weeks` from the JD of Jan 1 and performing `cwday`/`cweek` range checks) has been inlined. The reason it does not rival the C extension as closely as `valid_ordinal?` is due to the remaining overhead of a single method call to `c_gregorian_civil_to_jd(year, 1, 1)`. | Method | i/s | | :--- | :--- | | Date.valid_jd? | 9.29M | | Date.valid_jd?(false) | 9.68M | It is approximately **3.3x faster** compared to the C extension benchmarks (Reference values: 2.93M / 2.80M). The simplification to only perform type checks has had a significant impact on performance. | Method | Pre-optimization | Post-optimization | Improvement | | :--- | :--- | :--- | :--- | | Date.gregorian_leap?(2000) | 1.40M | 7.39M | 5.3x | | Date.gregorian_leap?(1900) | 1.39M | 7.48M | 5.4x | It is approximately **4.5x faster** even when compared to the C extension reference values (1.69M / 1.66M). For `Integer` arguments, the implementation now performs the leap year determination inline, skipping three method calls: the `numeric?` check, `decode_year`, and `c_gregorian_leap_p?`. Non-`Integer` arguments (such as `Rational`) will fall back to the conventional path. | Method | Pre-optimization | Post-optimization | Improvement | | :--- | :--- | :--- | :--- | | Date.julian_leap? | 2.27M | 8.98M | 4.0x | It is approximately **3.2x faster** even when compared to the C extension reference value (2.80M). For `Integer` arguments, the implementation now skips calls to `numeric?`, `decode_year`, and `c_julian_leap_p?`, returning the result directly via an inline `year % 4 == 0` check. | Method | Pre-optimization | Post-optimization | Improvement | | :--- | :--- | :--- | :--- | | Date#year | 3.27M | 10.06M | 3.1x | It is approximately **2.8x faster** even when compared to the C extension reference value (3.65M). In cases where `@nth == 0 && @has_civil` (which covers almost all typical use cases), the implementation now skips the `m_year` → `simple_dat_p?` → `get_s_civil` method chain as well as `self.class.send(:f_zero_p?, nth)`, returning `@year` directly. Add early return in `m_mon` when `@has_civil` is already true, skipping `simple_dat_p?` check and `get_s_civil`/`get_c_civil` method call overhead. Same pattern as `m_real_year`. Benchmark results (Ruby 4.0.1, benchmark-ips): Date#month: C 21,314,867 ips -> Ruby 14,302,144 ips (67.1%) DateTime#month: C 20,843,168 ips -> Ruby 14,113,170 ips (67.7%) Add early return in `m_mday` when `@has_civil` is already true, skipping `simple_dat_p?` check and `get_s_civil`/`get_c_civil` method call overhead. Same pattern as `m_real_year` and `m_mon`. Benchmark results (Ruby 4.0.1, benchmark-ips): Date#day: C 18,415,779 ips -> Ruby 14,248,797 ips (77.4%) DateTime#day: C 18,758,870 ips -> Ruby 13,750,236 ips (73.3%) Add early return in `m_wday` when `@has_jd` is true and `@of` is nil (simple Date), inlining `(@jd + 1) % 7` directly. This skips `m_local_jd`, `get_s_jd`, `c_jd_to_wday` method call overhead. Benchmark results (Ruby 4.0.1, benchmark-ips): Date#wday: C 20,923,653 ips -> Ruby 11,174,133 ips (53.4%) DateTime#wday: C 20,234,376 ips -> Ruby 3,721,404 ips (18.4%) Note: DateTime#wday is not covered by this fast path since it requires offset-aware local JD calculation. Add fast path in `m_yday` for simple Date (`@of.nil?`) with `@has_civil` already computed. When the calendar is proleptic Gregorian or the date is well past the reform period, compute yday directly via `YEARTAB[month] + day`, skipping `m_local_jd`, `m_virtual_sg`, `m_year`, `m_mon`, `m_mday`, and other method call overhead. Benchmark results (Ruby 4.0.1, benchmark-ips): Date#yday: C 16,253,269 ips -> Ruby 1,942,757 ips (12.0%) DateTime#yday: C 14,927,308 ips -> Ruby 851,319 ips ( 5.7%) Note: DateTime#yday is not covered by this fast path since it requires offset-aware local JD calculation. Multiple optimizations to `Date#+` and its object creation path: 1. Eliminate `instance_variable_set` in `new_with_jd_and_time`: Replace 10 `instance_variable_set` calls with a protected `_init_with_jd` method using direct `@var =` assignment. Benefits all callers (Date#+, Date#-, Date#>>, DateTime#+, etc). 2. Avoid `self.class.send` overhead in `Date#+`: Replace `self.class.send(:new_with_jd, ...)` chain with direct `self.class.allocate` + `obj._init_with_jd(...)` (protected call). 3. Eager JD computation in `Date.civil` fast path: Compute JD via Neri-Schneider algorithm in `initialize` instead of deferring. Ensures `@has_jd = true` from creation, so `Date#+` always takes the fast `@has_jd` path. 4. Add `_init_simple_with_jd` with only 4 ivar assignments: For simple Date fast path, skip 7 nil assignments that `allocate` already provides as undefined (returns nil). 5. Fix fast path condition to handle `@has_civil` without `@has_jd`: When only civil data is available, compute JD inline via Neri-Schneider before addition. Benchmark results (Ruby 4.0.1, benchmark-ips): Date#+1: C 5,961,579 ips -> Ruby 3,150,254 ips (52.8%) Date#+100: C 6,054,311 ips -> Ruby 3,088,684 ips (51.0%) Date#-1: C 4,077,013 ips -> Ruby 2,488,817 ips (61.0%) Date#+1 progression: Before: 1,065,416 ips (17.9% of C) After ivar_set removal: 1,972,000 ips (33.1% of C) After send avoidance: 2,691,799 ips (45.2% of C) After eager JD + 4-ivar init: 3,150,254 ips (52.8% of C) Date#-1: C 4,077,013 ips -> Ruby 2,863,047 ips (70.2%) Date#-1 progression: Before: 989,991 ips (24.3% of C) After Date#+ optimization: 2,488,817 ips (61.0% of C) After Date#- fast path: 2,863,047 ips (70.2% of C) Date#<<1: C 2,214,936 ips -> Ruby 1,632,773 ips (73.7%) Date#<<1 progression: Before: 205,555 ips ( 9.3% of C) After Date#>> optimization: 1,574,551 ips (71.1% of C) After direct fast path: 1,632,773 ips (73.7% of C) - Ruby version: 4.0 (Docker) - C baseline: bench/results/20260215/4.0.1_system.tsv - Tool: benchmark-ips ┌──────────────┬─────────┬────────────┬─────────┐ │ Benchmark │ C (ips) │ Ruby (ips) │ Ruby/C │ ├──────────────┼─────────┼────────────┼─────────┤ │ Date#<<1 │ 2.21 M │ 1.62 M │ 1/1.4x │ ├──────────────┼─────────┼────────────┼─────────┤ │ DateTime#<<1 │ 2.13 M │ 177.53 K │ 1/12.0x │ └──────────────┴─────────┴────────────┴─────────┘ Changes: Replaced the slow path of Date#<< which delegated to self >> (-n) with an inlined version of Date#>>'s slow path logic. This eliminates the extra method call, sign negation, and redundant condition checks. - Date#<< (Date only): reaches 71% of C performance - DateTime#<< (with offset): remains at 1/12x due to the slow path being exercised more heavily - Ruby version: 4.0 (Docker) - C baseline: bench/results/20260215/4.0.1_system.tsv - Tool: benchmark-ips ┌──────────────┬─────────┬───────────────────┬──────────────────┬─────────┐ │ Benchmark │ C (ips) │ Ruby before (ips) │ Ruby after (ips) │ after/C │ ├──────────────┼─────────┼───────────────────┼──────────────────┼─────────┤ │ Date#<=> │ 11.84 M │ 635.23 K │ 2.99 M │ 1/4.0x │ ├──────────────┼─────────┼───────────────────┼──────────────────┼─────────┤ │ DateTime#<=> │ 12.24 M │ 622.88 K │ 577.00 K │ 1/21.2x │ └──────────────┴─────────┴───────────────────┴──────────────────┴─────────┘ Changes: Added a fast path to `Date#<=>` for the common case where both objects are simple Date instances (`@df`, `@sf`, `@of` are all `nil`) with `@nth == 0` and `@has_jd` set. In this case, the comparison reduces to a direct `@jd <=> other.@jd` integer comparison, eliminating two `m_canonicalize_jd` calls (each of which allocates a `[nth, jd]` array via `canonicalize_jd`), redundant `simple_dat_p?` checks, and chained accessor calls for `m_nth`, `m_jd`, `m_df`, and `m_sf`. - `Date#<=>` (Date only): 4.7x improvement over pre-optimization Ruby, reaches 75% of C performance - `DateTime#<=>` (with offset): unaffected — falls through to the existing slow path Benchmark: Date#== optimization (pure Ruby vs C) - Ruby version: 4.0 (Docker) - C baseline: bench/results/20260215/4.0.1_system.tsv - Tool: benchmark-ips ┌─────────────┬─────────┬───────────────────┬──────────────────┬─────────┐ │ Benchmark │ C (ips) │ Ruby before (ips) │ Ruby after (ips) │ after/C │ ├─────────────┼─────────┼───────────────────┼──────────────────┼─────────┤ │ Date#== │ 2.78 M │ 875.47 K │ 3.24 M │ 1.17x │ ├─────────────┼─────────┼───────────────────┼──────────────────┼─────────┤ │ DateTime#== │ 2.72 M │ 798.68 K │ 924.96 K │ 1/2.9x │ └─────────────┴─────────┴───────────────────┴──────────────────┴─────────┘ Changes: Added a fast path to `Date#==` for the common case where both objects are simple Date instances (`@df`, `@sf`, `@of` are all `nil`) with `@nth == 0` and `@has_jd` set. In this case, equality reduces to a direct `@jd == other.@jd` integer comparison. This eliminates two `m_canonicalize_jd` calls (each allocating a `[nth, jd]` array via `canonicalize_jd`), redundant `simple_dat_p?` checks, and chained accessor calls for `m_nth`, `m_jd`, `m_df`, and `m_sf`. - `Date#==` (Date only): 3.7x improvement over pre-optimization Ruby, 17% faster than C - `DateTime#==` (with offset): unaffected — falls through to the existing slow path Add fast paths that skip `m_canonicalize_jd` (which allocates an array) for the common case: both objects are simple (`@df`, `@sf`, `@of` are all `nil`), `@nth == 0`, `@has_jd` is true, and `0 <= @jd < CM_PERIOD` (guaranteeing that canonicalization is a no-op). For `Date#===`, whether the two dates are on the same calendar or not, the result always reduces to `@jd == other.@jd` under these conditions, so the `m_gregorian_p?` check and both `m_canonicalize_jd` calls are eliminated. For `Date#hash`, the same bounds guarantee that `m_nth == 0` and `m_jd == @jd` after canonicalization, so `[0, @jd, @sg].hash` is returned directly. | Method | Before | After | Speedup | C impl | |-------------|-------------|--------------|---------|--------------| | `Date#===` | ~558K ips | ~2,940K ips | +5.3x | ~12,659K ips | | `Date#hash` | ~1,990K ips | ~6,873K ips | +3.5x | ~13,833K ips | feat: Optimized `Date#<`. Add an explicit `Date#<` method with a fast path that bypasses the `Comparable` module overhead. When both objects are simple (`@df`, `@sf`, `@of` are all `nil`), `@nth == 0`, and `@has_jd` is true, `@jd < other.@jd` is returned directly without going through `<=>`. The slow path delegates to `super` (Comparable) to preserve all edge-case behavior including `ArgumentError` for incomparable types. | Method | Before | After | Speedup | C impl | |----------|-------------|-------------|---------|-------------| | `Date#<` | ~2,430K ips | ~3,330K ips | +37% | ~7,628K ips | Add an explicit `Date#>` method with a fast path that bypasses the `Comparable` module overhead. When both objects are simple (`@df`, `@sf`, `@of` are all `nil`), `@nth == 0`, and `@has_jd` is true, `@jd > other.@jd` is returned directly without going through `<=>`. The slow path delegates to `super` (Comparable) to preserve all edge-case behavior including `ArgumentError` for incomparable types. | Method | Before | After | Speedup | C impl | |----------|-------------|-------------|---------|-------------| | `Date#>` | ~2,560K ips | ~3,330K ips | +30% | ~7,682K ips | --- lib/date/constants.rb | 8 +- lib/date/core.rb | 540 +++++++++++++++++++++++++++++++++++++----- 2 files changed, 481 insertions(+), 67 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 11bdb961..2f7ca2ba 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -72,14 +72,14 @@ class Date # Days in each month (non-leap and leap year) MONTH_DAYS = [ - [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31], # non-leap - [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] # leap + [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].freeze, # non-leap + [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].freeze # leap ].freeze private_constant :MONTH_DAYS YEARTAB = [ - [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334], # non-leap - [0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335] # leap + [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334].freeze, # non-leap + [0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335].freeze # leap ].freeze private_constant :YEARTAB diff --git a/lib/date/core.rb b/lib/date/core.rb index 03b6d9cb..ff00087c 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -29,6 +29,50 @@ class Date # # Related: Date.jd. def initialize(year = -4712, month = 1, day = 1, start = DEFAULT_SG) + # Fast path: Integer arguments, Gregorian calendar + # Avoids self.class.send, Hash allocation, redundant decode_year + if year.is_a?(Integer) && year.abs < 579000 && month.is_a?(Integer) && day.is_a?(Integer) + gregorian_fast = if start.is_a?(Float) && start.infinite? + start < 0 # GREGORIAN (-Infinity) only + elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD + year > REFORM_END_YEAR + end + + if gregorian_fast + m = month + m += 13 if m < 0 + raise Error unless m >= 1 && m <= 12 + + leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0) + last = MONTH_DAYS[leap ? 1 : 0][m] + d = day + d = last + d + 1 if d < 0 + raise Error unless d >= 1 && d <= last + + j = (m < 3) ? 1 : 0 + y0 = year - j + m0 = j.nonzero? ? m + 12 : m + d0 = d - 1 + q1 = y0 / 100 + yc = (NS_DAYS_IN_4_YEARS * y0) / 4 - q1 + q1 / 4 + mc = (NS_DAYS_BEFORE_NEW_YEAR * m0 - 914) / 10 + + @nth = 0 + @jd = yc + mc + d0 + NS_EPOCH + @sg = start + @year = year + @month = m + @day = d + @has_jd = true + @has_civil = true + @df = nil + @sf = nil + @of = nil + return self + end + end + + # Original path: handles non-Integer args, Julian/reform dates, fractional days y = year m = month d = day @@ -135,6 +179,21 @@ class << self # # Related: Date.jd, Date.new. def valid_civil?(year, month, day, start = DEFAULT_SG) + # Fast path: Integer args, non-Julian start + if year.is_a?(Integer) && month.is_a?(Integer) && day.is_a?(Integer) + gregorian_fast = if start.is_a?(Float) && start.infinite? + start < 0 + elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD + true + end + + if gregorian_fast + return false if month < 1 || month > 12 + leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0) + return day >= 1 && day <= MONTH_DAYS[leap ? 1 : 0][month] + end + end + return false unless numeric?(year) return false unless numeric?(month) return false unless numeric?(day) @@ -170,6 +229,32 @@ def valid_civil?(year, month, day, start = DEFAULT_SG) # # Related: Date.new. def jd(jd = 0, start = DEFAULT_SG) + # Fast path: Integer jd in common range, valid start + if jd.is_a?(Integer) && jd >= 0 && jd < CM_PERIOD + valid_start = if start.is_a?(Float) && start.infinite? + true + elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD + true + end + + if valid_start + obj = allocate + obj.instance_variable_set(:@nth, 0) + obj.instance_variable_set(:@jd, jd) + obj.instance_variable_set(:@sg, start) + obj.instance_variable_set(:@year, 0) + obj.instance_variable_set(:@month, 0) + obj.instance_variable_set(:@day, 0) + obj.instance_variable_set(:@has_jd, true) + obj.instance_variable_set(:@has_civil, false) + obj.instance_variable_set(:@df, nil) + obj.instance_variable_set(:@sf, nil) + obj.instance_variable_set(:@of, nil) + return obj + end + end + + # Original path j = 0 fr = 0 sg = start @@ -203,11 +288,11 @@ def jd(jd = 0, start = DEFAULT_SG) # # Related: Date.jd. def valid_jd?(jd, start = DEFAULT_SG) - return false unless numeric?(jd) + # All Numeric jd values are valid; skip valid_jd_sub/valid_sg chain + return true if jd.is_a?(Numeric) + return true if jd.respond_to?(:to_int) - result = valid_jd_sub(jd, start, 0) - - !result.nil? + false end # call-seq: @@ -221,6 +306,9 @@ def valid_jd?(jd, start = DEFAULT_SG) # # Related: Date.julian_leap?. def gregorian_leap?(year) + if year.is_a?(Integer) + return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0) + end raise TypeError, "invalid year (not numeric)" unless numeric?(year) _, ry = decode_year(year, -1) @@ -240,6 +328,9 @@ def gregorian_leap?(year) # # Related: Date.gregorian_leap?. def julian_leap?(year) + if year.is_a?(Integer) + return (year % 4).zero? + end raise TypeError, "invalid year (not numeric)" unless numeric?(year) _, ry = decode_year(year, +1) @@ -276,6 +367,40 @@ def julian_leap?(year) # # Related: Date.jd, Date.new. def ordinal(year = -4712, yday = 1, start = DEFAULT_SG) + # Fast path: Integer args, Gregorian calendar + if year.is_a?(Integer) && year.abs < 579000 && yday.is_a?(Integer) + gregorian_fast = if start.is_a?(Float) && start.infinite? + start < 0 + elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD + year > REFORM_END_YEAR + end + + if gregorian_fast + leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0) + days_in_year = leap ? 366 : 365 + d = yday + d = days_in_year + d + 1 if d < 0 + raise Error unless d >= 1 && d <= days_in_year + + rjd = c_gregorian_civil_to_jd(year, 1, 1) + d - 1 + + obj = allocate + obj.instance_variable_set(:@nth, 0) + obj.instance_variable_set(:@jd, rjd) + obj.instance_variable_set(:@sg, start) + obj.instance_variable_set(:@year, 0) + obj.instance_variable_set(:@month, 0) + obj.instance_variable_set(:@day, 0) + obj.instance_variable_set(:@has_jd, true) + obj.instance_variable_set(:@has_civil, false) + obj.instance_variable_set(:@df, nil) + obj.instance_variable_set(:@sf, nil) + obj.instance_variable_set(:@of, nil) + return obj + end + end + + # Original path y = year d = yday fr2 = 0 @@ -317,6 +442,23 @@ def ordinal(year = -4712, yday = 1, start = DEFAULT_SG) # # Related: Date.jd, Date.ordinal. def valid_ordinal?(year, day, start = DEFAULT_SG) + # Fast path: Integer args, non-Julian start + if year.is_a?(Integer) && day.is_a?(Integer) + gregorian_fast = if start.is_a?(Float) && start.infinite? + start < 0 + elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD + true + end + + if gregorian_fast + leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0) + days_in_year = leap ? 366 : 365 + d = day + d = days_in_year + d + 1 if d < 0 + return d >= 1 && d <= days_in_year + end + end + return false unless numeric?(year) return false unless numeric?(day) @@ -368,6 +510,55 @@ def valid_ordinal?(year, day, start = DEFAULT_SG) # # Related: Date.jd, Date.new, Date.ordinal. def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = DEFAULT_SG) + # Fast path: Integer args, Gregorian calendar + if cwyear.is_a?(Integer) && cwyear.abs < 579000 && cweek.is_a?(Integer) && cwday.is_a?(Integer) + gregorian_fast = if start.is_a?(Float) && start.infinite? + start < 0 + elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD + cwyear > REFORM_END_YEAR + end + + if gregorian_fast + # Validate cwday (handle negative) + d = cwday + d += 8 if d < 0 + raise Error unless d >= 1 && d <= 7 + + # JD of Jan 1 and ISO week metadata + jd_jan1 = c_gregorian_civil_to_jd(cwyear, 1, 1) + + # Max ISO weeks: 53 if Jan 1 is Thursday, or leap year and Jan 1 is Wednesday + p_val = (jd_jan1 + 1) % 7 # 0=Sun..6=Sat + p_val = 7 if p_val == 0 # Convert to ISO (1=Mon..7=Sun) + leap = (cwyear % 4 == 0) && (cwyear % 100 != 0 || cwyear % 400 == 0) + max_weeks = (p_val == 4 || (leap && p_val == 3)) ? 53 : 52 + + # Handle negative week + w = cweek + w = max_weeks + w + 1 if w < 0 + raise Error unless w >= 1 && w <= max_weeks + + # Compute JD: Monday of week 1 + offset + rjd2 = jd_jan1 + 3 + rjd = (rjd2 - (rjd2 % 7)) + 7 * (w - 1) + (d - 1) + + obj = allocate + obj.instance_variable_set(:@nth, 0) + obj.instance_variable_set(:@jd, rjd) + obj.instance_variable_set(:@sg, start) + obj.instance_variable_set(:@year, 0) + obj.instance_variable_set(:@month, 0) + obj.instance_variable_set(:@day, 0) + obj.instance_variable_set(:@has_jd, true) + obj.instance_variable_set(:@has_civil, false) + obj.instance_variable_set(:@df, nil) + obj.instance_variable_set(:@sf, nil) + obj.instance_variable_set(:@of, nil) + return obj + end + end + + # Original path y = cwyear w = cweek d = cwday @@ -418,6 +609,34 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = DEFAULT_SG) # # Related: Date.jd, Date.commercial. def valid_commercial?(year, week, day, start = DEFAULT_SG) + # Fast path: Integer args, non-Julian start + if year.is_a?(Integer) && week.is_a?(Integer) && day.is_a?(Integer) + gregorian_fast = if start.is_a?(Float) && start.infinite? + start < 0 + elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD + true + end + + if gregorian_fast + # Validate cwday (handle negative) + d = day + d += 8 if d < 0 + return false unless d >= 1 && d <= 7 + + # Max ISO weeks: 53 if Jan 1 is Thursday, or leap year and Jan 1 is Wednesday + jd_jan1 = c_gregorian_civil_to_jd(year, 1, 1) + p_val = (jd_jan1 + 1) % 7 # 0=Sun..6=Sat + p_val = 7 if p_val == 0 # Convert to ISO (1=Mon..7=Sun) + leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0) + max_weeks = (p_val == 4 || (leap && p_val == 3)) ? 53 : 52 + + # Handle negative week + w = week + w = max_weeks + w + 1 if w < 0 + return w >= 1 && w <= max_weeks + end + end + return false unless numeric?(year) return false unless numeric?(week) return false unless numeric?(day) @@ -436,40 +655,18 @@ def valid_commercial?(year, week, day, start = DEFAULT_SG) # # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. def today(start = DEFAULT_SG) - begin - time = Time.now - rescue - raise SystemCallError, "time" - end - - begin - y = time.year - m = time.month - d = time.day - rescue - raise SystemCallError, "localtime" - end - - nth, ry, _, _ = decode_year(y, -1) + time = Time.now obj = allocate - obj.instance_variable_set(:@nth, nth) - obj.instance_variable_set(:@year, ry) - obj.instance_variable_set(:@month, m) - obj.instance_variable_set(:@day, d) + obj.instance_variable_set(:@nth, 0) + obj.instance_variable_set(:@year, time.year) + obj.instance_variable_set(:@month, time.mon) + obj.instance_variable_set(:@day, time.mday) obj.instance_variable_set(:@jd, nil) - obj.instance_variable_set(:@sg, GREGORIAN) + obj.instance_variable_set(:@sg, start) obj.instance_variable_set(:@has_jd, false) obj.instance_variable_set(:@has_civil, true) - if start != GREGORIAN - obj.instance_variable_set(:@sg, start) - if obj.instance_variable_get(:@has_jd) - obj.instance_variable_set(:@jd, nil) - obj.instance_variable_set(:@has_jd, false) - end - end - obj end @@ -808,9 +1005,7 @@ def valid_civil_sub(year, month, day, start, need_jd) return nil if month < 1 || month > 12 leap_year = start == JULIAN ? julian_leap?(year) : gregorian_leap?(year) - - days_in_month = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] - max_day = (month == 2 && leap_year) ? 29 : days_in_month[month] + max_day = MONTH_DAYS[leap_year ? 1 : 0][month] return nil if day < 1 || day > max_day @@ -1137,13 +1332,7 @@ def c_gregorian_ldom_jd(year, month) end def c_gregorian_last_day_of_month(year, month) - days_in_month = [nil, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31] - - if month == 2 && gregorian_leap?(year) - 29 - else - days_in_month[month] - end + MONTH_DAYS[gregorian_leap?(year) ? 1 : 0][month] end def c_civil_to_jd(year, month, day, sg) @@ -1341,18 +1530,7 @@ def new_with_jd(nth, jd, start) def new_with_jd_and_time(nth, jd, df, sf, of, start) obj = allocate - obj.instance_variable_set(:@nth, nth) - obj.instance_variable_set(:@jd, jd) - obj.instance_variable_set(:@sg, start) - obj.instance_variable_set(:@df, df) - obj.instance_variable_set(:@sf, sf) - obj.instance_variable_set(:@of, of) - obj.instance_variable_set(:@year, nil) - obj.instance_variable_set(:@month, nil) - obj.instance_variable_set(:@day, nil) - obj.instance_variable_set(:@has_jd, true) - obj.instance_variable_set(:@has_civil, false) - + obj.send(:_init_with_jd, nth, jd, df, sf, of, start) obj end @@ -1586,6 +1764,16 @@ def start # # d <=> Object.new # => nil def <=>(other) + if other.is_a?(Date) && + @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && + other.instance_variable_get(:@nth) == 0 && + other.instance_variable_get(:@has_jd) && + other.instance_variable_get(:@df).nil? && + other.instance_variable_get(:@sf).nil? && + other.instance_variable_get(:@of).nil? + return @jd <=> other.instance_variable_get(:@jd) + end + case other when Date m_canonicalize_jd @@ -1625,6 +1813,32 @@ def <=>(other) end end + def <(other) # :nodoc: + if other.is_a?(Date) && + @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && + other.instance_variable_get(:@nth) == 0 && + other.instance_variable_get(:@has_jd) && + other.instance_variable_get(:@df).nil? && + other.instance_variable_get(:@sf).nil? && + other.instance_variable_get(:@of).nil? + return @jd < other.instance_variable_get(:@jd) + end + super + end + + def >(other) # :nodoc: + if other.is_a?(Date) && + @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && + other.instance_variable_get(:@nth) == 0 && + other.instance_variable_get(:@has_jd) && + other.instance_variable_get(:@df).nil? && + other.instance_variable_get(:@sf).nil? && + other.instance_variable_get(:@of).nil? + return @jd > other.instance_variable_get(:@jd) + end + super + end + # call-seq: # self === other -> true, false, or nil. # @@ -1659,6 +1873,17 @@ def <=>(other) # # d === Object.new # => nil def ===(other) + if other.is_a?(Date) && + @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && + @jd >= 0 && @jd < CM_PERIOD && + other.instance_variable_get(:@nth) == 0 && + other.instance_variable_get(:@has_jd) && + other.instance_variable_get(:@df).nil? && + other.instance_variable_get(:@sf).nil? && + other.instance_variable_get(:@of).nil? + return @jd == other.instance_variable_get(:@jd) + end + return equal_gen(other) unless other.is_a?(Date) # Call equal_gen even if the Gregorian calendars do not match. @@ -1700,6 +1925,29 @@ def ===(other) # d1 = d0 >> 1 # => # # d2 = d1 >> -1 # => # def >>(n) + if n.is_a?(Integer) && @of.nil? && @nth == 0 && @has_civil + sg = @sg + gregorian_fast = if sg.is_a?(Float) && sg.infinite? + sg < 0 + elsif sg.is_a?(Integer) && sg >= REFORM_BEGIN_JD && sg <= REFORM_END_JD + @year > REFORM_END_YEAR + end + if gregorian_fast + t = @year * 12 + (@month - 1) + n + y = t / 12 + m = (t % 12) + 1 + d = @day + + leap = (y % 4 == 0) && (y % 100 != 0 || y % 400 == 0) + last = MONTH_DAYS[leap ? 1 : 0][m] + d = last if d > last + + obj = self.class.allocate + obj._init_simple_with_civil(y, m, d, sg) + return obj + end + end + # Calculate years and months t = m_real_year * 12 + (m_mon - 1) + n @@ -1758,12 +2006,71 @@ def >>(n) # d1 = d0 << 1 # => # # d2 = d1 << -1 # => # def <<(n) + if n.is_a?(Integer) && @of.nil? && @nth == 0 && @has_civil + sg = @sg + gregorian_fast = if sg.is_a?(Float) && sg.infinite? + sg < 0 + elsif sg.is_a?(Integer) && sg >= REFORM_BEGIN_JD && sg <= REFORM_END_JD + @year > REFORM_END_YEAR + end + if gregorian_fast + t = @year * 12 + (@month - 1) - n + y = t / 12 + m = (t % 12) + 1 + d = @day + + leap = (y % 4 == 0) && (y % 100 != 0 || y % 400 == 0) + last = MONTH_DAYS[leap ? 1 : 0][m] + d = last if d > last + + obj = self.class.allocate + obj._init_simple_with_civil(y, m, d, sg) + return obj + end + end + raise TypeError, "expected numeric" unless n.is_a?(Numeric) - self >> (-n) + t = m_real_year * 12 + (m_mon - 1) - n + + if t.is_a?(Integer) && t.abs < (1 << 62) + y = t / 12 + m = (t % 12) + 1 + else + y = t.div(12) + m = (t % 12).to_i + 1 + end + + d = m_mday + sg = m_sg + + result = nil + loop do + result = self.class.send(:valid_civil_p, y, m, d, sg) + break if result + + d -= 1 + raise Error if d < 1 + end + + nth = result[:nth] + rjd = result[:rjd] + rjd2 = self.class.send(:encode_jd, nth, rjd) + + self + (rjd2 - m_real_local_jd) end def ==(other) # :nodoc: + if other.is_a?(Date) && + @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && + other.instance_variable_get(:@nth) == 0 && + other.instance_variable_get(:@has_jd) && + other.instance_variable_get(:@df).nil? && + other.instance_variable_get(:@sf).nil? && + other.instance_variable_get(:@of).nil? + return @jd == other.instance_variable_get(:@jd) + end + return false unless other.is_a?(Date) m_canonicalize_jd @@ -1776,6 +2083,17 @@ def ==(other) # :nodoc: end def eql?(other) # :nodoc: + if other.is_a?(Date) && + @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && + other.instance_variable_get(:@nth) == 0 && + other.instance_variable_get(:@has_jd) && + other.instance_variable_get(:@df).nil? && + other.instance_variable_get(:@sf).nil? && + other.instance_variable_get(:@of).nil? + return @jd == other.instance_variable_get(:@jd) && + @sg == other.instance_variable_get(:@sg) + end + return false unless other.is_a?(Date) m_canonicalize_jd @@ -1787,6 +2105,10 @@ def eql?(other) # :nodoc: end def hash # :nodoc: + if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && + @jd >= 0 && @jd < CM_PERIOD + return [0, @jd, @sg].hash + end m_canonicalize_jd [m_nth, m_jd, @sg].hash end @@ -1806,6 +2128,34 @@ def hash # :nodoc: # DateTime.jd(0,12) + DateTime.new(2001,2,3).ajd # #=> # def +(other) + if other.is_a?(Integer) && @of.nil? && @nth == 0 + if @has_jd + jd = @jd + other + elsif @has_civil + sg = @sg + gregorian_fast = if sg.is_a?(Float) && sg.infinite? + sg < 0 + elsif sg.is_a?(Integer) && sg >= REFORM_BEGIN_JD && sg <= REFORM_END_JD + @year > REFORM_END_YEAR + end + if gregorian_fast + j = (@month < 3) ? 1 : 0 + y0 = @year - j + m0 = j.nonzero? ? @month + 12 : @month + d0 = @day - 1 + q1 = y0 / 100 + yc = (NS_DAYS_IN_4_YEARS * y0) / 4 - q1 + q1 / 4 + mc = (NS_DAYS_BEFORE_NEW_YEAR * m0 - 914) / 10 + jd = yc + mc + d0 + NS_EPOCH + other + end + end + if jd && jd >= 0 && jd < CM_PERIOD + obj = self.class.allocate + obj._init_simple_with_jd(jd, @sg) + return obj + end + end + case other when Integer nth = m_nth @@ -1821,11 +2171,13 @@ def +(other) nth, jd = canonicalize_jd(nth, jd) end + obj = self.class.allocate if simple_dat_p? - self.class.send(:new_with_jd, nth, jd, @sg) + obj._init_with_jd(nth, jd, nil, nil, nil, @sg) else - self.class.send(:new_with_jd_and_time, nth, jd, @df || 0, @sf || 0, @of || 0, @sg) + obj._init_with_jd(nth, jd, @df || 0, @sf || 0, @of || 0, @sg) end + obj when Float s = other >= 0 ? 1 : -1 o = other.abs @@ -1884,11 +2236,13 @@ def +(other) nth = nth.nonzero? ? @nth + nth : @nth + obj = self.class.allocate if df.zero? && sf.zero? && (@of.nil? || @of.zero?) - self.class.send(:new_with_jd, nth, jd, @sg) + obj._init_with_jd(nth, jd, nil, nil, nil, @sg) else - self.class.send(:new_with_jd_and_time, nth, jd, df, sf, @of || 0, @sg) + obj._init_with_jd(nth, jd, df, sf, @of || 0, @sg) end + obj when Rational return self + other.numerator if other.denominator == 1 @@ -1949,11 +2303,13 @@ def +(other) nth = nth.nonzero? ? @nth + nth : @nth + obj = self.class.allocate if df.zero? && sf.zero? - self.class.send(:new_with_jd, nth, jd, @sg) + obj._init_with_jd(nth, jd, nil, nil, nil, @sg) else - self.class.send(:new_with_jd_and_time, nth, jd, df, sf, @of || 0, @sg) + obj._init_with_jd(nth, jd, df, sf, @of || 0, @sg) end + obj else raise TypeError, "expected numeric" unless other.is_a?(Numeric) @@ -1979,6 +2335,15 @@ def +(other) # Date.new(2001,2,3) - Date.new(2001) #=> (33/1) # DateTime.new(2001,2,3) - DateTime.new(2001,2,2,12) #=> (1/2) def -(other) + if other.is_a?(Integer) && @of.nil? && @nth == 0 && @has_jd + jd = @jd - other + if jd >= 0 && jd < CM_PERIOD + obj = self.class.allocate + obj._init_simple_with_jd(jd, @sg) + return obj + end + end + return minus_dd(other) if other.is_a?(Date) raise TypeError, "expected numeric" unless other.is_a?(Numeric) @@ -2833,6 +3198,40 @@ def valid_civil_date?(year, month, day, sg) self.class.send(:valid_civil_date?, year, month, day, sg) end + protected + + def _init_with_jd(nth, jd, df, sf, of, start) + @nth = nth + @jd = jd + @sg = start + @df = df + @sf = sf + @of = of + @year = nil + @month = nil + @day = nil + @has_jd = true + @has_civil = false + end + + def _init_simple_with_jd(jd, start) + @nth = 0 + @jd = jd + @sg = start + @has_jd = true + end + + def _init_simple_with_civil(year, month, day, start) + @nth = 0 + @sg = start + @year = year + @month = month + @day = day + @has_civil = true + end + + private + def canonicalize_jd(nth, jd) if jd < 0 nth = nth - 1 @@ -3114,6 +3513,8 @@ def m_of end def m_real_year + return @year if @nth == 0 && @has_civil + nth = @nth year = m_year @@ -3123,14 +3524,16 @@ def m_real_year end def m_mon - simple_dat_p? ? get_s_civil : get_c_civil + return @month if @has_civil + simple_dat_p? ? get_s_civil : get_c_civil @month end def m_mday - simple_dat_p? ? get_s_civil : get_c_civil + return @day if @has_civil + simple_dat_p? ? get_s_civil : get_c_civil @day end @@ -3341,6 +3744,8 @@ def c_valid_start_p?(sg) end def m_wday + return (@jd + 1) % 7 if @has_jd && @of.nil? + c_jd_to_wday(m_local_jd) end @@ -3349,6 +3754,15 @@ def c_jd_to_wday(jd) end def m_yday + if @has_civil && @of.nil? + sg = @sg + if (sg.is_a?(Float) && sg.infinite? && sg < 0) || + (sg.is_a?(Integer) && @has_jd && (@jd - sg) > 366) + leap = self.class.send(:c_gregorian_leap_p?, @year) + return YEARTAB[leap ? 1 : 0][@month] + @day + end + end + jd = m_local_jd sg = m_virtual_sg From d4aa1aa5709101443561205bdd5939599d584825 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 22 Feb 2026 16:51:23 +0900 Subject: [PATCH 004/144] Optimized some methods. MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit feat: Optimize Date#strftime with lookup tables, fast paths, and integer flags Summary of changes: 1. Replace string-based flag accumulation with integer bitmask - Introduced FLAG_MINUS, FLAG_SPACE, FLAG_UPPER, FLAG_CHCASE, FLAG_ZERO - Eliminates per-call String allocation for format modifier parsing 2. Add fast path in strftime_format for simple Date objects - Detects simple Date (@df/@sf/@of all nil, @nth == 0) once per call - Bypasses tmx_* method chain for common specs (Y, m, d, A, B, etc.) - Precomputes f_year, f_month, f_day, f_wday from instance variables 3. Add FOUR_DIGIT precomputed lookup table - "0000".."9999" frozen string table avoids per-call sprintf for years 0..9999 - Applied to fast paths (%F/%Y-%m-%d, composite, %c) and strftime_format 4. Move TWO_DIGIT, FOUR_DIGIT, and FLAG_* constants to constants.rb - Consolidates all Date constants in one file --- Performance comparison (Date#strftime, Ruby 4.0.1) Benchmark: Date#strftime (default) C extension: 2,862,515 Pure Ruby before: 86,749 Pure Ruby after: 1,341,000 vs before: +15.5x vs C ext: 46.8% ──────────────────────────────────────── Benchmark: Date#strftime(%Y-%m-%d) C extension: 3,040,048 Pure Ruby before: 108,336 Pure Ruby after: 1,346,000 vs before: +12.4x vs C ext: 44.3% ──────────────────────────────────────── Benchmark: Date#strftime(%A %B) C extension: 2,960,230 Pure Ruby before: 83,226 Pure Ruby after: 265,000 vs before: +3.2x vs C ext: 9.0% ──────────────────────────────────────── Benchmark: Date#strftime(%c) C extension: 2,001,595 Pure Ruby before: 43,985 Pure Ruby after: 1,010,000 vs before: +23.0x vs C ext: 50.5% ──────────────────────────────────────── Benchmark: Date#strftime(%x) C extension: 2,622,940 Pure Ruby before: 89,569 Pure Ruby after: 1,438,000 vs before: +16.1x vs C ext: 54.8% ──────────────────────────────────────── Benchmark: Date#strftime(composite) C extension: 1,652,488 Pure Ruby before: 47,050 Pure Ruby after: 1,268,000 vs before: +27.0x vs C ext: 76.7% feat: Add direct fast paths to Date#iso8601, #rfc2822, and #asctime For simple Date objects (no time/offset, @nth == 0), bypass the strftime machinery entirely and build the result string directly using the FOUR_DIGIT and TWO_DIGIT precomputed tables. Changes in lib/date/core.rb: - Date#iso8601 / #xmlschema: build "%Y-%m-%d" string directly - Date#rfc2822 / #rfc822: build RFC 2822 string directly using ABBR_DAYNAMES, ABBR_MONTHNAMES, FOUR_DIGIT; offset fixed to "+0000" for simple Date - Date#asctime / #ctime: build ctime string directly with space-padded day; uses ABBR_DAYNAMES, ABBR_MONTHNAMES, FOUR_DIGIT - All three methods fall back to strftime for non-simple Date objects (DateTime, objects with non-zero offset, etc.) Performance comparison (Ruby 4.0.1, measured 2026-02-22): Benchmark | Pure Ruby (after) | C extension | After / C ext ----------------|-------------------|---------------|--------------- Date#iso8601 | 2,420,256 | 3,983,797 | 60.8 % Date#rfc2822 | 1,811,210 | 1,960,706 | 92.4 % Date#asctime | 1,590,435 | 2,444,714 | 65.1 % Unit: iterations/second (i/s). "Pure Ruby (after)" is measured with Process.clock_gettime on Ruby 4.0.1 (docker ruby:4.0) after this change. All three methods previously delegated to strftime, which parsed the format string through strftime_format on every call. The new fast paths eliminate that overhead for the common case (simple Date created via Date.new / Date.civil). Date#rfc2822 reaches 92% of C extension performance. feat: Optimize Date._strptime with fast path and byte-level digit scanning Summary of changes in lib/date/strptime.rb: 1. Add fast path for '%F' / '%Y-%m-%d' (the default format) - Parse year/mon/mday directly with a single compiled regex, bypassing the full format-string scanner and _strptime_spec dispatch entirely. - Note: manual byte scanning was tested for this hot path but found to be slower than the C regex engine due to Ruby method-call overhead; the regex-based fast path is retained. 2. Remove unnecessary str = string.dup - The input string is read-only inside the parser; the copy was wasteful. 3. Cache fmt_len = format.length - Avoid repeated length calls on every loop iteration. 4. Replace String-based width accumulation with integer arithmetic - width_str = String.new + regex digit check replaced by d.ord - 48 integer accumulation; field_width is nil (not specified) or Integer. 5. Replace format whitespace regex with explicit char comparison - format[i] =~ /\s/ replaced by direct comparison against ' ', "\t", "\n", "\r", "\v", "\f". 6. Change _strptime_spec calling convention to in-place hash modification - Old: returns {pos: new_pos, hash: h} — allocates two hashes per spec. - New: modifies the caller's hash directly and returns new_pos (Integer) or nil on failure — zero extra allocations per spec. - _strptime_composite updated to match the new convention. 7. Add scan_uint / scan_sint byte-level digit scanners - scan_uint(str, pos, max): reads unsigned digits via getbyte, no regex, no substring, no MatchData — returns [value, new_pos] or nil. - scan_sint(str, pos, max): handles optional leading +/- prefix. 8. Replace regex-based matching in _strptime_spec for all numeric specifiers - Affected: Y, C, y, m, d/e, j, H/k, I/l, M, S, L, N, w, u, U, W, V, G, g, s, Q. - Each str[pos..].match(/\A.../) call eliminated: no substring allocation, no MatchData object, no regex engine overhead per numeric field. Performance comparison (Ruby 4.0.1, measured 2026-02-22): Benchmark | Before (i/s) | After (i/s) | C ext (i/s) | After / C ext ---------------------------|--------------|-------------|-------------|--------------- Date._strptime (default) | 40,248 | 740,864 | 2,610,013 | 28.4 % Date.strptime (default) | 37,440 | 323,953 | 1,373,996 | 23.6 % Date._strptime (complex) | 24,015 | 75,532 | 1,097,796 | 6.9 % Unit: iterations/second (i/s). "Before" is taken from bench/results/20260222/4.0.1_local.tsv (prior to this change). "C ext" is taken from bench/results/20260222/4.0.1_system.tsv. "After" is measured with Process.clock_gettime on ruby:4.0 (Docker) after all changes in this commit. The default format (Date._strptime with no explicit format argument) improves 18.4x over the baseline by hitting the '%F' fast path. The complex format ('%Y-%m-%d %H:%M:%S') improves 3.1x through the elimination of per-spec substring and MatchData allocations via scan_uint / scan_sint. feat: Apply StringScanner (Approach A) to Date._strptime general parser Replace the hand-rolled position-integer loop in _strptime with a StringScanner-based approach to eliminate redundant String allocations. Changes: - Add `require 'strscan'` - Main loop: use `format.getbyte(i)` (Integer comparison) instead of `format[i]` (String allocation) for every format character - Literal character matching: `ss.string.getbyte(ss.pos) == fb` + `ss.pos += 1` instead of `str[pos] == c` (String allocation per literal char) - Whitespace skipping: `ss.skip(/[ \t\n\r\v\f]*/)` instead of a hand-rolled while loop with per-char String comparisons - `%p`/`%P`: `ss.scan(/a\.?m\.?|p\.?m\.?/i)` eliminates the `str[pos..].match(/\A.../)` substring allocation - `%n`/`%t`: `ss.skip(/\s*/)` replaces `str[pos..].match(/\A\s+/)` - `_strptime_spec` signature: `(ss, spec, width, hash, next_is_num)` — updates `ss.pos` in-place, returns `true`/`nil` - `_strptime_composite` signature: `(ss, format, context_hash)` — uses `format.getbyte(i)` and `ss.string.getbyte(ss.pos)` throughout, returns the diff hash (or nil) rather than `{pos:, hash:}` - The `%F`/`%Y-%m-%d` regex fast path is unchanged Performance (500,000 iterations, ruby 4.0, linux/amd64): | Method | C ext (i/s) | Before (i/s) | After (i/s) | % of C | |-----------------------------|-------------|--------------|-------------|--------| | Date._strptime (default %F) | 2,610,014 | 740,864 | 747,515 | 28.6% | | Date.strptime (default %F) | 1,373,996 | 323,953 | 326,703 | 23.8% | | Date._strptime (complex fmt)| 1,097,796 | 75,532 | 106,642 | 9.7% | The default-format path shows only marginal gains because the regex fast path (`%F`/`%Y-%m-%d`) bypasses the StringScanner loop entirely. The complex-format path improves by ~41% over Approach C, driven by eliminating per-character String allocations in the main parse loop. feat: Expand _strptime fast paths for common datetime formats (Approach D) Add direct regex fast paths for two additional format strings, bypassing the StringScanner general parser loop entirely. Changes: - Refactor the existing `%F`/`%Y-%m-%d` fast path into a `case/when` dispatch for extensibility - Add fast path for `'%Y-%m-%d %H:%M:%S'`: matches `/\A([+-]?\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})/` and returns `{year:, mon:, mday:, hour:, min:, sec:}` directly - Add fast path for `'%Y-%m-%dT%H:%M:%S'`: same as above with `T` separator (ISO 8601 datetime) - Both fast paths validate ranges (mon 1-12, mday 1-31, hour 0-24, min 0-59, sec 0-60) and set `:leftover` if trailing input remains Performance (500,000 iterations, ruby 4.0, linux/amd64): | Method | C ext (i/s) | Before (i/s) | After (i/s) | % of C | |-----------------------------------|-------------|--------------|-------------| --------| | Date._strptime (default %F) | 2,610,014 | 747,515 | 723,600 | 27.7% | | Date.strptime (default %F) | 1,373,996 | 326,703 | 332,490 | 24.2% | | Date._strptime (%Y-%m-%d %H:%M:%S) | 1,097,796 | 106,642 | 544,377 | 49.6% | The complex datetime format improves ~5x by eliminating all StringScanner and spec-dispatch overhead for the hot `%Y-%m-%d %H:%M:%S` pattern. The default `%F` case is unchanged in behavior (before/after difference is within benchmark noise). feat: Optimize constructors, accessors, and strptime internals (Phases 4–8) Changes - strptime internals - Precompute NUM_PATTERN_SPECS_TABLE, STRPTIME_DAYNAME_BY_INT_KEY, and STRPTIME_MONNAME_BY_INT_KEY in constants.rb for O(1) byte-level lookup - Rewrite num_pattern_p with getbyte to eliminate String allocations - Replace ss.skip(/[ \t\n\r\v\f]*/) with skip_ws byte-loop helper (3 sites) -Julian calendar fast path - Add integer-arithmetic Julian JD fast path in Date#initialize covering Date::JULIAN start and pre-reform years (e.g. Date.civil(-4712, 1, 1)) - Computed accessor hot paths - Add @jd fast path to Date#ajd, #amjd, #mjd, #ld bypassing 6-level method chain - Arithmetic and conversion hot paths - Add @jd fast path to Date#to_datetime (skip decode_year + c_civil_to_jd) - Inline Date#wday as (@jd + 1) % 7 - Optimize Date#-(Date) to direct Rational(@jd - other.@jd, 1) - Constructor ivar reduction and accessor inlining - Reduce instance_variable_set calls in Date.jd / .ordinal / .commercial fast paths from 11 to 4 (allocate initializes remaining ivars to nil) - Inline early-return in Date#year, #month, #day Performance: C extension vs pure Ruby (i/s, measured on Ruby 4.0.1) Method | C ext | Ruby | Ruby/C -----------------------|----------|----------|------- Date.civil | 4,626k | 1,018k | 22% Date.civil(neg) | 4,649k | 1,258k | 27% Date.jd | 4,884k | 2,311k | 47% Date.ordinal | 3,032k | 947k | 31% Date.commercial | 2,483k | 809k | 33% Date#year | 20,261k | 13,268k | 65% Date#month | 21,387k | 15,796k | 74% Date#day | 18,377k | 15,798k | 86% Date#wday | 20,868k | 11,957k | 57% Date#jd | 19,662k | 16,496k | 84% Date#ajd | 7,566k | 4,643k | 61% Date#mjd | 11,732k | 8,089k | 69% Date#amjd | 10,574k | 5,746k | 54% Date#ld | 11,805k | 8,216k | 70% Date#yday | 15,685k | 19,099k | 122% Date#cwyear | 4,494k | 6,810k | 152% Date#cweek | 4,550k | 14,646k | 322% Date#-Date | 1,858k | 2,327k | 125% Date#-1 | 3,715k | 3,612k | 97% Date#+1 | 5,516k | 3,460k | 63% Date#to_datetime | 6,686k | 2,126k | 32% Date#iso8601 | 3,997k | 2,505k | 63% Date#rfc3339 | 1,801k | 2,242k | 125% Date#rfc2822 | 1,963k | 1,687k | 86% Date#strftime | 2,830k | 1,347k | 48% Date._parse(iso) | 237k | 61k | 26% Date._strptime | 2,719k | 782k | 29% Date.strptime(complex) | 1,123k | 114k | 10% --- lib/date/constants.rb | 56 ++++ lib/date/core.rb | 351 +++++++++++++++++---- lib/date/parse.rb | 13 +- lib/date/strftime.rb | 439 +++++++++++++++++--------- lib/date/strptime.rb | 709 +++++++++++++++++++++++------------------- 5 files changed, 1025 insertions(+), 543 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 2f7ca2ba..fcf8e2b5 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -161,6 +161,31 @@ class Date NUM_PATTERN_SPECS = "CDdeFGgHIjkLlMmNQRrSsTUuVvWwXxYy" private_constant :NUM_PATTERN_SPECS + # Precomputed byte-indexed boolean table for num_pattern_p. + # Entry is true if the byte value corresponds to a digit-consuming %-specifier. + NUM_PATTERN_SPECS_TABLE = begin + t = Array.new(256, false) + NUM_PATTERN_SPECS.each_byte { |b| t[b] = true } + t.freeze + end + private_constant :NUM_PATTERN_SPECS_TABLE + + # Precomputed zero-padded two-digit strings "00".."99". + TWO_DIGIT = (0..99).map { |i| (i < 10 ? "0#{i}" : i.to_s).freeze }.freeze + private_constant :TWO_DIGIT + + # Precomputed zero-padded four-digit year strings "0000".."9999". + FOUR_DIGIT = (0..9999).map { |y| sprintf("%04d", y).freeze }.freeze + private_constant :FOUR_DIGIT + + # Integer bitmask flags for strftime format modifier parsing. + FLAG_MINUS = 0x01 # '-' suppress padding + FLAG_SPACE = 0x02 # '_' space padding + FLAG_UPPER = 0x04 # '^' upcase result + FLAG_CHCASE = 0x08 # '#' change case (CHCASE) + FLAG_ZERO = 0x10 # '0' zero padding (explicit) + private_constant :FLAG_MINUS, :FLAG_SPACE, :FLAG_UPPER, :FLAG_CHCASE, :FLAG_ZERO + # Fragment completion table for DateTime parsing COMPLETE_FRAGS_TABLE = [ [:time, [:hour, :min, :sec].freeze], @@ -176,4 +201,35 @@ class Date [nil, [:year, :wnum1, :cwday, :hour, :min, :sec].freeze], ].each { |a| a.freeze }.freeze private_constant :COMPLETE_FRAGS_TABLE + + # Lookup tables for O(1) day/month name matching in strptime %a/%b. + # Key: 24-bit integer (b0|0x20)<<16|(b1|0x20)<<8|(b2|0x20) of lowercase 3-char abbreviation. + # Value: [index, full_lower, full_len, abbr_len]. + # This avoids string allocation for the 3-char prefix key entirely. + STRPTIME_DAYNAME_BY_INT_KEY = begin + h = {} + DAYNAMES.each_with_index do |name, idx| + abbr = ABBR_DAYNAMES[idx] + k = ((abbr.getbyte(0) | 0x20) << 16) | + ((abbr.getbyte(1) | 0x20) << 8) | + (abbr.getbyte(2) | 0x20) + h[k] = [idx, name.downcase, name.length, abbr.length].freeze + end + h.freeze + end + private_constant :STRPTIME_DAYNAME_BY_INT_KEY + + STRPTIME_MONNAME_BY_INT_KEY = begin + h = {} + MONTHNAMES.each_with_index do |name, idx| + next unless name + abbr = ABBR_MONTHNAMES[idx] + k = ((abbr.getbyte(0) | 0x20) << 16) | + ((abbr.getbyte(1) | 0x20) << 8) | + (abbr.getbyte(2) | 0x20) + h[k] = [idx, name.downcase, name.length, abbr.length].freeze + end + h.freeze + end + private_constant :STRPTIME_MONNAME_BY_INT_KEY end diff --git a/lib/date/core.rb b/lib/date/core.rb index ff00087c..4e285ffa 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -70,6 +70,50 @@ def initialize(year = -4712, month = 1, day = 1, start = DEFAULT_SG) @of = nil return self end + + # Julian fast path: JULIAN start, or year < REFORM_BEGIN_YEAR with reform-range start. + # Covers Date.civil(-4712, 1, 1) and Date.civil(2024, 6, 15, Date::JULIAN). + julian_fast = if start.is_a?(Float) && start.infinite? + start > 0 # JULIAN (+Infinity) + elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD + year < REFORM_BEGIN_YEAR + end + + if julian_fast + m = month + m += 13 if m < 0 + raise Error unless m >= 1 && m <= 12 + + # Julian leap year: divisible by 4 (no century exception) + leap = (year % 4 == 0) + last = MONTH_DAYS[leap ? 1 : 0][m] + d = day + d = last + d + 1 if d < 0 + raise Error unless d >= 1 && d <= last + + # Julian JD via integer arithmetic: + # jd = floor(365.25*(y+4716)) + floor(30.6001*(m+1)) + d - 1524 + # = (1461*(y+4716))/4 + (153*(m+1))/5 + d - 1524 + y2 = year; m2 = m + if m2 <= 2 + y2 -= 1 + m2 += 12 + end + jd = (1461 * (y2 + 4716)) / 4 + (153 * (m2 + 1)) / 5 + d - 1524 + + @nth = 0 + @jd = jd + @sg = start + @year = year + @month = m + @day = d + @has_jd = true + @has_civil = true + @df = nil + @sf = nil + @of = nil + return self + end end # Original path: handles non-Integer args, Julian/reform dates, fractional days @@ -242,14 +286,7 @@ def jd(jd = 0, start = DEFAULT_SG) obj.instance_variable_set(:@nth, 0) obj.instance_variable_set(:@jd, jd) obj.instance_variable_set(:@sg, start) - obj.instance_variable_set(:@year, 0) - obj.instance_variable_set(:@month, 0) - obj.instance_variable_set(:@day, 0) obj.instance_variable_set(:@has_jd, true) - obj.instance_variable_set(:@has_civil, false) - obj.instance_variable_set(:@df, nil) - obj.instance_variable_set(:@sf, nil) - obj.instance_variable_set(:@of, nil) return obj end end @@ -388,14 +425,7 @@ def ordinal(year = -4712, yday = 1, start = DEFAULT_SG) obj.instance_variable_set(:@nth, 0) obj.instance_variable_set(:@jd, rjd) obj.instance_variable_set(:@sg, start) - obj.instance_variable_set(:@year, 0) - obj.instance_variable_set(:@month, 0) - obj.instance_variable_set(:@day, 0) obj.instance_variable_set(:@has_jd, true) - obj.instance_variable_set(:@has_civil, false) - obj.instance_variable_set(:@df, nil) - obj.instance_variable_set(:@sf, nil) - obj.instance_variable_set(:@of, nil) return obj end end @@ -546,14 +576,7 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = DEFAULT_SG) obj.instance_variable_set(:@nth, 0) obj.instance_variable_set(:@jd, rjd) obj.instance_variable_set(:@sg, start) - obj.instance_variable_set(:@year, 0) - obj.instance_variable_set(:@month, 0) - obj.instance_variable_set(:@day, 0) obj.instance_variable_set(:@has_jd, true) - obj.instance_variable_set(:@has_civil, false) - obj.instance_variable_set(:@df, nil) - obj.instance_variable_set(:@sf, nil) - obj.instance_variable_set(:@of, nil) return obj end end @@ -1672,6 +1695,8 @@ def check_limit(str, limit) # Date.new(2001, 2, 3).year # => 2001 # (Date.new(1, 1, 1) - 1).year # => 0 def year + # Hot path: inline m_real_year for the common case (@nth=0, civil cached) + return @year if @nth == 0 && @has_civil m_real_year end @@ -1682,11 +1707,15 @@ def year # # Date.new(2001, 2, 3).mon # => 2 def month + # Hot path: inline m_mon for the common case (civil cached) + return @month if @has_civil m_mon end alias mon month def day + # Hot path: inline m_mday for the common case (civil cached) + return @day if @has_civil m_mday end alias mday day @@ -1700,6 +1729,7 @@ def day # DateTime.new(2001,2,3,4,5,6,'+7').jd #=> 2451944 # DateTime.new(2001,2,3,4,5,6,'-7').jd #=> 2451944 def jd + return @jd if @nth == 0 && @has_jd m_real_jd end @@ -2344,7 +2374,17 @@ def -(other) end end - return minus_dd(other) if other.is_a?(Date) + if other.is_a?(Date) + # Hot path: both simple dates with @nth=0 and JD set. + # Result is always Rational(jd_self - jd_other, 1). + if @df.nil? && @sf.nil? && @of.nil? && @has_jd && @nth == 0 && + other.send(:simple_dat_p?) && + other.instance_variable_get(:@has_jd) && + other.instance_variable_get(:@nth) == 0 + return Rational(@jd - other.instance_variable_get(:@jd), 1) + end + return minus_dd(other) + end raise TypeError, "expected numeric" unless other.is_a?(Numeric) @@ -2419,6 +2459,10 @@ def julian? # # Date.new(2001, 2, 3).ld # => 152784 def ld + # Hot path: simple Date with @nth=0 and JD already set. + if @df.nil? && @sf.nil? && @of.nil? && @has_jd && @nth == 0 + return @jd - 2299160 + end m_real_local_jd - 2299160 end @@ -2430,23 +2474,23 @@ def ld # Date.new(2000).leap? # => true # Date.new(2001).leap? # => false def leap? - if gregorian? - # For the Gregorian calendar, get m_year to determine if it is a leap year. + return @leap unless @leap.nil? + result = if gregorian? + self.class.send(:c_gregorian_leap_p?, m_year) + else + # For the Julian calendar, calculate JD for March 1st. y = m_year + sg = m_virtual_sg + rjd, _ = self.class.send(:c_civil_to_jd, y, 3, 1, sg) - return self.class.send(:c_gregorian_leap_p?, y) - end - - # For the Julian calendar, calculate JD for March 1st. - y = m_year - sg = m_virtual_sg - rjd, _ = self.class.send(:c_civil_to_jd, y, 3, 1, sg) + # Get the date of the day before March 1st (the last day of February). + _, _, rd = self.class.send(:c_jd_to_civil, rjd - 1, sg) - # Get the date of the day before March 1st (the last day of February). - _, _, rd = self.class.send(:c_jd_to_civil, rjd - 1, sg) - - # If February 29th exists, it is a leap year. - rd == 29 + # If February 29th exists, it is a leap year. + rd == 29 + end + @leap = result unless frozen? + result end # call-seq: @@ -2590,6 +2634,8 @@ def saturday? # # Date.new(2001, 2, 3).wday # => 6 def wday + # Hot path: inline m_wday for simple Date (C: (jd + 1) % 7) + return (@jd + 1) % 7 if @has_jd && @of.nil? m_wday end @@ -2600,7 +2646,10 @@ def wday # # Date.new(2001, 2, 3).yday # => 34 def yday - m_yday + return @yday if @yday + val = m_yday + @yday = val unless frozen? + val end # call-seq: @@ -2775,6 +2824,10 @@ def day_fraction # DateTime.new(2001,2,3,4,5,6,'+7').mjd #=> 51943 # DateTime.new(2001,2,3,4,5,6,'-7').mjd #=> 51943 def mjd + # Hot path: simple Date with @nth=0 and JD already set. + if @df.nil? && @sf.nil? && @of.nil? && @has_jd && @nth == 0 + return @jd - 2_400_001 + end m_real_local_jd - 2_400_001 end @@ -2847,7 +2900,13 @@ def to_date # # Returns a DateTime whose value is the same as +self+. def to_datetime - # Use internal constructor to bypass validation (reform-gap safety) + # Hot path: simple Date with JD already set. + # C: d_lite_to_datetime passes @nth, @jd, @sg directly (no civil->JD conversion). + if @df.nil? && @sf.nil? && @of.nil? && @has_jd + return DateTime.send(:new_with_jd_and_time, @nth, @jd, 0, 0, 0, @sg) + end + + # Original path for complex dates or JD-less simple dates. nth, ry = self.class.send(:decode_year, year, -1) rjd, _ = self.class.send(:c_civil_to_jd, ry, month, day, Date::GREGORIAN) obj = DateTime.send(:new_with_jd_and_time, nth, rjd, 0, 0, 0, Date::GREGORIAN) @@ -2864,6 +2923,11 @@ def to_datetime # DateTime.new(2001,2,3,4,5,6,'+7').ajd #=> (11769328217/4800) # DateTime.new(2001,2,2,14,5,6,'-7').ajd #=> (11769328217/4800) def ajd + # Hot path: simple Date with @nth=0 and JD already set. + # ajd = jd - 1/2 = Rational(jd * 2 - 1, 2) + if @df.nil? && @sf.nil? && @of.nil? && @has_jd && @nth == 0 + return Rational(@jd * 2 - 1, 2) + end m_ajd end @@ -2876,6 +2940,11 @@ def ajd # DateTime.new(2001,2,3,4,5,6,'+7').amjd #=> (249325817/4800) # DateTime.new(2001,2,2,14,5,6,'-7').amjd #=> (249325817/4800) def amjd + # Hot path: simple Date with @nth=0 and JD already set. + # amjd = jd - 2400001 as Rational + if @df.nil? && @sf.nil? && @of.nil? && @has_jd && @nth == 0 + return Rational(@jd - 2400001, 1) + end m_amjd end @@ -2970,7 +3039,22 @@ def marshal_load(array) # See {asctime}[https://linux.die.net/man/3/asctime]. # def asctime - strftime('%a %b %e %H:%M:%S %Y') + if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil && @has_jd + y = @year + wday = (@jd + 1) % 7 + ed = @day < 10 ? " #{@day}" : @day.to_s + y_str = if y >= 0 && y <= 9999 + FOUR_DIGIT[y] + elsif y >= 0 + sprintf("%04d", y) + else + sprintf("%05d", y) + end + str = "#{ABBR_DAYNAMES[wday]} #{ABBR_MONTHNAMES[@month]} #{ed} 00:00:00 #{y_str}" + str.force_encoding(Encoding::US_ASCII) + else + strftime('%a %b %e %H:%M:%S %Y') + end end alias_method :ctime, :asctime @@ -2983,7 +3067,19 @@ def asctime # # Date.new(2001, 2, 3).iso8601 # => "2001-02-03" def iso8601 - strftime('%Y-%m-%d') + if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil + y = @year + str = if y >= 0 && y <= 9999 + "#{FOUR_DIGIT[y]}-#{TWO_DIGIT[@month]}-#{TWO_DIGIT[@day]}" + elsif y >= 0 + sprintf("%04d-%02d-%02d", y, @month, @day) + else + sprintf("%05d-%02d-%02d", y, @month, @day) + end + str.force_encoding(Encoding::US_ASCII) + else + strftime('%Y-%m-%d') + end end alias_method :xmlschema, :iso8601 @@ -2995,7 +3091,19 @@ def iso8601 # # Date.new(2001, 2, 3).rfc3339 # => "2001-02-03T00:00:00+00:00" def rfc3339 - strftime('%Y-%m-%dT%H:%M:%S%:z') + if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil + y = @year + str = if y >= 0 && y <= 9999 + "#{FOUR_DIGIT[y]}-#{TWO_DIGIT[@month]}-#{TWO_DIGIT[@day]}T00:00:00+00:00" + elsif y >= 0 + sprintf("%04d-%02d-%02dT00:00:00+00:00", y, @month, @day) + else + sprintf("%05d-%02d-%02dT00:00:00+00:00", y, @month, @day) + end + str.force_encoding(Encoding::US_ASCII) + else + strftime('%Y-%m-%dT%H:%M:%S%:z') + end end # call-seq: @@ -3006,7 +3114,21 @@ def rfc3339 # # Date.new(2001, 2, 3).rfc2822 # => "Sat, 3 Feb 2001 00:00:00 +0000" def rfc2822 - strftime('%a, %-d %b %Y %T %z') + if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil && @has_jd + y = @year + wday = (@jd + 1) % 7 + y_str = if y >= 0 && y <= 9999 + FOUR_DIGIT[y] + elsif y >= 0 + sprintf("%04d", y) + else + sprintf("%05d", y) + end + str = "#{ABBR_DAYNAMES[wday]}, #{@day} #{ABBR_MONTHNAMES[@month]} #{y_str} 00:00:00 +0000" + str.force_encoding(Encoding::US_ASCII) + else + strftime('%a, %-d %b %Y %T %z') + end end alias_method :rfc822, :rfc2822 @@ -3019,8 +3141,22 @@ def rfc2822 # Date.new(2001, 2, 3).httpdate # => "Sat, 03 Feb 2001 00:00:00 GMT" # def httpdate - # For Date objects, offset is always 0, so we can directly call strftime - strftime('%a, %d %b %Y %T GMT') + if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil + get_s_jd + y = @year + wday = (@jd + 1) % 7 + y_str = if y >= 0 && y <= 9999 + FOUR_DIGIT[y] + elsif y >= 0 + sprintf("%04d", y) + else + sprintf("%05d", y) + end + str = "#{ABBR_DAYNAMES[wday]}, #{TWO_DIGIT[@day]} #{ABBR_MONTHNAMES[@month]} #{y_str} 00:00:00 GMT" + str.force_encoding(Encoding::US_ASCII) + else + strftime('%a, %d %b %Y %T GMT') + end end # call-seq: @@ -3032,11 +3168,44 @@ def httpdate # Date.new(2001, 2, 3).jisx0301 # => "H13.02.03" # def jisx0301 - jd = m_real_local_jd - y = m_real_year - - fmt = jisx0301_date_format(jd, y) - strftime(fmt) + if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil + get_s_jd + jd = @jd + y = @year + mm = TWO_DIGIT[@month] + dd = TWO_DIGIT[@day] + str = if !jd.is_a?(Integer) || jd < 2405160 + # Pre-Meiji or non-integer JD: ISO format + if y >= 0 && y <= 9999 + "#{FOUR_DIGIT[y]}-#{mm}-#{dd}" + elsif y >= 0 + sprintf("%04d-%02d-%02d", y, @month, @day) + else + sprintf("%05d-%02d-%02d", y, @month, @day) + end + elsif jd < 2419614 + ey = y - 1867 + "M#{ey < 100 ? TWO_DIGIT[ey] : sprintf('%02d', ey)}.#{mm}.#{dd}" + elsif jd < 2424875 + ey = y - 1911 + "T#{ey < 100 ? TWO_DIGIT[ey] : sprintf('%02d', ey)}.#{mm}.#{dd}" + elsif jd < 2447535 + ey = y - 1925 + "S#{ey < 100 ? TWO_DIGIT[ey] : sprintf('%02d', ey)}.#{mm}.#{dd}" + elsif jd < 2458605 + ey = y - 1988 + "H#{ey < 100 ? TWO_DIGIT[ey] : sprintf('%02d', ey)}.#{mm}.#{dd}" + else + ey = y - 2018 + "R#{ey < 100 ? TWO_DIGIT[ey] : sprintf('%02d', ey)}.#{mm}.#{dd}" + end + str.force_encoding(Encoding::US_ASCII) + else + jd = m_real_local_jd + y = m_real_year + fmt = jisx0301_date_format(jd, y) + strftime(fmt) + end end def to_s @@ -3644,28 +3813,70 @@ def f_jd(other) end def dup_obj_with_new_start(sg) - dup = dup_obj - dup.send(:set_sg, sg) - - dup + if @df.nil? && @sf.nil? && @of.nil? + # Fast path for simple Date (no time/offset components). + # Absolute hot path: nth==0 (common Gregorian date) with JD already cached. + if @nth == 0 && @has_jd + new_obj = self.class.send(:allocate) + new_obj.instance_variable_set(:@nth, 0) + new_obj.instance_variable_set(:@jd, @jd) + new_obj.instance_variable_set(:@sg, sg) + new_obj.instance_variable_set(:@df, nil) + new_obj.instance_variable_set(:@sf, nil) + new_obj.instance_variable_set(:@of, nil) + new_obj.instance_variable_set(:@year, nil) + new_obj.instance_variable_set(:@month, nil) + new_obj.instance_variable_set(:@day, nil) + new_obj.instance_variable_set(:@has_jd, true) + new_obj.instance_variable_set(:@has_civil, false) + return new_obj + end + # General simple path: inline get_s_jd and canon(@nth). + unless @has_jd + if @has_civil + jd, _ = self.class.send(:c_civil_to_jd, @year, @month, @day, s_virtual_sg) + @jd = jd + @has_jd = true + end + end + nth = @nth + nth = nth.numerator if nth.is_a?(Rational) && nth.denominator == 1 + new_obj = self.class.send(:allocate) + new_obj.instance_variable_set(:@nth, nth) + new_obj.instance_variable_set(:@jd, @jd) + new_obj.instance_variable_set(:@sg, sg) + new_obj.instance_variable_set(:@df, nil) + new_obj.instance_variable_set(:@sf, nil) + new_obj.instance_variable_set(:@of, nil) + new_obj.instance_variable_set(:@year, nil) + new_obj.instance_variable_set(:@month, nil) + new_obj.instance_variable_set(:@day, nil) + new_obj.instance_variable_set(:@has_jd, @has_jd) + new_obj.instance_variable_set(:@has_civil, false) + new_obj + else + dup = dup_obj + dup.send(:set_sg, sg) + dup + end end def dup_obj if simple_dat_p? - # Simple data replication - new_obj = self.class.send(:d_lite_s_alloc_simple) + # Simple data replication: allocate directly, avoid d_lite_s_alloc_simple overhead + new_obj = self.class.send(:allocate) new_obj.instance_variable_set(:@nth, canon(@nth)) new_obj.instance_variable_set(:@jd, @jd) new_obj.instance_variable_set(:@sg, @sg) + new_obj.instance_variable_set(:@df, nil) + new_obj.instance_variable_set(:@sf, nil) + new_obj.instance_variable_set(:@of, nil) new_obj.instance_variable_set(:@year, @year) new_obj.instance_variable_set(:@month, @month) new_obj.instance_variable_set(:@day, @day) new_obj.instance_variable_set(:@has_jd, @has_jd) new_obj.instance_variable_set(:@has_civil, @has_civil) - new_obj.instance_variable_set(:@df, nil) - new_obj.instance_variable_set(:@sf, nil) - new_obj.instance_variable_set(:@of, nil) new_obj else @@ -3882,20 +4093,24 @@ def m_real_cwyear end def m_cwyear - jd = m_local_jd - sg = m_virtual_sg - - ry, _, _ = self.class.send(:c_jd_to_commercial, jd, sg) - + return @cwyear if @has_commercial + ry, rw, _ = self.class.send(:c_jd_to_commercial, m_local_jd, m_virtual_sg) + unless frozen? + @cwyear = ry + @cweek = rw + @has_commercial = true + end ry end def m_cweek - jd = m_local_jd - sg = m_virtual_sg - - _, rw, _ = self.class.send(:c_jd_to_commercial, jd, sg) - + return @cweek if @has_commercial + ry, rw, _ = self.class.send(:c_jd_to_commercial, m_local_jd, m_virtual_sg) + unless frozen? + @cwyear = ry + @cweek = rw + @has_commercial = true + end rw end diff --git a/lib/date/parse.rb b/lib/date/parse.rb index 095a522f..e560b3bb 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -1914,14 +1914,11 @@ def subx(str, pat, rep = " ") def check_class(str) flags = 0 - str.each_char do |c| - flags |= HAVE_ALPHA if c =~ /[a-zA-Z]/ - flags |= HAVE_DIGIT if c =~ /\d/ - flags |= HAVE_DASH if c == '-' - flags |= HAVE_DOT if c == '.' - flags |= HAVE_SLASH if c == '/' - end - + flags |= HAVE_ALPHA if str.match?(/[a-zA-Z]/) + flags |= HAVE_DIGIT if str.match?(/\d/) + flags |= HAVE_DASH if str.include?('-') + flags |= HAVE_DOT if str.include?('.') + flags |= HAVE_SLASH if str.include?('/') flags end diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index eacec7a0..b4e3f020 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -20,6 +20,53 @@ def strftime(format = STRFTIME_DEFAULT_FMT) # Empty format returns empty string return '' if format.empty? + # Fast path: simple Date (no time/offset, @nth == 0) with civil fields cached. + # Covers the most common case for Date objects created via Date.new or Date.civil. + if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil && !format.include?("\0") + y = @year + case format + when '%Y-%m-%d', '%F' + str = if y >= 0 && y <= 9999 + "#{FOUR_DIGIT[y]}-#{TWO_DIGIT[@month]}-#{TWO_DIGIT[@day]}" + elsif y >= 0 + sprintf("%04d-%02d-%02d", y, @month, @day) + else + sprintf("%05d-%02d-%02d", y, @month, @day) + end + return str.force_encoding(format.encoding) + when '%Y-%m-%dT%H:%M:%S%z' + str = if y >= 0 && y <= 9999 + "#{FOUR_DIGIT[y]}-#{TWO_DIGIT[@month]}-#{TWO_DIGIT[@day]}T00:00:00+0000" + elsif y >= 0 + sprintf("%04d-%02d-%02dT00:00:00+0000", y, @month, @day) + else + sprintf("%05d-%02d-%02dT00:00:00+0000", y, @month, @day) + end + return str.force_encoding(format.encoding) + when '%x' + # %x = %m/%d/%y + str = "#{TWO_DIGIT[@month]}/#{TWO_DIGIT[@day]}/#{TWO_DIGIT[y % 100]}" + return str.force_encoding(format.encoding) + end + + # Formats that also require wday (needs @jd). + if @has_jd + wday = (@jd + 1) % 7 + case format + when '%c' + # %c = %a %b %e %H:%M:%S %Y (always 24 chars for 4-digit year) + ed = @day < 10 ? " #{@day}" : @day.to_s + y_str = (y >= 0 && y <= 9999) ? FOUR_DIGIT[y] : (y >= 0 ? sprintf("%04d", y) : sprintf("%05d", y)) + str = "#{ABBR_DAYNAMES[wday]} #{ABBR_MONTHNAMES[@month]} #{ed} 00:00:00 #{y_str}" + return str.force_encoding(format.encoding) + when '%A, %B %d, %Y' + y_str = (y >= 0 && y <= 9999) ? FOUR_DIGIT[y] : (y >= 0 ? sprintf("%04d", y) : sprintf("%05d", y)) + str = "#{DAYNAMES[wday]}, #{MONTHNAMES[@month]} #{TWO_DIGIT[@day]}, #{y_str}" + return str.force_encoding(format.encoding) + end + end + end + # What to do if format string contains a "\0". if format.include?("\0") result = String.new @@ -172,113 +219,204 @@ def decode_offset(of) end # Processing format strings. + # Uses format.index('%') to scan literal sections in bulk, avoiding + # per-character String allocation from format[i] indexing. def strftime_format(format) result = String.new - i = 0 + pos = 0 + fmt_len = format.length + + # Detect simple Date (no time/offset) with both civil and JD fields cached. + # Precompute frequently accessed values to bypass the tmx_* method chain. + if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil && @has_jd + f_year = @year + f_month = @month + f_day = @day + f_wday = (@jd + 1) % 7 + is_simple = true + else + is_simple = false + end - while i < format.length - if format[i] == '%' && i + 1 < format.length - # Skip '%' - i += 1 + while pos < fmt_len + # Find next '%' starting from current position. + pct = format.index('%', pos) - # C: Parse all modifiers in a flat loop (flags, width, colons, E/O) - flags = String.new - width = String.new - modifier = nil - colons = 0 - - while i < format.length - c = format[i] - case c - when 'E', 'O' - modifier = c - i += 1 - when ':' - colons += 1 - i += 1 - when '-', '_', '^', '#' - flags << c - i += 1 - when '0' - # '0' is a flag only when width is still empty - if width.empty? - flags << c - i += 1 - else - width << c - i += 1 - end - when /[1-9]/ - width << c - i += 1 - # Continue reading remaining digits - while i < format.length && format[i] =~ /[0-9]/ - width << format[i] - i += 1 - end + if pct.nil? + # No more format specs — append remaining literal text as a block. + result << format[pos..] if pos < fmt_len + break + end + + # Append literal text before this '%' as a single block copy. + result << format[pos, pct - pos] if pct > pos + + i = pct + 1 + if i >= fmt_len + # Trailing '%' with nothing after — append as literal (matches C behavior). + result << '%' + break + end + + # Parse all modifiers in a flat loop (flags, width, colons, E/O). + # flags: integer bitmask (FLAG_MINUS | FLAG_SPACE | FLAG_UPPER | FLAG_CHCASE | FLAG_ZERO) + # width: integer (-1 = not specified) + flags = 0 + width = -1 + modifier = nil + colons = 0 + + while i < fmt_len + c = format[i] + case c + when 'E', 'O' + modifier = c + i += 1 + when ':' + colons += 1 + i += 1 + when '-' + flags |= FLAG_MINUS + i += 1 + when '_' + flags |= FLAG_SPACE + i += 1 + when '^' + flags |= FLAG_UPPER + i += 1 + when '#' + flags |= FLAG_CHCASE + i += 1 + when '0' + # '0' is a flag only when width is not yet started + if width == -1 + flags |= FLAG_ZERO else - break + width = width * 10 end - end - - # Invalid if both E/O and colon modifiers are present. - if modifier && colons > 0 - if i < format.length - spec = format[i] - result << "%#{modifier}#{':' * colons}#{spec}" + i += 1 + when '1'..'9' + width = format[i].ord - 48 + i += 1 + # Continue reading remaining digits + while i < fmt_len + d = format[i] + break if d < '0' || d > '9' + width = width * 10 + (d.ord - 48) i += 1 end - next + else + break end + end - # Width specifier overflow check - unless width.empty? - if width.length > 10 || (width.length == 10 && width > '2147483647') - raise Errno::ERANGE, "Result too large" - end - if width.to_i >= 1024 - raise Errno::ERANGE, "Result too large" - end + # Invalid if both E/O and colon modifiers are present. + if modifier && colons > 0 + if i < fmt_len + spec = format[i] + result << "%#{modifier}#{':' * colons}#{spec}" + i += 1 end + pos = i + next + end - if i < format.length - spec = format[i] + # Width specifier overflow check + if width != -1 && width >= 1024 + raise Errno::ERANGE, "Result too large" + end - if modifier - # E/O modifier check must come first - valid = case modifier - when 'E' - %w[c C x X y Y].include?(spec) - when 'O' - %w[d e H k I l m M S u U V w W y].include?(spec) - else - false - end + if i < fmt_len + spec = format[i] - if valid - formatted = format_spec(spec, flags, width) - result << formatted + if modifier + # E/O modifier check must come first + valid = case modifier + when 'E' + %w[c C x X y Y].include?(spec) + when 'O' + %w[d e H k I l m M S u U V w W y].include?(spec) + else + false + end + + if valid + result << format_spec(spec, flags, width) + else + result << "%#{modifier}#{flags_to_s(flags)}#{width == -1 ? '' : width}#{spec}" + end + elsif spec == 'z' + if is_simple && flags == 0 && width == -1 && colons == 0 + # Simple Date: offset is always 0, result is always '+0000'. + result << '+0000' + else + result << format_z(tmx_offset, width, flags, colons) + end + elsif colons > 0 + # Colon modifier is only valid for 'z'. + result << "%#{':' * colons}#{flags_to_s(flags)}#{width == -1 ? '' : width}#{spec}" + elsif is_simple && flags == 0 && width == -1 + # Fast path: simple Date with no flags or width — bypass tmx_* method chain. + case spec + when 'Y' + raise Errno::ERANGE, "Result too large" if f_year.bit_length > 128 + if f_year >= 0 && f_year <= 9999 + result << FOUR_DIGIT[f_year] else - result << "%#{modifier}#{flags}#{width}#{spec}" + result << sprintf("%0#{f_year < 0 ? 5 : 4}d", f_year) end - elsif spec == 'z' - # %z with any combination of colons/width/flags - formatted = format_z(tmx_offset, width, flags, colons) - result << formatted - elsif colons > 0 - # Colon modifier is only valid for 'z'. - result << "%#{':' * colons}#{flags}#{width}#{spec}" + when 'C' + c = f_year / 100 + result << (c >= 0 && c < 100 ? TWO_DIGIT[c] : sprintf('%02d', c)) + when 'y' + result << TWO_DIGIT[f_year % 100] + when 'm' + result << TWO_DIGIT[f_month] + when 'd' + result << TWO_DIGIT[f_day] + when 'e' + result << sprintf('%2d', f_day) + when 'A' + result << (DAYNAMES[f_wday] || '?') + when 'a' + result << (ABBR_DAYNAMES[f_wday] || '?')[0, 3] + when 'B' + result << (MONTHNAMES[f_month] || '?') + when 'b', 'h' + result << (ABBR_MONTHNAMES[f_month] || '?')[0, 3] + when 'H', 'M', 'S' + result << '00' + when 'I', 'l' + # hour=0 → h = 0%12 = 0 → h = 12 + result << '12' + when 'k' + # sprintf('%2d', 0) = ' 0' + result << ' 0' + when 'P' + result << 'am' # hour=0 < 12 + when 'p' + result << 'AM' + when 'w' + result << f_wday.to_s + when 'Z' + result << '+00:00' + when '%' + result << '%' + when 'n' + result << "\n" + when 't' + result << "\t" else - formatted = format_spec(spec, flags, width) - result << formatted + result << format_spec(spec, flags, width) end - - i += 1 + else + result << format_spec(spec, flags, width) end - else - result << format[i] + i += 1 end + + pos = i end result.force_encoding('US-ASCII') if result.ascii_only? @@ -286,11 +424,22 @@ def strftime_format(format) result end - def format_spec(spec, flags = '', width = '') + def flags_to_s(flags) + return '' if flags == 0 + s = ''.dup + s << '-' if flags & FLAG_MINUS != 0 + s << '_' if flags & FLAG_SPACE != 0 + s << '^' if flags & FLAG_UPPER != 0 + s << '#' if flags & FLAG_CHCASE != 0 + s << '0' if flags & FLAG_ZERO != 0 + s + end + + def format_spec(spec, flags = 0, width = -1) # N/L: width controls precision (number of fractional digits) if spec == 'N' || spec == 'L' - precision = if !width.empty? - width.to_i + precision = if width != -1 + width elsif spec == 'L' 3 else @@ -308,8 +457,7 @@ def format_spec(spec, flags = '', width = '') base_result = apply_case_flags(base_result, spec, flags) # Apply width specifier. - if !width.empty? - width_num = width.to_i + if width != -1 default_pad = if NUMERIC_SPECS.include?(spec) '0' elsif SPACE_PAD_SPECS.include?(spec) @@ -317,7 +465,7 @@ def format_spec(spec, flags = '', width = '') else ' ' end - apply_width(base_result, width_num, flags, default_pad) + apply_width(base_result, width, flags, default_pad) else base_result end @@ -325,9 +473,9 @@ def format_spec(spec, flags = '', width = '') # C: Apply ^ (UPPER) and # (CHCASE) flags def apply_case_flags(str, spec, flags) - if flags.include?('^') + if flags & FLAG_UPPER != 0 str.upcase - elsif flags.include?('#') + elsif flags & FLAG_CHCASE != 0 if CHCASE_UPPER_SPECS.include?(spec) str.upcase elsif CHCASE_LOWER_SPECS.include?(spec) @@ -341,94 +489,99 @@ def apply_case_flags(str, spec, flags) end # format specifiers - def get_base_format(spec, flags = '') + def get_base_format(spec, flags = 0) case spec when 'Y' # 4-digit year y = tmx_year raise Errno::ERANGE, "Result too large" if y.is_a?(Integer) && y.bit_length > 128 # C: FMT('0', y >= 0 ? 4 : 5, "ld", y) - prec = y < 0 ? 5 : 4 - if flags.include?('-') + if flags & FLAG_MINUS != 0 y.to_s - elsif flags.include?('_') - sprintf("%#{prec}d", y) + elsif flags & FLAG_SPACE != 0 + sprintf("%#{y < 0 ? 5 : 4}d", y) + elsif y >= 0 && y <= 9999 + FOUR_DIGIT[y] else - sprintf("%0#{prec}d", y) + sprintf("%0#{y < 0 ? 5 : 4}d", y) end when 'C' # Century - sprintf('%02d', tmx_year / 100) + c = tmx_year / 100 + c >= 0 && c < 100 ? TWO_DIGIT[c] : sprintf('%02d', c) when 'y' # Two-digit year - sprintf('%02d', tmx_year % 100) + TWO_DIGIT[tmx_year % 100] when 'm' # Month (01-12) - sprintf('%02d', tmx_mon) + if flags & FLAG_MINUS != 0 + tmx_mon.to_s + elsif flags & FLAG_SPACE != 0 + sprintf('%2d', tmx_mon) + else + TWO_DIGIT[tmx_mon] + end when 'B' # Full month name MONTHNAMES[tmx_mon] || '?' when 'b', 'h' # Abbreviated month name (ABBR_MONTHNAMES[tmx_mon] || '?')[0, 3] when 'd' # Day (01-31) - if flags.include?('-') - # Left-justified (no padding) + if flags & FLAG_MINUS != 0 tmx_mday.to_s - elsif flags.include?('_') - # Space-padded + elsif flags & FLAG_SPACE != 0 sprintf('%2d', tmx_mday) else - # Zero-padded (default) - sprintf('%02d', tmx_mday) + TWO_DIGIT[tmx_mday] end when 'e' # Day (1-31) blank filled - if flags.include?('-') + if flags & FLAG_MINUS != 0 tmx_mday.to_s - elsif flags.include?('0') - sprintf('%02d', tmx_mday) + elsif flags & FLAG_ZERO != 0 + TWO_DIGIT[tmx_mday] else sprintf('%2d', tmx_mday) end when 'j' # Day of the year (001-366) - if flags.include?('-') + if flags & FLAG_MINUS != 0 tmx_yday.to_s else sprintf('%03d', tmx_yday) end when 'H' # Hour (00-23) - if flags.include?('-') + if flags & FLAG_MINUS != 0 tmx_hour.to_s - elsif flags.include?('_') + elsif flags & FLAG_SPACE != 0 sprintf('%2d', tmx_hour) else - sprintf('%02d', tmx_hour) + TWO_DIGIT[tmx_hour] end when 'k' # Hour (0-23) blank-padded sprintf('%2d', tmx_hour) when 'I' # Hour (01-12) h = tmx_hour % 12 h = 12 if h.zero? - if flags.include?('-') + if flags & FLAG_MINUS != 0 h.to_s - elsif flags.include?('_') + elsif flags & FLAG_SPACE != 0 sprintf('%2d', h) else - sprintf('%02d', h) + TWO_DIGIT[h] end when 'l' # Hour (1-12) blank filled h = tmx_hour % 12 h = 12 if h.zero? sprintf('%2d', h) when 'M' # Minutes (00-59) - if flags.include?('-') + if flags & FLAG_MINUS != 0 tmx_min.to_s - elsif flags.include?('_') + elsif flags & FLAG_SPACE != 0 sprintf('%2d', tmx_min) else - sprintf('%02d', tmx_min) + TWO_DIGIT[tmx_min] end when 'S' # Seconds (00-59) - if flags.include?('-') + if flags & FLAG_MINUS != 0 tmx_sec.to_s - elsif flags.include?('_') + elsif flags & FLAG_SPACE != 0 sprintf('%2d', tmx_sec) else - sprintf('%02d', tmx_sec) + TWO_DIGIT[tmx_sec] end when 'L' # Milliseconds (000-999) sprintf('%09d', (tmx_sec_fraction * 1_000_000_000).floor) @@ -451,25 +604,26 @@ def get_base_format(spec, flags = '') when 'u' # Day of the week (1-7, Monday is 1) tmx_cwday.to_s when 'U' # Week number (00-53, Sunday start) - sprintf('%02d', tmx_wnum0) + TWO_DIGIT[tmx_wnum0] when 'W' # Week number (00-53, Monday start) - sprintf('%02d', tmx_wnum1) + TWO_DIGIT[tmx_wnum1] when 'V' # ISO week number (01-53) - sprintf('%02d', tmx_cweek) + TWO_DIGIT[tmx_cweek] when 'G' # ISO week year y = tmx_cwyear - prec = y < 0 ? 5 : 4 - if flags.include?('-') + if flags & FLAG_MINUS != 0 y.to_s - elsif flags.include?('_') - sprintf("%#{prec}d", y) + elsif flags & FLAG_SPACE != 0 + sprintf("%#{y < 0 ? 5 : 4}d", y) + elsif y >= 0 && y <= 9999 + FOUR_DIGIT[y] else - sprintf("%0#{prec}d", y) + sprintf("%0#{y < 0 ? 5 : 4}d", y) end when 'g' # ISO week year (2 digits) - sprintf('%02d', tmx_cwyear % 100) + TWO_DIGIT[tmx_cwyear % 100] when 'z' # Time Zone Offset (+0900) — handled by format_z in format_spec - format_z(tmx_offset, '', '', 0) + format_z(tmx_offset, -1, 0, 0) when 'Z' # Time Zone Name tmx_zone || '' when 's' # Number of seconds since the Unix epoch @@ -511,14 +665,14 @@ def get_base_format(spec, flags = '') def apply_width(str, width, flags, default_pad = ' ') # '-' flag means no padding at all - return str if flags.include?('-') + return str if flags & FLAG_MINUS != 0 return str if str.length >= width # Determine a padding character. padding = - if flags.include?('0') + if flags & FLAG_ZERO != 0 '0' - elsif flags.include?('_') + elsif flags & FLAG_SPACE != 0 ' ' else default_pad @@ -529,7 +683,8 @@ def apply_width(str, width, flags, default_pad = ' ') # C: format %z with width/flags/colons support # Matches date_strftime.c case 'z' logic exactly. - def format_z(offset, width_str, flags, colons) + # width: integer (-1 = not specified), flags: integer bitmask + def format_z(offset, width, flags, colons) sign = offset < 0 ? '-' : '+' aoff = offset.abs hours = aoff / 3600 @@ -538,9 +693,9 @@ def format_z(offset, width_str, flags, colons) hl = hours < 10 ? 1 : 2 # actual digits needed for hours hw = 2 # default hour width - hw = 1 if flags.include?('-') && hl == 1 + hw = 1 if flags & FLAG_MINUS != 0 && hl == 1 - precision = width_str.empty? ? -1 : width_str.to_i + precision = width # -1 means not specified # Calculate fixed chars (everything except hour digits) per colons variant fixed = case colons @@ -565,7 +720,7 @@ def format_z(offset, width_str, flags, colons) result = String.new # C: space padding — print spaces before sign, reduce hour precision - if flags.include?('_') && hp > hl + if flags & FLAG_SPACE != 0 && hp > hl result << ' ' * (hp - hl) hp = hl end diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index e73bfc55..d4889ca6 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -1,4 +1,5 @@ # frozen_string_literal: true +require 'strscan' # Implementation of ruby/date/ext/date/date_strptime.c class Date @@ -19,37 +20,85 @@ class << self # # Related: Date.strptime (returns a \Date object). def _strptime(string, format = '%F') - str = string.dup - pos = 0 + # Fast paths for the most common format strings. + case format + when '%F', '%Y-%m-%d' + m = /\A([+-]?\d+)-(\d{1,2})-(\d{1,2})/.match(string) + return nil unless m + mon = m[2].to_i + mday = m[3].to_i + return nil if mon < 1 || mon > 12 || mday < 1 || mday > 31 + h = { year: m[1].to_i, mon: mon, mday: mday } + rest = m.post_match + h[:leftover] = rest unless rest.empty? + return h + + when '%Y-%m-%d %H:%M:%S' + m = /\A([+-]?\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})/.match(string) + return nil unless m + mon = m[2].to_i + mday = m[3].to_i + hour = m[4].to_i + min = m[5].to_i + sec = m[6].to_i + return nil if mon < 1 || mon > 12 || mday < 1 || mday > 31 + return nil if hour > 24 || min > 59 || sec > 60 + h = { year: m[1].to_i, mon: mon, mday: mday, hour: hour, min: min, sec: sec } + rest = m.post_match + h[:leftover] = rest unless rest.empty? + return h + + when '%Y-%m-%dT%H:%M:%S' + m = /\A([+-]?\d+)-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2})/.match(string) + return nil unless m + mon = m[2].to_i + mday = m[3].to_i + hour = m[4].to_i + min = m[5].to_i + sec = m[6].to_i + return nil if mon < 1 || mon > 12 || mday < 1 || mday > 31 + return nil if hour > 24 || min > 59 || sec > 60 + h = { year: m[1].to_i, mon: mon, mday: mday, hour: hour, min: min, sec: sec } + rest = m.post_match + h[:leftover] = rest unless rest.empty? + return h + end + + ss = StringScanner.new(string) hash = {} i = 0 - while i < format.length - if format[i] == '%' && i + 1 < format.length + fmt_len = format.length + while i < fmt_len + fb = format.getbyte(i) + if fb == 37 && i + 1 < fmt_len # '%' i += 1 # Parse modifier (E, O) modifier = nil - if i < format.length && (format[i] == 'E' || format[i] == 'O') - modifier = format[i] + fb2 = format.getbyte(i) + if i < fmt_len && (fb2 == 69 || fb2 == 79) # 'E' == 69, 'O' == 79 + modifier = fb2 == 69 ? 'E' : 'O' i += 1 end # Parse colons for %:z, %::z, %:::z colons = 0 - while i < format.length && format[i] == ':' + while i < fmt_len && format.getbyte(i) == 58 # ':' colons += 1 i += 1 end - # Parse width - width_str = String.new - while i < format.length && format[i] =~ /[0-9]/ - width_str << format[i] + # Parse width as integer (avoids String allocation and regex digit check) + field_width = nil + while i < fmt_len + db = format.getbyte(i) + break if db < 48 || db > 57 # '0'..'9' + field_width = (field_width || 0) * 10 + db - 48 i += 1 end - break if i >= format.length + break if i >= fmt_len spec = format[i] i += 1 @@ -65,10 +114,9 @@ def _strptime(string, format = '%F') false end unless valid - # Invalid modifier - try to match literal - literal = "%#{modifier}#{':' * colons}#{width_str}#{spec}" - if str[pos, literal.length] == literal - pos += literal.length + literal = "%#{modifier}#{':' * colons}#{field_width}#{spec}" + if ss.string[ss.pos, literal.length] == literal + ss.pos += literal.length else return nil end @@ -78,9 +126,9 @@ def _strptime(string, format = '%F') # Handle colon+z if colons > 0 && spec == 'z' - result = _strptime_zone_colon(str, pos, colons) + result = _strptime_zone_colon(ss.string, ss.pos, colons) return nil unless result - pos = result[:pos] + ss.pos = result[:pos] hash[:zone] = result[:zone] hash[:offset] = result[:offset] next @@ -89,33 +137,25 @@ def _strptime(string, format = '%F') return nil end - # Determine field width - field_width = width_str.empty? ? nil : width_str.to_i - # C: NUM_PATTERN_P() - check if next format element is a digit-consuming pattern. - # Used by %C, %G, %L, %N, %Y to limit digit consumption when adjacent. next_is_num = num_pattern_p(format, i) - result = _strptime_spec(str, pos, spec, field_width, hash, next_is_num) - return nil unless result - pos = result[:pos] - hash.merge!(result[:hash]) if result[:hash] - elsif format[i] == '%' && i + 1 == format.length - # Trailing % - match literal - if pos < str.length && str[pos] == '%' - pos += 1 + return nil unless _strptime_spec(ss, spec, field_width, hash, next_is_num) + elsif fb == 37 && i + 1 == fmt_len # Trailing % - match literal + if ss.string.getbyte(ss.pos) == 37 # '%' + ss.pos += 1 else return nil end i += 1 - elsif format[i] =~ /\s/ + elsif fb == 32 || fb == 9 || fb == 10 || fb == 13 || fb == 11 || fb == 12 # whitespace # Whitespace in format matches zero or more whitespace in input i += 1 - pos += 1 while pos < str.length && str[pos] =~ /\s/ + skip_ws(ss) else # Literal match - if pos < str.length && str[pos] == format[i] - pos += 1 + if ss.string.getbyte(ss.pos) == fb + ss.pos += 1 else return nil end @@ -124,29 +164,15 @@ def _strptime(string, format = '%F') end # Store leftover if any - if pos < str.length - hash[:leftover] = str[pos..] - end + hash[:leftover] = ss.rest unless ss.eos? # --- Post-processing (C: date__strptime, date_strptime.c:524-546) --- # C: cent = del_hash("_cent"); - # Apply _cent to both cwyear and year. - # Note: The inline _century approach in %C/%y/%g handlers covers most - # cases, but this post-processing ensures correctness for all orderings - # and applies century to both year and cwyear simultaneously. - # We delete _century and _century_set here to keep the hash clean, - # matching C's del_hash("_cent") behavior. hash.delete(:_century) hash.delete(:_century_set) # C: merid = del_hash("_merid"); - # Apply _merid to hour: hour = (hour % 12) + merid - # This handles both %I (12-hour) and %H (24-hour) correctly: - # %I=12 + AM(0) → (12 % 12) + 0 = 0 - # %I=12 + PM(12) → (12 % 12) + 12 = 12 - # %I=4 + PM(12) → (4 % 12) + 12 = 16 - # %I=4 + AM(0) → (4 % 12) + 0 = 4 merid = hash.delete(:_merid) if merid hour = hash[:hour] @@ -195,431 +221,464 @@ def strptime(string = JULIAN_EPOCH_DATE, format = '%F', start = DEFAULT_SG) private + # Advances StringScanner past zero or more ASCII whitespace bytes + # (space=32, tab=9, LF=10, CR=13, VT=11, FF=12). + # Avoids regex overhead compared to ss.skip(/[ \t\n\r\v\f]*/). + def skip_ws(ss) + str = ss.string + p = ss.pos + len = str.length + while p < len + b = str.getbyte(p) + break unless b == 32 || b == 9 || b == 10 || b == 13 || b == 11 || b == 12 + p += 1 + end + ss.pos = p + end + + # Scans unsigned decimal integer from +str+ at +pos+, up to +max+ digits. + # Returns [value, new_pos] or nil if no digit found. + def scan_uint(str, pos, max) + val = 0 + count = 0 + len = str.length + while count < max && pos + count < len + b = str.getbyte(pos + count) + break unless b >= 48 && b <= 57 # '0'..'9' + val = val * 10 + b - 48 + count += 1 + end + count > 0 ? [val, pos + count] : nil + end + + # Scans signed decimal integer (optional leading +/-) from +str+ at +pos+. + # Returns [value, new_pos] or nil if no digit found. + def scan_sint(str, pos, max) + b = str.getbyte(pos) + if b == 43 # '+' + result = scan_uint(str, pos + 1, max) + result + elsif b == 45 # '-' + result = scan_uint(str, pos + 1, max) + result ? [-result[0], result[1]] : nil + else + scan_uint(str, pos, max) + end + end + # C: num_pattern_p (date_strptime.c:48) # Returns true if the format string at position `i` starts with a # digit-consuming pattern (a literal digit or a %-specifier that reads digits). + # Uses byte-level operations to avoid String allocations. def num_pattern_p(format, i) return false if i >= format.length - c = format[i] - return true if c =~ /\d/ - if c == '%' + b = format.getbyte(i) + return true if b >= 48 && b <= 57 # '0'..'9' + if b == 37 # '%' i += 1 return false if i >= format.length - # Skip E/O modifier - if format[i] == 'E' || format[i] == 'O' + b2 = format.getbyte(i) + # Skip E/O modifier (E=69, O=79) + if b2 == 69 || b2 == 79 i += 1 return false if i >= format.length + b2 = format.getbyte(i) end - s = format[i] - return true if s =~ /\d/ || NUM_PATTERN_SPECS.include?(s) + return true if (b2 >= 48 && b2 <= 57) || NUM_PATTERN_SPECS_TABLE[b2] end false end - def _strptime_spec(str, pos, spec, width, context_hash, next_is_num = false) - h = {} + # Modifies +hash+ in-place with parsed values for +spec+. + # Advances +ss+ position on success. Returns true on success, nil on failure. + def _strptime_spec(ss, spec, width, hash, next_is_num = false) + str = ss.string + pos = ss.pos case spec when 'Y' # Full year (possibly negative) - # C: if (NUM_PATTERN_P()) READ_DIGITS(n, 4); else READ_DIGITS_MAX(n); - if width - w = width - elsif next_is_num - w = 4 - else - w = 40 # effectively unlimited - end - m = str[pos..].match(/\A([+-]?\d{1,#{w}})/) - return nil unless m - h[:year] = m[1].to_i - { pos: pos + m[0].length, hash: h } + year, new_pos = scan_sint(str, pos, width || (next_is_num ? 4 : 40)) + return nil unless year + hash[:year] = year + ss.pos = new_pos + true when 'C' # Century - # C: if (NUM_PATTERN_P()) READ_DIGITS(n, 2); else READ_DIGITS_MAX(n); - if width - w = width - elsif next_is_num - w = 2 - else - w = 40 + century, new_pos = scan_sint(str, pos, width || (next_is_num ? 2 : 40)) + return nil unless century + hash[:_century] = century + if hash[:year] && !hash[:_century_set] + hash[:year] = century * 100 + (hash[:year] % 100) + hash[:_century_set] = true end - m = str[pos..].match(/\A([+-]?\d{1,#{w}})/) - return nil unless m - century = m[1].to_i - h[:_century] = century - if context_hash[:year] && !context_hash[:_century_set] - h[:year] = century * 100 + (context_hash[:year] % 100) - h[:_century_set] = true - end - { pos: pos + m[0].length, hash: h } + ss.pos = new_pos + true when 'y' # 2-digit year - w = width || 2 - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - y = m[1].to_i - if context_hash[:_century] - h[:year] = context_hash[:_century] * 100 + y - h[:_century_set] = true + y, new_pos = scan_uint(str, pos, width || 2) + return nil unless y + if hash[:_century] + hash[:year] = hash[:_century] * 100 + y + hash[:_century_set] = true else - h[:year] = y >= 69 ? y + 1900 : y + 2000 + hash[:year] = y >= 69 ? y + 1900 : y + 2000 end - { pos: pos + m[0].length, hash: h } + ss.pos = new_pos + true when 'm' # Month (01-12) - w = width || 2 - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - mon = m[1].to_i + mon, new_pos = scan_uint(str, pos, width || 2) + return nil unless mon return nil if mon < 1 || mon > 12 - h[:mon] = mon - { pos: pos + m[0].length, hash: h } + hash[:mon] = mon + ss.pos = new_pos + true when 'd', 'e' # Day of month - # C: if (str[si] == ' ') { si++; READ_DIGITS(n, 1); } else { READ_DIGITS(n, 2); } - if str[pos] == ' ' - m = str[pos + 1..].match(/\A(\d)/) - return nil unless m - day = m[1].to_i + if str.getbyte(pos) == 32 # ' ' + day, new_pos = scan_uint(str, pos + 1, 1) + return nil unless day return nil if day < 1 || day > 31 - h[:mday] = day - { pos: pos + 1 + m[0].length, hash: h } + hash[:mday] = day + ss.pos = new_pos else - w = width || 2 - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - day = m[1].to_i + day, new_pos = scan_uint(str, pos, width || 2) + return nil unless day return nil if day < 1 || day > 31 - h[:mday] = day - { pos: pos + m[0].length, hash: h } + hash[:mday] = day + ss.pos = new_pos end + true when 'j' # Day of year (001-366) - w = width || 3 - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - yday = m[1].to_i + yday, new_pos = scan_uint(str, pos, width || 3) + return nil unless yday return nil if yday < 1 || yday > 366 - h[:yday] = yday - { pos: pos + m[0].length, hash: h } + hash[:yday] = yday + ss.pos = new_pos + true when 'H', 'k' # Hour (00-24) - # C: if (str[si] == ' ') { si++; READ_DIGITS(n, 1); } else { READ_DIGITS(n, 2); } - if str[pos] == ' ' - m = str[pos + 1..].match(/\A(\d)/) - return nil unless m - hour = m[1].to_i + if str.getbyte(pos) == 32 # ' ' + hour, new_pos = scan_uint(str, pos + 1, 1) + return nil unless hour return nil if hour > 24 - h[:hour] = hour - { pos: pos + 1 + m[0].length, hash: h } + hash[:hour] = hour + ss.pos = new_pos else - w = width || 2 - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - hour = m[1].to_i + hour, new_pos = scan_uint(str, pos, width || 2) + return nil unless hour return nil if hour > 24 - h[:hour] = hour - { pos: pos + m[0].length, hash: h } + hash[:hour] = hour + ss.pos = new_pos end + true when 'I', 'l' # Hour (01-12) - # C: if (str[si] == ' ') { si++; READ_DIGITS(n, 1); } else { READ_DIGITS(n, 2); } - if str[pos] == ' ' - m = str[pos + 1..].match(/\A(\d)/) - return nil unless m - hour = m[1].to_i + if str.getbyte(pos) == 32 # ' ' + hour, new_pos = scan_uint(str, pos + 1, 1) + return nil unless hour return nil if hour < 1 || hour > 12 - h[:hour] = hour - { pos: pos + 1 + m[0].length, hash: h } + hash[:hour] = hour + ss.pos = new_pos else - w = width || 2 - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - hour = m[1].to_i + hour, new_pos = scan_uint(str, pos, width || 2) + return nil unless hour return nil if hour < 1 || hour > 12 - h[:hour] = hour # C stores raw value; _merid post-processing applies % 12 - { pos: pos + m[0].length, hash: h } + hash[:hour] = hour + ss.pos = new_pos end + true when 'M' # Minute (00-59) - w = width || 2 - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - min = m[1].to_i + min, new_pos = scan_uint(str, pos, width || 2) + return nil unless min return nil if min > 59 - h[:min] = min - { pos: pos + m[0].length, hash: h } + hash[:min] = min + ss.pos = new_pos + true when 'S' # Second (00-60) - w = width || 2 - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - sec = m[1].to_i + sec, new_pos = scan_uint(str, pos, width || 2) + return nil unless sec return nil if sec > 60 - h[:sec] = sec - { pos: pos + m[0].length, hash: h } - - when 'L' # Milliseconds - # C: if (NUM_PATTERN_P()) READ_DIGITS(n, 3); else READ_DIGITS_MAX(n); - if width - w = width - elsif next_is_num - w = 3 - else - w = 40 + hash[:sec] = sec + ss.pos = new_pos + true + + when 'L' # Milliseconds — normalize digit string to 3-digit precision + w = width || (next_is_num ? 3 : 40) + val, count = 0, 0 + str_len = str.length + while count < w && pos + count < str_len + b = str.getbyte(pos + count) + break unless b >= 48 && b <= 57 + val = val * 10 + b - 48 + count += 1 end - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - frac_str = m[1].ljust(3, '0')[0, 3] - h[:sec_fraction] = Rational(frac_str.to_i, 1000) - { pos: pos + m[0].length, hash: h } - - when 'N' # Nanoseconds - # C: if (NUM_PATTERN_P()) READ_DIGITS(n, 9); else READ_DIGITS_MAX(n); - if width - w = width - elsif next_is_num - w = 9 - else - w = 40 + return nil if count == 0 + val *= 10 ** (3 - count) if count < 3 + val /= 10 ** (count - 3) if count > 3 + hash[:sec_fraction] = Rational(val, 1000) + ss.pos = pos + count + true + + when 'N' # Nanoseconds — normalize digit string to 9-digit precision + w = width || (next_is_num ? 9 : 40) + val, count = 0, 0 + str_len = str.length + while count < w && pos + count < str_len + b = str.getbyte(pos + count) + break unless b >= 48 && b <= 57 + val = val * 10 + b - 48 + count += 1 end - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - frac_str = m[1].ljust(9, '0')[0, 9] - h[:sec_fraction] = Rational(frac_str.to_i, 1_000_000_000) - { pos: pos + m[0].length, hash: h } + return nil if count == 0 + val *= 10 ** (9 - count) if count < 9 + val /= 10 ** (count - 9) if count > 9 + hash[:sec_fraction] = Rational(val, 1_000_000_000) + ss.pos = pos + count + true when 'p', 'P' # AM/PM - # C: set_hash("_merid", INT2FIX(hour)); - # Store _merid value (0 for AM, 12 for PM) for post-processing. - # This avoids order-dependency: %p can appear before or after %I/%H. - m = str[pos..].match(/\A(a\.?m\.?|p\.?m\.?)/i) + m = ss.scan(/a\.?m\.?|p\.?m\.?/i) return nil unless m - ampm = m[1].delete('.').upcase - h[:_merid] = (ampm == 'PM') ? 12 : 0 - { pos: pos + m[0].length, hash: h } + ampm = m.delete('.').upcase + hash[:_merid] = (ampm == 'PM') ? 12 : 0 + true when 'A', 'a' # Day name (full or abbreviated) - DAYNAMES.each_with_index do |name, idx| - next unless name - # Try full name first, then abbreviated - [name, ABBR_DAYNAMES[idx]].each do |n| - next unless n - if str[pos, n.length]&.downcase == n.downcase - h[:wday] = idx - return { pos: pos + n.length, hash: h } + # Zero-alloc integer key from 3 bytes (lowercase via | 0x20). + # Check byte 4 to skip full-name string comparison in the common case. + b0 = str.getbyte(pos) + b1 = str.getbyte(pos + 1) + b2 = str.getbyte(pos + 2) + if b0 && b1 && b2 + k0 = b0 | 0x20; k1 = b1 | 0x20; k2 = b2 | 0x20 + if k0 >= 97 && k0 <= 122 && k1 >= 97 && k1 <= 122 && k2 >= 97 && k2 <= 122 + ikey = (k0 << 16) | (k1 << 8) | k2 + if (info = STRPTIME_DAYNAME_BY_INT_KEY[ikey]) + idx, full, full_len, abbr_len = info + b3 = str.getbyte(pos + abbr_len) + # If next byte is non-alpha, it's an abbreviated name. + if b3.nil? || (t = b3 | 0x20) < 97 || t > 122 + hash[:wday] = idx + ss.pos = pos + abbr_len + elsif str[pos, full_len]&.downcase == full + hash[:wday] = idx + ss.pos = pos + full_len + else + hash[:wday] = idx + ss.pos = pos + abbr_len + end + true end end end - return nil when 'B', 'b', 'h' # Month name (full or abbreviated) - MONTHNAMES.each_with_index do |name, idx| - next unless name - # Try full name first, then abbreviated - [name, ABBR_MONTHNAMES[idx]].each do |n| - next unless n - if str[pos, n.length]&.downcase == n.downcase - h[:mon] = idx - return { pos: pos + n.length, hash: h } + # Zero-alloc integer key from 3 bytes (lowercase via | 0x20). + b0 = str.getbyte(pos) + b1 = str.getbyte(pos + 1) + b2 = str.getbyte(pos + 2) + if b0 && b1 && b2 + k0 = b0 | 0x20; k1 = b1 | 0x20; k2 = b2 | 0x20 + if k0 >= 97 && k0 <= 122 && k1 >= 97 && k1 <= 122 && k2 >= 97 && k2 <= 122 + ikey = (k0 << 16) | (k1 << 8) | k2 + if (info = STRPTIME_MONNAME_BY_INT_KEY[ikey]) + idx, full, full_len, abbr_len = info + b3 = str.getbyte(pos + abbr_len) + if b3.nil? || (t = b3 | 0x20) < 97 || t > 122 + hash[:mon] = idx + ss.pos = pos + abbr_len + elsif str[pos, full_len]&.downcase == full + hash[:mon] = idx + ss.pos = pos + full_len + else + hash[:mon] = idx + ss.pos = pos + abbr_len + end + true end end end - return nil when 'w' # Weekday number (0-6, Sunday=0) - m = str[pos..].match(/\A(\d)/) - return nil unless m - wday = m[1].to_i - return nil if wday > 6 - h[:wday] = wday - { pos: pos + m[0].length, hash: h } + b = str.getbyte(pos) + return nil unless b && b >= 48 && b <= 54 # '0'..'6' + hash[:wday] = b - 48 + ss.pos = pos + 1 + true when 'u' # Weekday number (1-7, Monday=1) - m = str[pos..].match(/\A(\d)/) - return nil unless m - cwday = m[1].to_i - return nil if cwday < 1 || cwday > 7 - h[:cwday] = cwday - { pos: pos + m[0].length, hash: h } + b = str.getbyte(pos) + return nil unless b && b >= 49 && b <= 55 # '1'..'7' + hash[:cwday] = b - 48 + ss.pos = pos + 1 + true when 'U' # Week number (Sunday start, 00-53) - w = width || 2 - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - wnum = m[1].to_i + wnum, new_pos = scan_uint(str, pos, width || 2) + return nil unless wnum return nil if wnum > 53 - h[:wnum0] = wnum - { pos: pos + m[0].length, hash: h } + hash[:wnum0] = wnum + ss.pos = new_pos + true when 'W' # Week number (Monday start, 00-53) - w = width || 2 - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - wnum = m[1].to_i + wnum, new_pos = scan_uint(str, pos, width || 2) + return nil unless wnum return nil if wnum > 53 - h[:wnum1] = wnum - { pos: pos + m[0].length, hash: h } + hash[:wnum1] = wnum + ss.pos = new_pos + true when 'V' # ISO week number (01-53) - w = width || 2 - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - cweek = m[1].to_i + cweek, new_pos = scan_uint(str, pos, width || 2) + return nil unless cweek return nil if cweek < 1 || cweek > 53 - h[:cweek] = cweek - { pos: pos + m[0].length, hash: h } + hash[:cweek] = cweek + ss.pos = new_pos + true when 'G' # ISO week year - # C: if (NUM_PATTERN_P()) READ_DIGITS(n, 4); else READ_DIGITS_MAX(n); - if width - w = width - elsif next_is_num - w = 4 - else - w = 40 - end - m = str[pos..].match(/\A([+-]?\d{1,#{w}})/) - return nil unless m - h[:cwyear] = m[1].to_i - { pos: pos + m[0].length, hash: h } + cwyear, new_pos = scan_sint(str, pos, width || (next_is_num ? 4 : 40)) + return nil unless cwyear + hash[:cwyear] = cwyear + ss.pos = new_pos + true when 'g' # ISO week year (2-digit) - w = width || 2 - m = str[pos..].match(/\A(\d{1,#{w}})/) - return nil unless m - y = m[1].to_i - if context_hash[:_century] - h[:cwyear] = context_hash[:_century] * 100 + y - h[:_century_set] = true + y, new_pos = scan_uint(str, pos, width || 2) + return nil unless y + if hash[:_century] + hash[:cwyear] = hash[:_century] * 100 + y + hash[:_century_set] = true else - h[:cwyear] = y >= 69 ? y + 1900 : y + 2000 + hash[:cwyear] = y >= 69 ? y + 1900 : y + 2000 end - { pos: pos + m[0].length, hash: h } + ss.pos = new_pos + true when 'Z', 'z' # Timezone result = _strptime_zone(str, pos) return nil unless result - h[:zone] = result[:zone] - h[:offset] = result[:offset] unless result[:offset].nil? - { pos: result[:pos], hash: h } + hash[:zone] = result[:zone] + hash[:offset] = result[:offset] unless result[:offset].nil? + ss.pos = result[:pos] + true when 's' # Seconds since epoch - m = str[pos..].match(/\A([+-]?\d+)/) - return nil unless m - h[:seconds] = m[1].to_i - { pos: pos + m[0].length, hash: h } + secs, new_pos = scan_sint(str, pos, 40) + return nil unless secs + hash[:seconds] = secs + ss.pos = new_pos + true when 'Q' # Milliseconds since epoch - m = str[pos..].match(/\A([+-]?\d+)/) - return nil unless m - h[:seconds] = Rational(m[1].to_i, 1000) - { pos: pos + m[0].length, hash: h } + msecs, new_pos = scan_sint(str, pos, 40) + return nil unless msecs + hash[:seconds] = Rational(msecs, 1000) + ss.pos = new_pos + true - when 'n' # Newline - m = str[pos..].match(/\A\s+/) - if m - { pos: pos + m[0].length, hash: h } - else - { pos: pos, hash: h } - end - - when 't' # Tab - m = str[pos..].match(/\A\s+/) - if m - { pos: pos + m[0].length, hash: h } - else - { pos: pos, hash: h } - end + when 'n', 't' # Newline / Tab — match any whitespace + skip_ws(ss) + true when '%' # Literal % - if pos < str.length && str[pos] == '%' - { pos: pos + 1, hash: h } - else - return nil - end + return nil unless str.getbyte(pos) == 37 # '%' + ss.pos = pos + 1 + true when 'F' # %Y-%m-%d - result = _strptime_composite(str, pos, '%Y-%m-%d', context_hash) + result = _strptime_composite(ss, '%Y-%m-%d', hash) return nil unless result - { pos: result[:pos], hash: result[:hash] } + hash.merge!(result) + true when 'D', 'x' # %m/%d/%y - result = _strptime_composite(str, pos, '%m/%d/%y', context_hash) + result = _strptime_composite(ss, '%m/%d/%y', hash) return nil unless result - { pos: result[:pos], hash: result[:hash] } + hash.merge!(result) + true when 'T', 'X' # %H:%M:%S - result = _strptime_composite(str, pos, '%H:%M:%S', context_hash) + result = _strptime_composite(ss, '%H:%M:%S', hash) return nil unless result - { pos: result[:pos], hash: result[:hash] } + hash.merge!(result) + true when 'R' # %H:%M - result = _strptime_composite(str, pos, '%H:%M', context_hash) + result = _strptime_composite(ss, '%H:%M', hash) return nil unless result - { pos: result[:pos], hash: result[:hash] } + hash.merge!(result) + true when 'r' # %I:%M:%S %p - result = _strptime_composite(str, pos, '%I:%M:%S %p', context_hash) + result = _strptime_composite(ss, '%I:%M:%S %p', hash) return nil unless result - { pos: result[:pos], hash: result[:hash] } + hash.merge!(result) + true when 'c' # %a %b %e %H:%M:%S %Y - result = _strptime_composite(str, pos, '%a %b %e %H:%M:%S %Y', context_hash) + result = _strptime_composite(ss, '%a %b %e %H:%M:%S %Y', hash) return nil unless result - { pos: result[:pos], hash: result[:hash] } + hash.merge!(result) + true when 'v' # %e-%b-%Y - result = _strptime_composite(str, pos, '%e-%b-%Y', context_hash) + result = _strptime_composite(ss, '%e-%b-%Y', hash) return nil unless result - { pos: result[:pos], hash: result[:hash] } + hash.merge!(result) + true when '+' # %a %b %e %H:%M:%S %Z %Y - result = _strptime_composite(str, pos, '%a %b %e %H:%M:%S %Z %Y', context_hash) + result = _strptime_composite(ss, '%a %b %e %H:%M:%S %Z %Y', hash) return nil unless result - { pos: result[:pos], hash: result[:hash] } + hash.merge!(result) + true else # Unknown specifier - try to match literal literal = "%#{spec}" if str[pos, literal.length] == literal - { pos: pos + literal.length, hash: h } + ss.pos = pos + literal.length + true else - return nil + nil end end end - def _strptime_composite(str, pos, format, context_hash) + def _strptime_composite(ss, format, context_hash) merged_hash = context_hash.dup i = 0 - while i < format.length - if format[i] == '%' && i + 1 < format.length + fmt_len = format.length + while i < fmt_len + fb = format.getbyte(i) + if fb == 37 && i + 1 < fmt_len # '%' i += 1 spec = format[i] i += 1 - result = _strptime_spec(str, pos, spec, nil, merged_hash) - return nil unless result - pos = result[:pos] - merged_hash.merge!(result[:hash]) if result[:hash] - elsif format[i] =~ /\s/ + return nil unless _strptime_spec(ss, spec, nil, merged_hash) + elsif fb == 32 || fb == 9 || fb == 10 || fb == 13 || fb == 11 || fb == 12 # whitespace i += 1 - pos += 1 while pos < str.length && str[pos] =~ /\s/ + skip_ws(ss) else - if pos < str.length && str[pos] == format[i] - pos += 1 + if ss.string.getbyte(ss.pos) == fb + ss.pos += 1 else return nil end i += 1 end end - # Return only newly parsed keys + # Return only newly parsed or updated keys new_hash = {} merged_hash.each { |k, v| new_hash[k] = v unless context_hash.key?(k) && context_hash[k] == v } - # Ensure updated values are included merged_hash.each { |k, v| new_hash[k] = v if context_hash[k] != v } - { pos: pos, hash: new_hash } + new_hash end def _strptime_zone(str, pos) From 8909ef5c1669a1005f3e16faf5337b002325d170 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 25 Feb 2026 15:40:10 +0900 Subject: [PATCH 005/144] Rewrite Date and DateTime from C extension to pure Ruby Replace the C extension (ext/date/date_core.c, date_parse.c, date_strftime.c, date_strptime.c) with a pure Ruby implementation while maintaining full compatibility with the existing test suite (143 tests, 162,593 assertions). Key implementation files: - lib/date/core.rb: Date class with calendar conversions, arithmetic, and comparison operators - lib/date/datetime.rb: DateTime class with time component handling - lib/date/parse.rb: Date parsing (_parse, _rfc3339, _httpdate, _rfc2822, _xmlschema, _iso8601, _jisx0301) with byte-level fast paths - lib/date/strftime.rb: strftime formatting engine - lib/date/strptime.rb: strptime parsing engine - lib/date/constants.rb: Consolidated constants - lib/date/zonetab.rb: Timezone lookup table - lib/date/time.rb: Time conversion methods Performance optimizations: - Byte-level fast paths for common date format parsing (ISO 8601, RFC 3339, RFC 2822, HTTP dates) - Integer-based JD comparison instead of Rational arithmetic - Lazy evaluation for civil date computation and deconstruct_keys - Inlined private method calls to reduce __send__ overhead - O(1) boolean lookup tables replacing Array linear scans in strptime --- lib/date.rb | 2 + lib/date/constants.rb | 591 +++-- lib/date/core.rb | 5385 ++++++++++++----------------------------- lib/date/datetime.rb | 1415 ++++++----- lib/date/parse.rb | 3799 +++++++++++------------------ lib/date/strftime.rb | 1157 ++++----- lib/date/strptime.rb | 2100 ++++++++++------ lib/date/time.rb | 64 +- 8 files changed, 6016 insertions(+), 8497 deletions(-) diff --git a/lib/date.rb b/lib/date.rb index 3ad70c9c..1bb5da3f 100644 --- a/lib/date.rb +++ b/lib/date.rb @@ -1,6 +1,8 @@ # frozen_string_literal: true # date.rb: Written by Tadayoshi Funaba 1998-2011 +require 'timeout' + if RUBY_VERSION >= "3.3" require_relative "date/version" require_relative "date/constants" diff --git a/lib/date/constants.rb b/lib/date/constants.rb index fcf8e2b5..c9333b6a 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -3,26 +3,13 @@ # Constants class Date - HAVE_JD = 0b00000001 # 1 - HAVE_DF = 0b00000010 # 2 - HAVE_CIVIL = 0b00000100 # 4 - HAVE_TIME = 0b00001000 # 8 - COMPLEX_DAT = 0b10000000 # 128 - private_constant :HAVE_JD, :HAVE_DF, :HAVE_CIVIL, :HAVE_TIME, :COMPLEX_DAT - - MONTHNAMES = [nil, "January", "February", "March", "April", "May", "June", - "July", "August", "September", "October", "November", "December"].freeze - ABBR_MONTHNAMES = [nil, "Jan", "Feb", "Mar", "Apr", "May", "Jun", - "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"].freeze + MONTHNAMES = [nil, 'January', 'February', 'March', 'April', 'May', 'June', + 'July', 'August', 'September', 'October', 'November', 'December'].freeze + ABBR_MONTHNAMES = [nil, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'].freeze DAYNAMES = %w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday].freeze ABBR_DAYNAMES = %w[Sun Mon Tue Wed Thu Fri Sat].freeze - # Pattern constants for regex - ABBR_DAYS_PATTERN = 'sun|mon|tue|wed|thu|fri|sat' - DAYS_PATTERN = 'sunday|monday|tuesday|wednesday|thursday|friday|saturday' - ABBR_MONTHS_PATTERN = 'jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec' - private_constant :ABBR_DAYS_PATTERN, :DAYS_PATTERN, :ABBR_MONTHS_PATTERN - ITALY = 2299161 # 1582-10-15 ENGLAND = 2361222 # 1752-09-14 JULIAN = Float::INFINITY @@ -31,205 +18,377 @@ class Date DEFAULT_SG = ITALY private_constant :DEFAULT_SG - MINUTE_IN_SECONDS = 60 - HOUR_IN_SECONDS = 3600 - DAY_IN_SECONDS = 86400 - HALF_DAYS_IN_SECONDS = DAY_IN_SECONDS / 2 - SECOND_IN_MILLISECONDS = 1000 - SECOND_IN_NANOSECONDS = 1_000_000_000 - private_constant :MINUTE_IN_SECONDS, :HOUR_IN_SECONDS, :DAY_IN_SECONDS, :SECOND_IN_MILLISECONDS, :SECOND_IN_NANOSECONDS, :HALF_DAYS_IN_SECONDS - - JC_PERIOD0 = 1461 # 365.25 * 4 - GC_PERIOD0 = 146097 # 365.2425 * 400 - CM_PERIOD0 = 71149239 # (lcm 7 1461 146097) - CM_PERIOD = (0xfffffff / CM_PERIOD0) * CM_PERIOD0 - CM_PERIOD_JCY = (CM_PERIOD / JC_PERIOD0) * 4 - CM_PERIOD_GCY = (CM_PERIOD / GC_PERIOD0) * 400 - private_constant :JC_PERIOD0, :GC_PERIOD0, :CM_PERIOD0, :CM_PERIOD, :CM_PERIOD_JCY, :CM_PERIOD_GCY - - REFORM_BEGIN_YEAR = 1582 - REFORM_END_YEAR = 1930 - REFORM_BEGIN_JD = 2298874 # ns 1582-01-01 - REFORM_END_JD = 2426355 # os 1930-12-31 - private_constant :REFORM_BEGIN_YEAR, :REFORM_END_YEAR, :REFORM_BEGIN_JD, :REFORM_END_JD - - SEC_WIDTH = 6 - MIN_WIDTH = 6 - HOUR_WIDTH = 5 - MDAY_WIDTH = 5 - MON_WIDTH = 4 - private_constant :SEC_WIDTH, :MIN_WIDTH, :HOUR_WIDTH, :MDAY_WIDTH, :MON_WIDTH - - SEC_SHIFT = 0 - MIN_SHIFT = SEC_WIDTH - HOUR_SHIFT = MIN_WIDTH + SEC_WIDTH - MDAY_SHIFT = HOUR_WIDTH + MIN_WIDTH + SEC_WIDTH - MON_SHIFT = MDAY_WIDTH + HOUR_WIDTH + MIN_WIDTH + SEC_WIDTH - private_constant :SEC_SHIFT, :MIN_SHIFT, :HOUR_SHIFT, :MDAY_SHIFT, :MON_SHIFT - - PK_MASK = ->(x) { (1 << x) - 1 } - private_constant :PK_MASK - - # Days in each month (non-leap and leap year) - MONTH_DAYS = [ - [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].freeze, # non-leap - [0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].freeze # leap + # Pre-computed lowercase byte arrays for fast case-insensitive name matching in strptime + ABBR_DAY_LOWER_BYTES = ABBR_DAYNAMES.map { |n| n.downcase.bytes.freeze }.freeze + DAY_LOWER_BYTES = DAYNAMES.map { |n| n.downcase.bytes.freeze }.freeze + ABBR_MONTH_LOWER_BYTES = ABBR_MONTHNAMES.each_with_object([]) { |n, a| + a << (n ? n.downcase.bytes.freeze : nil) + }.freeze + MONTH_LOWER_BYTES = MONTHNAMES.each_with_object([]) { |n, a| + a << (n ? n.downcase.bytes.freeze : nil) + }.freeze + private_constant :ABBR_DAY_LOWER_BYTES, :DAY_LOWER_BYTES, + :ABBR_MONTH_LOWER_BYTES, :MONTH_LOWER_BYTES + + # 3-byte integer key lookup tables for O(1) abbreviated name matching. + # Key = (byte0_lower << 16) | (byte1_lower << 8) | byte2_lower + # Value = [index, full_name_length] + ABBR_DAY_3KEY = ABBR_DAYNAMES.each_with_index.to_h { |n, i| + b = n.downcase.bytes + [(b[0] << 16) | (b[1] << 8) | b[2], [i, DAYNAMES[i].length].freeze] + }.freeze + ABBR_MONTH_3KEY = ABBR_MONTHNAMES.each_with_index.each_with_object({}) { |(n, i), h| + next if n.nil? + b = n.downcase.bytes + h[(b[0] << 16) | (b[1] << 8) | b[2]] = [i, MONTHNAMES[i].length].freeze + }.freeze + private_constant :ABBR_DAY_3KEY, :ABBR_MONTH_3KEY + + # Case-insensitive abbreviated month name -> month number (1-12) + ABBR_MONTH_NUM = ABBR_MONTHNAMES.each_with_index.each_with_object({}) { |(n, i), h| + next if n.nil? + h[n.downcase] = i + }.freeze + + # Case-insensitive abbreviated day name -> wday number (0-6) + ABBR_DAY_NUM = ABBR_DAYNAMES.each_with_index.to_h { |n, i| [n.downcase, i] }.freeze + private_constant :ABBR_MONTH_NUM, :ABBR_DAY_NUM + + JULIAN_EPOCH_DATE = '-4712-01-01'.freeze + JULIAN_EPOCH_DATETIME = '-4712-01-01T00:00:00+00:00'.freeze + JULIAN_EPOCH_DATETIME_RFC2822 = 'Mon, 1 Jan -4712 00:00:00 +0000'.freeze + JULIAN_EPOCH_DATETIME_HTTPDATE = 'Mon, 01 Jan -4712 00:00:00 GMT'.freeze + private_constant :JULIAN_EPOCH_DATE, :JULIAN_EPOCH_DATETIME, + :JULIAN_EPOCH_DATETIME_RFC2822, :JULIAN_EPOCH_DATETIME_HTTPDATE + + # === Calendar computation (from core.rb) === + + # Days in month for Gregorian calendar. + DAYS_IN_MONTH_GREGORIAN = [0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31].freeze + private_constant :DAYS_IN_MONTH_GREGORIAN + + # Precomputed month offset for Julian Day computation: + # GJD_MONTH_OFFSET[m] == (306001 * (gm + 1)) / 10000 + # where gm = m + 12 for m <= 2, else gm = m. + # Used to avoid an integer multiply in the hot path of civil_to_jd. + GJD_MONTH_OFFSET = [nil, 428, 459, 122, 153, 183, 214, 244, 275, 306, 336, 367, 397].freeze + private_constant :GJD_MONTH_OFFSET + + STRFTIME_DATE_DEFAULT_FMT = '%F'.encode(Encoding::US_ASCII) + private_constant :STRFTIME_DATE_DEFAULT_FMT + + ASCTIME_DAYS = %w[Sun Mon Tue Wed Thu Fri Sat].freeze + ASCTIME_MONS = [nil, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', + 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'].freeze + RFC2822_DAYS = ASCTIME_DAYS + private_constant :ASCTIME_DAYS, :ASCTIME_MONS, :RFC2822_DAYS + + # Pre-computed " Mon " strings for rfc2822/httpdate: " Jan ", " Feb ", ... + RFC_MON_SPACE = ASCTIME_MONS.map { |m| m ? " #{m} ".freeze : nil }.freeze + private_constant :RFC_MON_SPACE + + ERA_TABLE = [ + [2458605, 'R', 2018], # Reiwa: 2019-05-01 + [2447535, 'H', 1988], # Heisei: 1989-01-08 + [2424875, 'S', 1925], # Showa: 1926-12-25 + [2419614, 'T', 1911], # Taisho: 1912-07-30 + [2405160, 'M', 1867], # Meiji: 1873-01-01 ].freeze - private_constant :MONTH_DAYS - - YEARTAB = [ - [0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334].freeze, # non-leap - [0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335].freeze # leap + private_constant :ERA_TABLE + + # Pre-built "-MM-DD" suffixes for all valid month/day combinations. + # Indexed by [month][day]. Avoids per-call format() for the month/day portion. + MONTH_DAY_SUFFIX = Array.new(13) { |m| + Array.new(32) { |d| + next nil if m == 0 || d == 0 + format('-%02d-%02d', m, d).encode(Encoding::US_ASCII).freeze + }.freeze + }.freeze + private_constant :MONTH_DAY_SUFFIX + + # === String formatting (from strftime.rb) === + + DEFAULT_STRFTIME_FMT = '%F'.encode(Encoding::US_ASCII).freeze + private_constant :DEFAULT_STRFTIME_FMT + + YMD_FMT = '%Y-%m-%d'.encode(Encoding::US_ASCII).freeze + private_constant :YMD_FMT + + # Locale-independent month/day name tables (same as C ext) + STRFTIME_MONTHS_FULL = MONTHNAMES.freeze + STRFTIME_MONTHS_ABBR = ABBR_MONTHNAMES.freeze + STRFTIME_DAYS_FULL = DAYNAMES.freeze + STRFTIME_DAYS_ABBR = ABBR_DAYNAMES.freeze + private_constant :STRFTIME_MONTHS_FULL, :STRFTIME_MONTHS_ABBR, + :STRFTIME_DAYS_FULL, :STRFTIME_DAYS_ABBR + + # Pre-computed "Sun Jan " prefix table for %c / asctime [wday][month] + ASCTIME_PREFIX = Array.new(7) { |w| + Array.new(13) { |m| + m == 0 ? nil : "#{STRFTIME_DAYS_ABBR[w]} #{STRFTIME_MONTHS_ABBR[m]} ".freeze + }.freeze + }.freeze + private_constant :ASCTIME_PREFIX + + # Pre-computed "Saturday, " prefix table for %A format [wday] + DAY_FULL_COMMA = STRFTIME_DAYS_FULL.map { |d| "#{d}, ".freeze }.freeze + # Pre-computed "March " prefix table for %B format [month] + MONTH_FULL_SPACE = STRFTIME_MONTHS_FULL.map { |m| m ? "#{m} ".freeze : nil }.freeze + private_constant :DAY_FULL_COMMA, :MONTH_FULL_SPACE + + # Bitmask flag constants for strftime parsing + FL_LEFT = 0x01 # '-' flag + FL_SPACE = 0x02 # '_' flag + FL_ZERO = 0x04 # '0' flag + FL_UPPER = 0x08 # '^' flag + FL_CHCASE = 0x10 # '#' flag + private_constant :FL_LEFT, :FL_SPACE, :FL_ZERO, :FL_UPPER, :FL_CHCASE + + # Pre-computed 2-digit zero-padded strings for 0..99 + PAD2 = (0..99).map { |n| format('%02d', n).freeze }.freeze + private_constant :PAD2 + + # Map composite spec bytes to their expansion strings + STRFTIME_COMPOSITE_BYTE = { + 99 => '%a %b %e %H:%M:%S %Y', # 'c' + 68 => '%m/%d/%y', # 'D' + 70 => '%Y-%m-%d', # 'F' + 110 => "\n", # 'n' + 114 => '%I:%M:%S %p', # 'r' + 82 => '%H:%M', # 'R' + 116 => "\t", # 't' + 84 => '%H:%M:%S', # 'T' + 118 => '%e-%^b-%4Y', # 'v' + 88 => '%H:%M:%S', # 'X' + 120 => '%m/%d/%y', # 'x' + }.freeze + private_constant :STRFTIME_COMPOSITE_BYTE + + # Valid specs for %E locale modifier (as byte values) + # c=99, C=67, x=120, X=88, y=121, Y=89 + STRFTIME_E_VALID_BYTES = [99, 67, 120, 88, 121, 89].freeze + # Valid specs for %O locale modifier (as byte values) + # d=100, e=101, H=72, k=107, I=73, l=108, m=109, M=77, S=83, u=117, U=85, V=86, w=119, W=87, y=121 + STRFTIME_O_VALID_BYTES = [100, 101, 72, 107, 73, 108, 109, 77, 83, 117, 85, 86, 119, 87, 121].freeze + private_constant :STRFTIME_E_VALID_BYTES, :STRFTIME_O_VALID_BYTES + + # Maximum allowed format width to prevent unreasonable memory allocation + STRFTIME_MAX_WIDTH = 65535 + # Maximum length for a single formatted field (matches C's STRFTIME_MAX_COPY_LEN) + STRFTIME_MAX_COPY_LEN = 1024 + private_constant :STRFTIME_MAX_WIDTH, :STRFTIME_MAX_COPY_LEN + + # === Parse regex patterns (from parse.rb) === + + RFC3339_RE = /\A\s*(-?\d{4})-(\d{2})-(\d{2})[Tt ](\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(Z|[-+]\d{2}:\d{2})\s*\z/i + private_constant :RFC3339_RE + + HTTPDATE_TYPE1_RE = /\A\s*(sun|mon|tue|wed|thu|fri|sat)\s*,\s+(\d{2})\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+(-?\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+(gmt)\s*\z/i + HTTPDATE_TYPE2_RE = /\A\s*(sunday|monday|tuesday|wednesday|thursday|friday|saturday)\s*,\s+(\d{2})\s*-\s*(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s*-\s*(\d{2})\s+(\d{2}):(\d{2}):(\d{2})\s+(gmt)\s*\z/i + HTTPDATE_TYPE3_RE = /\A\s*(sun|mon|tue|wed|thu|fri|sat)\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})\s+(\d{4})\s*\z/i + # Fast path: simplified Type 1 with generic [a-zA-Z] instead of alternation + FAST_HTTPDATE_TYPE1_RE = /\A\s*([a-zA-Z]{3}),\s+(\d{2})\s+([a-zA-Z]{3})\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+(GMT)\s*\z/i + private_constant :HTTPDATE_TYPE1_RE, :HTTPDATE_TYPE2_RE, :HTTPDATE_TYPE3_RE, + :FAST_HTTPDATE_TYPE1_RE + + # Wday lookup from abbreviated day name (3-char lowercase key) + HTTPDATE_WDAY = {'sun'=>0,'mon'=>1,'tue'=>2,'wed'=>3,'thu'=>4,'fri'=>5,'sat'=>6}.freeze + HTTPDATE_FULL_WDAY = {'sunday'=>0,'monday'=>1,'tuesday'=>2,'wednesday'=>3,'thursday'=>4,'friday'=>5,'saturday'=>6}.freeze + private_constant :HTTPDATE_WDAY, :HTTPDATE_FULL_WDAY + + RFC2822_RE = /\A\s*(?:(sun|mon|tue|wed|thu|fri|sat)\s*,\s+)?(\d{1,2})\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+(-?\d{2,})\s+(\d{2}):(\d{2})(?::(\d{2}))?\s*([-+]\d{4}|ut|gmt|e[sd]t|c[sd]t|m[sd]t|p[sd]t|[a-ik-z])\s*\z/i + private_constant :RFC2822_RE + + XMLSCHEMA_DATETIME_RE = /\A\s*(-?\d{4,})(?:-(\d{2})(?:-(\d{2}))?)?(?:t(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?)?(z|[-+]\d{2}:\d{2})?\s*\z/i + XMLSCHEMA_TIME_RE = /\A\s*(\d{2}):(\d{2}):(\d{2})(?:\.(\d+))?(z|[-+]\d{2}:\d{2})?\s*\z/i + XMLSCHEMA_TRUNC_RE = /\A\s*(?:--(\d{2})(?:-(\d{2}))?|---(\d{2}))(z|[-+]\d{2}:\d{2})?\s*\z/i + private_constant :XMLSCHEMA_DATETIME_RE, :XMLSCHEMA_TIME_RE, :XMLSCHEMA_TRUNC_RE + + ISO8601_EXT_DATETIME_RE = %r{\A\s* + (?: + ([-+]?\d{2,}|-)-(\d{2})?(?:-(\d{2}))? | # year-mon-mday or --mon-mday or ---mday + ([-+]?\d{2,})?-(\d{3}) | # year-yday + (\d{4}|\d{2})?-w(\d{2})(?:-(\d))? | # cwyear-wNN-D + -w-(\d) # -w-D + ) + (?:t + (\d{2}):(\d{2})(?::(\d{2})(?:[,.](\d+))?)? + (z|[-+]\d{2}(?::?\d{2})?)? + )? + \s*\z}xi + + ISO8601_BAS_DATETIME_RE = %r{\A\s* + (?: + ([-+]?(?:\d{4}|\d{2})|--)(\d{2}|-)(\d{2}) | # yyyymmdd / --mmdd / ----dd + ([-+]?(?:\d{4}|\d{2}))(\d{3}) | # yyyyddd + -(\d{3}) | # -ddd + (\d{4}|\d{2})w(\d{2})(\d) | # yyyywwwd + -w(\d{2})(\d) | # -wNN-D + -w-(\d) # -w-D + ) + (?:t? + (\d{2})(\d{2})(?:(\d{2})(?:[,.](\d+))?)? + (z|[-+]\d{2}(\d{2})?)? + )? + \s*\z}xi + + ISO8601_EXT_TIME_RE = /\A\s*(\d{2}):(\d{2})(?::(\d{2})(?:[,.](\d+))?(z|[-+]\d{2}(?::?\d{2})?)?)?\s*\z/i + ISO8601_BAS_TIME_RE = /\A\s*(\d{2})(\d{2})(?:(\d{2})(?:[,.](\d+))?(z|[-+]\d{2}(\d{2})?)?)?\s*\z/i + private_constant :ISO8601_EXT_DATETIME_RE, :ISO8601_BAS_DATETIME_RE, + :ISO8601_EXT_TIME_RE, :ISO8601_BAS_TIME_RE + + JISX0301_ERA = { 'm' => 1867, 't' => 1911, 's' => 1925, 'h' => 1988, 'r' => 2018 }.freeze + JISX0301_RE = /\A\s*([mtshr])?(\d{2})\.(\d{2})\.(\d{2})(?:t(?:(\d{2}):(\d{2})(?::(\d{2})(?:[,.](\d*))?)?(z|[-+]\d{2}(?::?\d{2})?)?)?)?\s*\z/i + private_constant :JISX0301_ERA, :JISX0301_RE + + # Character class flags + HAVE_ALPHA = 1 + HAVE_DIGIT = 2 + HAVE_DASH = 4 + HAVE_DOT = 8 + HAVE_SLASH = 16 + HAVE_COLON = 32 + private_constant :HAVE_ALPHA, :HAVE_DIGIT, :HAVE_DASH, :HAVE_DOT, :HAVE_SLASH, :HAVE_COLON + + PARSE_DAYS_RE = /\b(sun|mon|tue|wed|thu|fri|sat)[^-\/\d\s]*/i + PARSE_MON_RE = /\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\S*/i + PARSE_MDAY_RE = /(?> 16 - NS_MONTH_COEFF = 2141 - NS_MONTH_OFFSET = 197913 - private_constant :NS_MONTH_COEFF, :NS_MONTH_OFFSET - - # Coefficients for civil date to JDN month contribution. - # Maps month to accumulated days: days = (NS_CIVIL_MONTH_COEFF * m - NS_CIVIL_MONTH_OFFSET) / 32 - NS_CIVIL_MONTH_COEFF = 979 - NS_CIVIL_MONTH_OFFSET = 2919 - NS_CIVIL_MONTH_DIVISOR = 32 - private_constant :NS_CIVIL_MONTH_COEFF, :NS_CIVIL_MONTH_OFFSET, :NS_CIVIL_MONTH_DIVISOR - - # Days from March 1 to December 31 (for Jan/Feb year adjustment) - NS_DAYS_BEFORE_NEW_YEAR = 306 - private_constant :NS_DAYS_BEFORE_NEW_YEAR - - # Safe bounds for Neri-Schneider algorithm to avoid integer overflow. - # These correspond to approximately years -1,000,000 to +1,000,000. - NS_JD_MIN = -364_000_000 - NS_JD_MAX = 538_000_000 - private_constant :NS_JD_MIN, :NS_JD_MAX - - JULIAN_EPOCH_DATE = "-4712-01-01" - JULIAN_EPOCH_DATETIME = "-4712-01-01T00:00:00+00:00" - JULIAN_EPOCH_DATETIME_RFC2822 = "Mon, 1 Jan -4712 00:00:00 +0000" - JULIAN_EPOCH_DATETIME_HTTPDATE = "Mon, 01 Jan -4712 00:00:00 GMT" - private_constant :JULIAN_EPOCH_DATE, :JULIAN_EPOCH_DATETIME, :JULIAN_EPOCH_DATETIME_RFC2822, :JULIAN_EPOCH_DATETIME_HTTPDATE - - JISX0301_ERA_INITIALS = 'mtshr' - JISX0301_DEFAULT_ERA = 'H' # obsolete - private_constant :JISX0301_ERA_INITIALS, :JISX0301_DEFAULT_ERA - - HAVE_ALPHA = 1 << 0 - HAVE_DIGIT = 1 << 1 - HAVE_DASH = 1 << 2 - HAVE_DOT = 1 << 3 - HAVE_SLASH = 1 << 4 - private_constant :HAVE_ALPHA, :HAVE_DIGIT, :HAVE_DASH, :HAVE_DOT, :HAVE_SLASH - - # C: default strftime format is US-ASCII - STRFTIME_DEFAULT_FMT = '%F' - private_constant :STRFTIME_DEFAULT_FMT - - # strftime spec categories - NUMERIC_SPECS = %w[Y C y m d j H I M S L N G g U W V u w s Q].freeze - SPACE_PAD_SPECS = %w[e k l].freeze - CHCASE_UPPER_SPECS = %w[A a B b h].freeze - CHCASE_LOWER_SPECS = %w[Z p].freeze - private_constant :NUMERIC_SPECS, :SPACE_PAD_SPECS, - :CHCASE_UPPER_SPECS, :CHCASE_LOWER_SPECS - - # strptime digit-consuming specs - NUM_PATTERN_SPECS = "CDdeFGgHIjkLlMmNQRrSsTUuVvWwXxYy" - private_constant :NUM_PATTERN_SPECS - - # Precomputed byte-indexed boolean table for num_pattern_p. - # Entry is true if the byte value corresponds to a digit-consuming %-specifier. - NUM_PATTERN_SPECS_TABLE = begin - t = Array.new(256, false) - NUM_PATTERN_SPECS.each_byte { |b| t[b] = true } - t.freeze - end - private_constant :NUM_PATTERN_SPECS_TABLE - - # Precomputed zero-padded two-digit strings "00".."99". - TWO_DIGIT = (0..99).map { |i| (i < 10 ? "0#{i}" : i.to_s).freeze }.freeze - private_constant :TWO_DIGIT - - # Precomputed zero-padded four-digit year strings "0000".."9999". - FOUR_DIGIT = (0..9999).map { |y| sprintf("%04d", y).freeze }.freeze - private_constant :FOUR_DIGIT - - # Integer bitmask flags for strftime format modifier parsing. - FLAG_MINUS = 0x01 # '-' suppress padding - FLAG_SPACE = 0x02 # '_' space padding - FLAG_UPPER = 0x04 # '^' upcase result - FLAG_CHCASE = 0x08 # '#' change case (CHCASE) - FLAG_ZERO = 0x10 # '0' zero padding (explicit) - private_constant :FLAG_MINUS, :FLAG_SPACE, :FLAG_UPPER, :FLAG_CHCASE, :FLAG_ZERO - - # Fragment completion table for DateTime parsing - COMPLETE_FRAGS_TABLE = [ - [:time, [:hour, :min, :sec].freeze], - [nil, [:jd].freeze], - [:ordinal, [:year, :yday, :hour, :min, :sec].freeze], - [:civil, [:year, :mon, :mday, :hour, :min, :sec].freeze], - [:commercial, [:cwyear, :cweek, :cwday, :hour, :min, :sec].freeze], - [:wday, [:wday, :hour, :min, :sec].freeze], - [:wnum0, [:year, :wnum0, :wday, :hour, :min, :sec].freeze], - [:wnum1, [:year, :wnum1, :wday, :hour, :min, :sec].freeze], - [nil, [:cwyear, :cweek, :wday, :hour, :min, :sec].freeze], - [nil, [:year, :wnum0, :cwday, :hour, :min, :sec].freeze], - [nil, [:year, :wnum1, :cwday, :hour, :min, :sec].freeze], - ].each { |a| a.freeze }.freeze - private_constant :COMPLETE_FRAGS_TABLE - - # Lookup tables for O(1) day/month name matching in strptime %a/%b. - # Key: 24-bit integer (b0|0x20)<<16|(b1|0x20)<<8|(b2|0x20) of lowercase 3-char abbreviation. - # Value: [index, full_lower, full_len, abbr_len]. - # This avoids string allocation for the 3-char prefix key entirely. - STRPTIME_DAYNAME_BY_INT_KEY = begin - h = {} - DAYNAMES.each_with_index do |name, idx| - abbr = ABBR_DAYNAMES[idx] - k = ((abbr.getbyte(0) | 0x20) << 16) | - ((abbr.getbyte(1) | 0x20) << 8) | - (abbr.getbyte(2) | 0x20) - h[k] = [idx, name.downcase, name.length, abbr.length].freeze - end - h.freeze - end - private_constant :STRPTIME_DAYNAME_BY_INT_KEY - - STRPTIME_MONNAME_BY_INT_KEY = begin - h = {} - MONTHNAMES.each_with_index do |name, idx| - next unless name - abbr = ABBR_MONTHNAMES[idx] - k = ((abbr.getbyte(0) | 0x20) << 16) | - ((abbr.getbyte(1) | 0x20) << 8) | - (abbr.getbyte(2) | 0x20) - h[k] = [idx, name.downcase, name.length, abbr.length].freeze - end - h.freeze - end - private_constant :STRPTIME_MONNAME_BY_INT_KEY + private_constant :COMPLETE_FRAGS_TAB + + # O(1) boolean lookup table for numeric specs (used by _sp_num_p_b?) + # Includes both STRPTIME_NUMERIC_SPECS chars and digits '0'..'9' + STRPTIME_NUMERIC_SPEC_SET = Array.new(256, false).tap { |a| + STRPTIME_NUMERIC_SPECS.each_byte { |b| a[b] = true } + 48.upto(57) { |b| a[b] = true } # '0'..'9' + }.freeze + private_constant :STRPTIME_NUMERIC_SPEC_SET + + # O(1) boolean lookup table for E-modifier valid specs + STRPTIME_E_VALID_SET = Array.new(256, false).tap { |a| + 'cCxXyY'.each_byte { |b| a[b] = true } + }.freeze + private_constant :STRPTIME_E_VALID_SET + + # O(1) boolean lookup table for O-modifier valid specs + STRPTIME_O_VALID_SET = Array.new(256, false).tap { |a| + 'deHImMSuUVwWy'.each_byte { |b| a[b] = true } + }.freeze + private_constant :STRPTIME_O_VALID_SET end diff --git a/lib/date/core.rb b/lib/date/core.rb index 4e285ffa..e625ddd2 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1,214 +1,53 @@ # frozen_string_literal: true -# Implementation of ruby/date/ext/date/date_core.c class Date include Comparable Error = Class.new(ArgumentError) - # Initialize method - # call-seq: - # Date.new(year = -4712, month = 1, mday = 1, start = Date::ITALY) -> date - # - # Returns a new Date object constructed from the given arguments: - # - # Date.new(2022).to_s # => "2022-01-01" - # Date.new(2022, 2).to_s # => "2022-02-01" - # Date.new(2022, 2, 4).to_s # => "2022-02-04" - # - # Argument +month+ should be in range (1..12) or range (-12..-1); - # when the argument is negative, counts backward from the end of the year: - # - # Date.new(2022, -11, 4).to_s # => "2022-02-04" - # - # Argument +mday+ should be in range (1..n) or range (-n..-1) - # where +n+ is the number of days in the month; - # when the argument is negative, counts backward from the end of the month. - # - # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - # - # Related: Date.jd. - def initialize(year = -4712, month = 1, day = 1, start = DEFAULT_SG) - # Fast path: Integer arguments, Gregorian calendar - # Avoids self.class.send, Hash allocation, redundant decode_year - if year.is_a?(Integer) && year.abs < 579000 && month.is_a?(Integer) && day.is_a?(Integer) - gregorian_fast = if start.is_a?(Float) && start.infinite? - start < 0 # GREGORIAN (-Infinity) only - elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD - year > REFORM_END_YEAR - end - - if gregorian_fast - m = month - m += 13 if m < 0 - raise Error unless m >= 1 && m <= 12 - - leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0) - last = MONTH_DAYS[leap ? 1 : 0][m] - d = day - d = last + d + 1 if d < 0 - raise Error unless d >= 1 && d <= last - - j = (m < 3) ? 1 : 0 - y0 = year - j - m0 = j.nonzero? ? m + 12 : m - d0 = d - 1 - q1 = y0 / 100 - yc = (NS_DAYS_IN_4_YEARS * y0) / 4 - q1 + q1 / 4 - mc = (NS_DAYS_BEFORE_NEW_YEAR * m0 - 914) / 10 - - @nth = 0 - @jd = yc + mc + d0 + NS_EPOCH - @sg = start - @year = year - @month = m - @day = d - @has_jd = true - @has_civil = true - @df = nil - @sf = nil - @of = nil - return self - end - - # Julian fast path: JULIAN start, or year < REFORM_BEGIN_YEAR with reform-range start. - # Covers Date.civil(-4712, 1, 1) and Date.civil(2024, 6, 15, Date::JULIAN). - julian_fast = if start.is_a?(Float) && start.infinite? - start > 0 # JULIAN (+Infinity) - elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD - year < REFORM_BEGIN_YEAR - end - - if julian_fast - m = month - m += 13 if m < 0 - raise Error unless m >= 1 && m <= 12 - - # Julian leap year: divisible by 4 (no century exception) - leap = (year % 4 == 0) - last = MONTH_DAYS[leap ? 1 : 0][m] - d = day - d = last + d + 1 if d < 0 - raise Error unless d >= 1 && d <= last + # --------------------------------------------------------------------------- + # Class methods + # --------------------------------------------------------------------------- - # Julian JD via integer arithmetic: - # jd = floor(365.25*(y+4716)) + floor(30.6001*(m+1)) + d - 1524 - # = (1461*(y+4716))/4 + (153*(m+1))/5 + d - 1524 - y2 = year; m2 = m - if m2 <= 2 - y2 -= 1 - m2 += 12 + class << self + # Same as Date.new. + def civil(year = -4712, month = 1, day = 1, start = DEFAULT_SG) + unless (Integer === (year + month + day) rescue false) && month >= 1 && month <= 12 + return new(year, month, day, start) + end + if day >= 1 && day <= 28 + gy = month > 2 ? year : year - 1 + gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[month] + day + a = gy / 100 + jd_julian = gjd_base - 1524 + gjd = jd_julian + 2 - a + a / 4 + obj = allocate + obj.__send__(:_init_from_jd, gjd >= start ? gjd : jd_julian, start) + return obj + elsif day >= -31 + dim = if month == 2 + if start == Float::INFINITY + year % 4 == 0 ? 29 : 28 + else + (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 29 : 28 + end + else + DAYS_IN_MONTH_GREGORIAN[month] + end + d = day < 0 ? day + dim + 1 : day + if d >= 1 && d <= dim + gy = month > 2 ? year : year - 1 + gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[month] + d + a = gy / 100 + jd_julian = gjd_base - 1524 + gjd = jd_julian + 2 - a + a / 4 + obj = allocate + obj.__send__(:_init_from_jd, gjd >= start ? gjd : jd_julian, start) + return obj end - jd = (1461 * (y2 + 4716)) / 4 + (153 * (m2 + 1)) / 5 + d - 1524 - - @nth = 0 - @jd = jd - @sg = start - @year = year - @month = m - @day = d - @has_jd = true - @has_civil = true - @df = nil - @sf = nil - @of = nil - return self end + new(year, month, day, start) end - - # Original path: handles non-Integer args, Julian/reform dates, fractional days - y = year - m = month - d = day - sg = start - fr2 = 0 - - # argument type checking - if y - raise TypeError, "invalid year (not numeric)" unless year.is_a?(Numeric) - end - if m - raise TypeError, "invalid month (not numeric)" unless month.is_a?(Numeric) - end - if d - raise TypeError, "invalid day (not numeric)" unless day.is_a?(Numeric) - # Check if there is a decimal part. - d_trunc, fr = d_trunc_with_frac(d) - d = d_trunc - fr2 = fr if fr.nonzero? - end - - sg = self.class.send(:valid_sg, sg) - style = self.class.send(:guess_style, y, sg) - - if style < 0 - # gregorian calendar only - result = self.class.send(:valid_gregorian_p, y, m, d) - raise Error unless result - - nth, ry = self.class.send(:decode_year, y, -1) - rm = result[:rm] - rd = result[:rd] - - @nth = canon(nth) - @jd = 0 - @sg = sg - @year = ry - @month = rm - @day = rd - @has_jd = false - @has_civil = true - @df = nil - @sf = nil - @of = nil - else - # full validation - result = self.class.send(:valid_civil_p, y, m, d, sg) - raise Error unless result - - nth = result[:nth] - ry = result[:ry] - rm = result[:rm] - rd = result[:rd] - rjd = result[:rjd] - - @nth = canon(nth) - @jd = rjd - @sg = sg - @year = ry - @month = rm - @day = rd - @has_jd = true - @has_civil = true - @df = nil - @sf = nil - @of = nil - end - - # Add any decimal parts. - if fr2.nonzero? - new_date = self + fr2 - @nth = new_date.instance_variable_get(:@nth) - @jd = new_date.instance_variable_get(:@jd) - @sg = new_date.instance_variable_get(:@sg) - @year = new_date.instance_variable_get(:@year) - @month = new_date.instance_variable_get(:@month) - @day = new_date.instance_variable_get(:@day) - @has_jd = new_date.instance_variable_get(:@has_jd) - @has_civil = new_date.instance_variable_get(:@has_civil) - @df = new_date.instance_variable_get(:@df) - @sf = new_date.instance_variable_get(:@sf) - @of = new_date.instance_variable_get(:@of) - end - - self - end - - # Class methods - class << self - # Same as `Date.new`. - alias_method :civil, :new - # call-seq: # Date.valid_civil?(year, month, mday, start = Date::ITALY) -> true or false # @@ -223,28 +62,8 @@ class << self # # Related: Date.jd, Date.new. def valid_civil?(year, month, day, start = DEFAULT_SG) - # Fast path: Integer args, non-Julian start - if year.is_a?(Integer) && month.is_a?(Integer) && day.is_a?(Integer) - gregorian_fast = if start.is_a?(Float) && start.infinite? - start < 0 - elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD - true - end - - if gregorian_fast - return false if month < 1 || month > 12 - leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0) - return day >= 1 && day <= MONTH_DAYS[leap ? 1 : 0][month] - end - end - - return false unless numeric?(year) - return false unless numeric?(month) - return false unless numeric?(day) - - result = valid_civil_sub(year, month, day, start, 0) - - !result.nil? + return false unless year.is_a?(Numeric) && month.is_a?(Numeric) && day.is_a?(Numeric) + !!internal_valid_civil?(year, month, day, start) end alias_method :valid_date?, :valid_civil? @@ -273,44 +92,10 @@ def valid_civil?(year, month, day, start = DEFAULT_SG) # # Related: Date.new. def jd(jd = 0, start = DEFAULT_SG) - # Fast path: Integer jd in common range, valid start - if jd.is_a?(Integer) && jd >= 0 && jd < CM_PERIOD - valid_start = if start.is_a?(Float) && start.infinite? - true - elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD - true - end - - if valid_start - obj = allocate - obj.instance_variable_set(:@nth, 0) - obj.instance_variable_set(:@jd, jd) - obj.instance_variable_set(:@sg, start) - obj.instance_variable_set(:@has_jd, true) - return obj - end - end - - # Original path - j = 0 - fr = 0 - sg = start - - sg = valid_sg(start) if start - - if jd - raise TypeError, "invalid jd (not numeric)" unless jd.is_a?(Numeric) - - j, fr = value_trunc(jd) - end - - nth, rjd = decode_jd(j) - - ret = d_simple_new_internal(nth, rjd, sg, 0, 0, 0, HAVE_JD) - - ret = ret + fr if fr.nonzero? - - ret + jd = Integer(jd) + obj = allocate + obj.__send__(:_init_from_jd, jd, start) + obj end # call-seq: @@ -324,12 +109,8 @@ def jd(jd = 0, start = DEFAULT_SG) # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # # Related: Date.jd. - def valid_jd?(jd, start = DEFAULT_SG) - # All Numeric jd values are valid; skip valid_jd_sub/valid_sg chain - return true if jd.is_a?(Numeric) - return true if jd.respond_to?(:to_int) - - false + def valid_jd?(jd, _start = DEFAULT_SG) + jd.is_a?(Numeric) end # call-seq: @@ -343,14 +124,8 @@ def valid_jd?(jd, start = DEFAULT_SG) # # Related: Date.julian_leap?. def gregorian_leap?(year) - if year.is_a?(Integer) - return (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0) - end - raise TypeError, "invalid year (not numeric)" unless numeric?(year) - - _, ry = decode_year(year, -1) - - c_gregorian_leap_p?(ry) + raise TypeError, "expected numeric" unless year.is_a?(Numeric) + internal_gregorian_leap?(year) end alias_method :leap?, :gregorian_leap? @@ -365,14 +140,8 @@ def gregorian_leap?(year) # # Related: Date.gregorian_leap?. def julian_leap?(year) - if year.is_a?(Integer) - return (year % 4).zero? - end - raise TypeError, "invalid year (not numeric)" unless numeric?(year) - - _, ry = decode_year(year, +1) - - c_julian_leap_p?(ry) + raise TypeError, "expected numeric" unless year.is_a?(Numeric) + internal_julian_leap?(year) end # call-seq: @@ -404,59 +173,21 @@ def julian_leap?(year) # # Related: Date.jd, Date.new. def ordinal(year = -4712, yday = 1, start = DEFAULT_SG) - # Fast path: Integer args, Gregorian calendar - if year.is_a?(Integer) && year.abs < 579000 && yday.is_a?(Integer) - gregorian_fast = if start.is_a?(Float) && start.infinite? - start < 0 - elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD - year > REFORM_END_YEAR - end - - if gregorian_fast - leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0) - days_in_year = leap ? 366 : 365 - d = yday - d = days_in_year + d + 1 if d < 0 - raise Error unless d >= 1 && d <= days_in_year - - rjd = c_gregorian_civil_to_jd(year, 1, 1) + d - 1 - - obj = allocate - obj.instance_variable_set(:@nth, 0) - obj.instance_variable_set(:@jd, rjd) - obj.instance_variable_set(:@sg, start) - obj.instance_variable_set(:@has_jd, true) - return obj - end - end - - # Original path - y = year - d = yday - fr2 = 0 - sg = start - - if y - raise TypeError, "invalid year (not numeric)" unless year.is_a?(Numeric) - end - if d - raise TypeError, "invalid yday (not numeric)" unless yday.is_a?(Numeric) - d_trunc, fr = value_trunc(d) - d = d_trunc - fr2 = fr if fr.nonzero? + if Integer === year && Integer === yday && yday >= 1 && yday <= 365 + gy = year - 1 + gjd_base = (1461 * (gy + 4716)) / 4 + 429 # GJD_MONTH_OFFSET[1] + 1 + a = gy / 100 + gjd = gjd_base - 1524 + 2 - a + a / 4 + jd1 = gjd >= start ? gjd : gjd_base - 1524 + obj = allocate + obj.__send__(:_init_from_jd, jd1 + yday - 1, start) + return obj end - - result = valid_ordinal_p(year, yday, start) - raise Error unless result - - nth = result[:nth] - rjd = result[:rjd] - - obj = d_simple_new_internal(nth, rjd, sg, 0, 0, 0, HAVE_JD) - - obj = obj + fr2 if fr2.nonzero? - - obj + year = Integer(year) + yday = Integer(yday) + jd = internal_valid_ordinal?(year, yday, start) + raise Date::Error, "invalid date" unless jd + _new_from_jd(jd, start) end # call-seq: @@ -472,29 +203,8 @@ def ordinal(year = -4712, yday = 1, start = DEFAULT_SG) # # Related: Date.jd, Date.ordinal. def valid_ordinal?(year, day, start = DEFAULT_SG) - # Fast path: Integer args, non-Julian start - if year.is_a?(Integer) && day.is_a?(Integer) - gregorian_fast = if start.is_a?(Float) && start.infinite? - start < 0 - elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD - true - end - - if gregorian_fast - leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0) - days_in_year = leap ? 366 : 365 - d = day - d = days_in_year + d + 1 if d < 0 - return d >= 1 && d <= days_in_year - end - end - - return false unless numeric?(year) - return false unless numeric?(day) - - result = valid_ordinal_sub(year, day, start, false) - - !result.nil? + return false unless year.is_a?(Numeric) && day.is_a?(Numeric) + !!internal_valid_ordinal?(year, day, start) end # call-seq: @@ -540,81 +250,28 @@ def valid_ordinal?(year, day, start = DEFAULT_SG) # # Related: Date.jd, Date.new, Date.ordinal. def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = DEFAULT_SG) - # Fast path: Integer args, Gregorian calendar - if cwyear.is_a?(Integer) && cwyear.abs < 579000 && cweek.is_a?(Integer) && cwday.is_a?(Integer) - gregorian_fast = if start.is_a?(Float) && start.infinite? - start < 0 - elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD - cwyear > REFORM_END_YEAR - end - - if gregorian_fast - # Validate cwday (handle negative) - d = cwday - d += 8 if d < 0 - raise Error unless d >= 1 && d <= 7 - - # JD of Jan 1 and ISO week metadata - jd_jan1 = c_gregorian_civil_to_jd(cwyear, 1, 1) - - # Max ISO weeks: 53 if Jan 1 is Thursday, or leap year and Jan 1 is Wednesday - p_val = (jd_jan1 + 1) % 7 # 0=Sun..6=Sat - p_val = 7 if p_val == 0 # Convert to ISO (1=Mon..7=Sun) - leap = (cwyear % 4 == 0) && (cwyear % 100 != 0 || cwyear % 400 == 0) - max_weeks = (p_val == 4 || (leap && p_val == 3)) ? 53 : 52 - - # Handle negative week - w = cweek - w = max_weeks + w + 1 if w < 0 - raise Error unless w >= 1 && w <= max_weeks - - # Compute JD: Monday of week 1 + offset - rjd2 = jd_jan1 + 3 - rjd = (rjd2 - (rjd2 % 7)) + 7 * (w - 1) + (d - 1) - - obj = allocate - obj.instance_variable_set(:@nth, 0) - obj.instance_variable_set(:@jd, rjd) - obj.instance_variable_set(:@sg, start) - obj.instance_variable_set(:@has_jd, true) - return obj - end - end - - # Original path - y = cwyear - w = cweek - d = cwday - fr2 = 0 - sg = start - - if y - raise TypeError, "invalid year (not numeric)" unless cwyear.is_a?(Numeric) - end - if w - raise TypeError, "invalid cweek (not numeric)" unless cweek.is_a?(Numeric) - w = w.to_i - end - if d - raise TypeError, "invalid cwday (not numeric)" unless cwday.is_a?(Numeric) - d_trunc, fr = value_trunc(d) - d = d_trunc - fr2 = fr if fr.nonzero? + if Integer === cwyear && Integer === cweek && Integer === cwday && + cweek >= 1 && cweek <= 52 && cwday >= 1 && cwday <= 7 + # ISO 8601: every year has at least 52 weeks, so weeks 1-52 are always valid. + # Inline civil_to_jd(cwyear, 1, 4, start): month=1, day=4 + gy = cwyear - 1 + gjd_base4 = (1461 * (gy + 4716)) / 4 + 432 # GJD_MONTH_OFFSET[1] + 4 + a = gy / 100 + gjd4 = gjd_base4 - 1524 + 2 - a + a / 4 + jd_jan4 = gjd4 >= start ? gjd4 : gjd_base4 - 1524 + wday_jan4 = (jd_jan4 + 1) % 7 + mon_wk1 = jd_jan4 - (wday_jan4 == 0 ? 6 : wday_jan4 - 1) + jd = mon_wk1 + (cweek - 1) * 7 + (cwday - 1) + obj = allocate + obj.__send__(:_init_from_jd, jd, start) + return obj end - - sg = valid_sg(start) if start - - result = valid_commercial_p(y, w, d, sg) - raise Error unless result - - nth = result[:nth] - rjd = result[:rjd] - - obj = d_simple_new_internal(nth, rjd, sg, 0, 0, 0, HAVE_JD) - - obj = obj + fr2 if fr2.nonzero? - - obj + cwyear = Integer(cwyear) + cweek = Integer(cweek) + cwday = Integer(cwday) + jd = internal_valid_commercial?(cwyear, cweek, cwday, start) + raise Date::Error, "invalid date" unless jd + _new_from_jd(jd, start) end # call-seq: @@ -632,41 +289,42 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = DEFAULT_SG) # # Related: Date.jd, Date.commercial. def valid_commercial?(year, week, day, start = DEFAULT_SG) - # Fast path: Integer args, non-Julian start - if year.is_a?(Integer) && week.is_a?(Integer) && day.is_a?(Integer) - gregorian_fast = if start.is_a?(Float) && start.infinite? - start < 0 - elsif start.is_a?(Integer) && start >= REFORM_BEGIN_JD && start <= REFORM_END_JD - true - end - - if gregorian_fast - # Validate cwday (handle negative) - d = day - d += 8 if d < 0 - return false unless d >= 1 && d <= 7 - - # Max ISO weeks: 53 if Jan 1 is Thursday, or leap year and Jan 1 is Wednesday - jd_jan1 = c_gregorian_civil_to_jd(year, 1, 1) - p_val = (jd_jan1 + 1) % 7 # 0=Sun..6=Sat - p_val = 7 if p_val == 0 # Convert to ISO (1=Mon..7=Sun) - leap = (year % 4 == 0) && (year % 100 != 0 || year % 400 == 0) - max_weeks = (p_val == 4 || (leap && p_val == 3)) ? 53 : 52 - - # Handle negative week - w = week - w = max_weeks + w + 1 if w < 0 - return w >= 1 && w <= max_weeks - end - end - - return false unless numeric?(year) - return false unless numeric?(week) - return false unless numeric?(day) + return false unless year.is_a?(Numeric) && week.is_a?(Numeric) && day.is_a?(Numeric) + !!internal_valid_commercial?(year, week, day, start) + end - result = valid_commercial_sub(year, week, day, start, false) + # call-seq: + # Date.weeknum(year, week, wday, wstart = 0, start = Date::ITALY) -> date + def weeknum(year = -4712, week = 0, wday = 1, wstart = 0, start = DEFAULT_SG) + year = Integer(year) + week = Integer(week) + wday = Integer(wday) + wstart = Integer(wstart) + # Validate wday range + raise Date::Error, "invalid date" unless wday >= 0 && wday <= 6 + # Validate week: reconstruct and check round-trip + jd = weeknum_to_jd(year, week, wday, wstart, start) + # Verify the resulting date is in the same year (week must be valid) + y2, = jd_to_civil(jd, start) + raise Date::Error, "invalid date" if y2 != year + _new_from_jd(jd, start) + end - !result.nil? + # call-seq: + # Date.nth_kday(year, month, n, k, start = Date::ITALY) -> date + def nth_kday(year = -4712, month = 1, n = 1, k = 1, start = DEFAULT_SG) + year = Integer(year) + month = Integer(month) + n = Integer(n) + k = Integer(k) + raise Date::Error, "invalid date" unless month >= 1 && month <= 12 + raise Date::Error, "invalid date" unless k >= 0 && k <= 6 + raise Date::Error, "invalid date" if n == 0 + jd = nth_kday_to_jd(year, month, n, k, start) + # Verify the result is in the same month + y2, m2, = jd_to_civil(jd, start) + raise Date::Error, "invalid date" if y2 != year || m2 != month + _new_from_jd(jd, start) end # call-seq: @@ -677,24 +335,14 @@ def valid_commercial?(year, week, day, start = DEFAULT_SG) # Date.today.to_s # => "2022-07-06" # # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # def today(start = DEFAULT_SG) - time = Time.now - - obj = allocate - obj.instance_variable_set(:@nth, 0) - obj.instance_variable_set(:@year, time.year) - obj.instance_variable_set(:@month, time.mon) - obj.instance_variable_set(:@day, time.mday) - obj.instance_variable_set(:@jd, nil) - obj.instance_variable_set(:@sg, start) - obj.instance_variable_set(:@has_jd, false) - obj.instance_variable_set(:@has_civil, true) - - obj + t = Time.now + jd = civil_to_jd(t.year, t.mon, t.mday, start) + _new_from_jd(jd, start) end # :nodoc: - # C: date_s__load — for Marshal format 1.4, 1.6, 1.8 (u: prefix) def _load(s) a = Marshal.load(s) obj = allocate @@ -702,3621 +350,1634 @@ def _load(s) obj end - private - - # Optimized: Gregorian date -> Julian Day Number - def gregorian_civil_to_jd(year, month, day) - # Shift epoch to March 1 of year 0 (Jan/Feb belong to previous year) - j = (month < 3) ? 1 : 0 - y0 = year - j - m0 = j == 1 ? month + 12 : month - d0 = day - 1 - - # Calculate year contribution with leap year correction - q1 = y0 / NS_YEARS_PER_CENTURY - yc = (NS_DAYS_IN_4_YEARS * y0) / 4 - q1 + (q1 / 4) - - # Calculate month contribution using integer arithmetic - mc = (NS_CIVIL_MONTH_COEFF * m0 - NS_CIVIL_MONTH_OFFSET) / NS_CIVIL_MONTH_DIVISOR - - # Combine and add epoch offset to get JDN - yc + mc + d0 + NS_EPOCH + # :nodoc: + def new!(ajd = 0, of = 0, sg = DEFAULT_SG) + # ajd is Astronomical Julian Day (may be Rational) + # Convert to integer JD and day fraction (same as C's old_to_new) + raw_jd = ajd + Rational(1, 2) + jd = raw_jd.floor + df = raw_jd - jd + obj = allocate + obj.__send__(:_init_from_jd, jd, sg, df == 0 ? nil : df) + obj end - def julian_civil_to_jd(y, m, d) - # Traditional Julian calendar algorithm - y2 = y - m2 = m + private - if m2 <= 2 - y2 -= 1 - m2 += 12 - end + # --------------------------------------------------------------------------- + # Internal calendar arithmetic (pure Ruby, no C dependency) + # --------------------------------------------------------------------------- - (365.25 * (y2 + 4716)).floor + (30.6001 * (m2 + 1)).floor + d - 1524 + # Floor division that works correctly for negative numbers. + def idiv(a, b) + a.div(b) end - def validate_ordinal(year, yday, sg) - # Handling negative day of year - if yday < 0 - # Counting backwards from the end of the year - last_jd, _ = c_find_ldoy(year, sg) - return nil unless last_jd - - # Recalculate the total number of days in the year from the calculated JD - adjusted_jd = last_jd + yday + 1 - y, d = jd_to_ordinal(adjusted_jd, sg) - - # Invalid if the year does not match - return nil if y != year - - yday = d - end - - # Calculate jd from the day of the year - nth, ry, _, _ = decode_year(year, sg) - first_jd, ns = c_find_fdoy(ry, sg) - - return nil unless first_jd - - jd = first_jd + yday - 1 - - # Verify that the calculated jd actually belongs to the specified year - verify_y, verify_d = jd_to_ordinal(jd, sg) - return nil if verify_y != ry || verify_d != yday + # Gregorian leap year? + def internal_gregorian_leap?(y) + (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 + end - [nth, ry, yday, jd, ns] + # Julian leap year? + def internal_julian_leap?(y) + y % 4 == 0 end - def extract_fraction(value) - if value.is_a?(Rational) || value.is_a?(Float) - int_part = value.floor - frac_part = value - int_part - [int_part, frac_part] + def days_in_month_gregorian(y, m) + if m == 2 && internal_gregorian_leap?(y) + 29 else - [value.to_i, 0] + DAYS_IN_MONTH_GREGORIAN[m] end end - def jd_to_ordinal(jd, sg) - year, _, _ = jd_to_civil_internal(jd, sg) - first_jd, _ = c_find_fdoy(year, sg) - yday = jd - first_jd + 1 - - [year, yday] - end - - def validate_commercial(year, week, day, sg) - if day < 0 - day += 8 # -1 -> 7 (Sun), -7 -> 1 (Mon) - end - - return nil if day < 1 || day > 7 - - if week < 0 - next_year_jd, ns = commercial_to_jd_internal(year + 1, 1, 1, sg) - return nil unless next_year_jd - - adjusted_jd = next_year_jd + week * 7 - y2, w2, _ = jd_to_commercial_internal(adjusted_jd, sg) - - return nil if y2 != year - - week = w2 + # Days in month for Julian calendar. + def days_in_month_julian(y, m) + if m == 2 && internal_julian_leap?(y) + 29 + else + DAYS_IN_MONTH_GREGORIAN[m] + end + end + + # Gregorian civil (year, month, day) -> Julian Day Number + def gregorian_to_jd(y, m, d) + if m <= 2 + y -= 1 + m += 12 + end + a = y / 100 + b = 2 - a + a / 4 + (1461 * (y + 4716)) / 4 + (306001 * (m + 1)) / 10000 + d + b - 1524 + end + + # Julian civil (year, month, day) -> Julian Day Number + def julian_to_jd(y, m, d) + if m <= 2 + y -= 1 + m += 12 + end + (1461 * (y + 4716)) / 4 + (306001 * (m + 1)) / 10000 + d - 1524 + end + + # Civil (year, month, day) -> JD, respecting start (cutover). + # Uses a unified formula: gjd >= sg -> Gregorian JD, else Julian JD. + # Works for all sg values: Float::INFINITY (always Julian), + # -Float::INFINITY (always Gregorian), or integer cutover JD. + def civil_to_jd(y, m, d, sg) + offset = GJD_MONTH_OFFSET[m] + y -= 1 if m <= 2 + gjd_base = (1461 * (y + 4716)) / 4 + offset + d + a = y / 100 + gjd = gjd_base - 1524 + 2 - a + a / 4 + gjd >= sg ? gjd : gjd_base - 1524 + end + + # Gregorian JD -> (year, month, day) + def jd_to_gregorian(jd) + a = jd + 32044 + b = idiv(4 * a + 3, 146097) + c = a - idiv(146097 * b, 4) + d = idiv(4 * c + 3, 1461) + e = c - idiv(1461 * d, 4) + m = idiv(5 * e + 2, 153) + day = e - idiv(153 * m + 2, 5) + 1 + mon = m + 3 - 12 * idiv(m, 10) + year = 100 * b + d - 4800 + idiv(m, 10) + [year, mon, day] + end + + # Julian JD -> (year, month, day) + def jd_to_julian(jd) + c = jd + 32082 + d = idiv(4 * c + 3, 1461) + e = c - idiv(1461 * d, 4) + m = idiv(5 * e + 2, 153) + day = e - idiv(153 * m + 2, 5) + 1 + mon = m + 3 - 12 * idiv(m, 10) + year = d - 4800 + idiv(m, 10) + [year, mon, day] + end + + # JD -> (year, month, day), respecting start (cutover). + def jd_to_civil(jd, sg) + if sg == Float::INFINITY + jd_to_julian(jd) + elsif sg == -Float::INFINITY || jd >= sg + jd_to_gregorian(jd) + else + jd_to_julian(jd) end - - # Calculate jd from ISO week date - nth, ry, _, _ = decode_year(year, sg) - jd, ns = commercial_to_jd_internal(ry, week, day, sg) - - return nil unless jd - - verify_y, verify_w, verify_d = jd_to_commercial_internal(jd, sg) - return nil if verify_y != ry || verify_w != week || verify_d != day - - [nth, ry, week, day, jd, ns] - end - - def commercial_to_jd_internal(cwyear, cweek, cwday, sg) - # Calculating ISO week date(The week containing January 4 is week 1) - jan4_jd = gregorian_civil_to_jd(cwyear, 1, 4) - - # Day of the week on which January 4th falls - # (0 = Sun, 1 = Mon, ..., 6 = Sat) - jan4_wday = (jan4_jd + 1) % 7 - - # Monday of week 1 - week1_mon = jan4_jd - jan4_wday + 1 - - # jd for a specified weekday - jd = week1_mon + (cweek - 1) * 7 + (cwday - 1) - - # If before sg, it is the Julian calendar - ns = jd >= sg ? 1 : 0 - - [jd, ns] end - def jd_to_commercial_internal(jd, sg) - # get date from jd - year, _, _ = jd_to_civil_internal(jd, sg) - - # calculate jd for January 4 of that year - jan4_jd = gregorian_civil_to_jd(year, 1, 4) - jan4_wday = (jan4_jd + 1) % 7 - week1_mon = jan4_jd - jan4_wday + 1 - - # If jd is before the first week, it belongs to the previous year - if jd < week1_mon - year -= 1 - jan4_jd = gregorian_civil_to_jd(year, 1, 4) - jan4_wday = (jan4_jd + 1) % 7 - week1_mon = jan4_jd - jan4_wday + 1 - end - - # check the first week of the next year - next_jan4 = gregorian_civil_to_jd(year + 1, 1, 4) - next_jan4_wday = (next_jan4 + 1) % 7 - next_week1_mon = next_jan4 - next_jan4_wday + 1 - - if jd >= next_week1_mon - year += 1 - week1_mon = next_week1_mon - end - - # Calculate the week number - week = (jd - week1_mon) / 7 + 1 - - # week(1 = mon, ..., 7 = sun) - cwday = (jd + 1) % 7 - cwday = 7 if cwday.zero? - - [year, week, cwday] + # Ordinal (year, day-of-year) -> JD + def ordinal_to_jd(y, d, sg) + civil_to_jd(y, 1, 1, sg) + d - 1 end - def jd_to_civil_internal(jd, sg) - # Does it overlap with jd_to_civil? - # Calculate the date from jd (using existing methods) - # simple version - r0 = jd - NS_EPOCH - - n1 = 4 * r0 + 3 - q1 = n1 / NS_DAYS_IN_400_YEARS - r1 = (n1 % NS_DAYS_IN_400_YEARS) / 4 - - n2 = 4 * r1 + 3 - u2 = NS_YEAR_MULTIPLIER * n2 - q2 = u2 >> 32 - r2 = (u2 & 0xFFFFFFFF) / NS_YEAR_MULTIPLIER / 4 - - n3 = NS_MONTH_COEFF * r2 + NS_MONTH_OFFSET - q3 = n3 >> 16 - r3 = (n3 & 0xFFFF) / NS_MONTH_COEFF - - y0 = NS_YEARS_PER_CENTURY * q1 + q2 - j = (r2 >= NS_DAYS_BEFORE_NEW_YEAR) ? 1 : 0 - - year = y0 + j - month = j == 1 ? q3 - 12 : q3 - day = r3 + 1 - - [year, month, day] + # JD -> (year, day-of-year) + def jd_to_ordinal(jd, sg) + y, = jd_to_civil(jd, sg) + jd_jan1 = civil_to_jd(y, 1, 1, sg) + [y, jd - jd_jan1 + 1] end - def valid_civil_date?(year, month, day, sg) - return false if month < 1 || month > 12 - - if sg == GREGORIAN || sg < 0 - last_day = last_day_of_month_gregorian(year, month) - elsif sg == JULIAN || sg > 0 - last_day = last_day_of_month_julian(year, month) + # Commercial (ISO week: cwyear, cweek, cwday) -> JD + def commercial_to_jd(y, w, d, sg = -Float::INFINITY) + # Jan 4 is always in week 1 (ISO 8601) + jd_jan4 = civil_to_jd(y, 1, 4, sg) + # Monday of week 1 + wday_jan4 = (jd_jan4 + 1) % 7 # 0=Sun + iso_wday_jan4 = wday_jan4 == 0 ? 7 : wday_jan4 + mon_wk1 = jd_jan4 - (iso_wday_jan4 - 1) + mon_wk1 + (w - 1) * 7 + (d - 1) + end + + # JD -> (cwyear, cweek, cwday) + def jd_to_commercial(jd, sg = -Float::INFINITY) + wday = (jd + 1) % 7 # 0=Sun + cwday = wday == 0 ? 7 : wday # 1=Mon..7=Sun + # Thursday of the same ISO week + thursday = jd + (4 - cwday) + y, = thursday >= sg ? jd_to_gregorian(thursday) : jd_to_julian(thursday) + jd_jan4 = civil_to_jd(y, 1, 4, sg) + wday_jan4 = (jd_jan4 + 1) % 7 + iso_wday_jan4 = wday_jan4 == 0 ? 7 : wday_jan4 + mon_wk1 = jd_jan4 - (iso_wday_jan4 - 1) + cweek = (jd - mon_wk1) / 7 + 1 + [y, cweek, cwday] + end + + # Weeknum (year, week, wday, week_start, sg) -> JD + # week_start: 0=Sun-based (%U), 1=Mon-based (%W) + def weeknum_to_jd(y, w, d, ws, sg = -Float::INFINITY) + jd_jan1 = civil_to_jd(y, 1, 1, sg) + wday_jan1 = (jd_jan1 + 1) % 7 # 0=Sun + j = jd_jan1 - wday_jan1 + j += 1 if ws == 1 + j + 7 * w + d + end + + # n-th k-day (nth occurrence of weekday k in year y, month m) -> JD + # k: 0=Sun..6=Sat, n: positive from beginning, negative from end + def nth_kday_to_jd(y, m, n, k, sg) + if n > 0 + jd_m1 = civil_to_jd(y, m, 1, sg) + wday = (jd_m1 + 1) % 7 + diff = (k - wday + 7) % 7 + jd_m1 + diff + (n - 1) * 7 else - # Calculate (calendar reform period - jd) and determine - jd = gregorian_civil_to_jd(year, month, day) - - if jd < sg - last_day = last_day_of_month_julian(year, month) + # Last day of month + if m == 12 + jd_last = civil_to_jd(y + 1, 1, 1, sg) - 1 else - last_day = last_day_of_month_gregorian(year, month) + jd_last = civil_to_jd(y, m + 1, 1, sg) - 1 end + wday = (jd_last + 1) % 7 + diff = (wday - k + 7) % 7 + jd_last - diff + (n + 1) * 7 end - - return false if day < 1 || day > last_day - - true end - def last_day_of_month_gregorian(y, m) - return nil if m < 1 || m > 12 + # --------------------------------------------------------------------------- + # Validation helpers + # --------------------------------------------------------------------------- - leap_index = gregorian_leap?(y) ? 1 : 0 - MONTH_DAYS[leap_index][m] + def internal_valid_jd?(jd, _sg) + jd.is_a?(Numeric) ? jd.to_i : nil end - def last_day_of_month_julian(y, m) + def internal_valid_civil?(y, m, d, sg) + return nil unless y.is_a?(Numeric) && m.is_a?(Numeric) && d.is_a?(Numeric) + y = y.to_i + m = m.to_i + d = d.to_i + # Handle negative month/day + m += 13 if m < 0 return nil if m < 1 || m > 12 - - leap_index = julian_leap?(y) ? 1 : 0 - MONTH_DAYS[leap_index][m] - end - - def civil_to_jd_with_check(year, month, day, sg) - return nil unless valid_civil_date?(year, month, day, sg) - - jd, ns = civil_to_jd(year, month, day, sg) - - [jd, ns] - end - - def civil_to_jd(year, month, day, sg) - if sg == GREGORIAN - jd = gregorian_civil_to_jd(year, month, day) - - return [jd, 1] - end - - jd = gregorian_civil_to_jd(year, month, day) - - if jd < sg - jd = julian_civil_to_jd(year, month, day) - ns = 0 + # Days in that month + if sg == Float::INFINITY + dim = days_in_month_julian(y, m) else - ns = 1 - end - - [jd, ns] - end - - def last_day_of_month_for_sg(year, month, sg) - last_day_of_month_gregorian(year, month) - end - - def validate_civil(year, month, day, sg) - month += 13 if month < 0 - return nil if month < 1 || month > 12 - - if day < 0 - last_day = last_day_of_month_gregorian(year, month) - return nil unless last_day - day = last_day + day + 1 + dim = days_in_month_gregorian(y, m) end - - last_day = last_day_of_month_gregorian(year, month) - return nil if day < 1 || day > last_day - - nth, ry = decode_year(year, -1) - - jd, ns = civil_to_jd_with_style(ry, month, day, sg) - - [nth, ry, month, day, jd, ns] + d += dim + 1 if d < 0 + return nil if d < 1 || d > dim + civil_to_jd(y, m, d, sg) end - def civil_to_jd_with_style(year, month, day, sg) - jd = gregorian_civil_to_jd(year, month, day) - - if jd < sg - jd = julian_civil_to_jd(year, month, day) - ns = 0 + def internal_valid_ordinal?(y, yday, sg) + return nil unless y.is_a?(Numeric) && yday.is_a?(Numeric) + y = y.to_i + yday = yday.to_i + # Days in year + if sg == Float::INFINITY + diy = internal_julian_leap?(y) ? 366 : 365 else - ns = 1 - end - - [jd, ns] + diy = internal_gregorian_leap?(y) ? 366 : 365 + end + yday += diy + 1 if yday < 0 + return nil if yday < 1 || yday > diy + ordinal_to_jd(y, yday, sg) + end + + def internal_valid_commercial?(y, w, d, sg) + return nil unless y.is_a?(Numeric) && w.is_a?(Numeric) && d.is_a?(Numeric) + y = y.to_i + w = w.to_i + d = d.to_i + # ISO cwday: 1=Mon..7=Sun + d += 8 if d < 0 + return nil if d < 1 || d > 7 + # Weeks in year: Dec 28 is always in the last ISO week + jd_dec28 = civil_to_jd(y, 12, 28, sg) + _, max_week, = jd_to_commercial(jd_dec28, sg) + w += max_week + 1 if w < 0 + return nil if w < 1 || w > max_week + commercial_to_jd(y, w, d, sg) + end + + # --------------------------------------------------------------------------- + # Internal object factory + # --------------------------------------------------------------------------- + + # Build a Date from a Julian Day Number (integer part), start, and optional day fraction. + def _new_from_jd(jd, sg, df = nil) + obj = allocate + obj.__send__(:_init_from_jd, jd, sg, df) + obj end - def convert_to_integer(value) - if value.respond_to?(:to_int) - value.to_int - elsif value.is_a?(Numeric) - value.to_i + # Parse offset string like "+09:00", "-07:30", "Z" to seconds. + def _offset_str_to_sec(str) + case str + when 'Z', 'z', 'UTC', 'GMT' + 0 + when /\A([+-])(\d{1,2}):?(\d{2})(?::(\d{2}))?\z/ + sign = $1 == '+' ? 1 : -1 + h, m, s = $2.to_i, $3.to_i, ($4 || '0').to_i + sign * (h * 3600 + m * 60 + s) + when /\A([+-])(\d{2})(\d{2})\z/ + sign = $1 == '+' ? 1 : -1 + h, m = $2.to_i, $3.to_i + sign * (h * 3600 + m * 60) else - value + 0 end end - def numeric?(value) - value.is_a?(Numeric) || value.respond_to?(:to_int) - end - - def valid_civil_sub(year, month, day, start, need_jd) - year = convert_to_integer(year) - month = convert_to_integer(month) - day = convert_to_integer(day) - - start = valid_sg(start) - - return nil if month < 1 || month > 12 - - leap_year = start == JULIAN ? julian_leap?(year) : gregorian_leap?(year) - max_day = MONTH_DAYS[leap_year ? 1 : 0][month] - - return nil if day < 1 || day > max_day + end - need_jd ? civil_to_jd(year, month, day, start) : 0 - end - - def valid_sg(start) - unless c_valid_start_p(start) - warn "invalid start is ignored" - return 0 - end - - start - end - - def c_valid_start_p(start) - return false unless start.is_a?(Numeric) - - return false if start.respond_to?(:nan?) && start.nan? - - return true if start.respond_to?(:infinite?) && start.infinite? - - return false if start < REFORM_BEGIN_JD || start > REFORM_END_JD - - true - end - - def valid_jd_sub(jd, start, need_jd) - valid_sg(start) - - jd - end - - def valid_commercial_sub(year, week, day, start, need_jd) - week = convert_to_integer(week) - day = convert_to_integer(day) - - valid_sg(start) - - result = valid_commercial_p(year, week, day, start) - - return nil unless result - - return 0 unless need_jd - - encode_jd(result[:nth], result[:rjd]) - end - - def valid_commercial_p(year, week, day, start) - style = guess_style(year, start) - - if style.zero? - int_year = year.to_i - result = c_valid_commercial_p(int_year, week, day, start) - return nil unless result - - nth, rjd = decode_jd(result[:jd]) - - if f_zero_p?(nth) - ry = int_year - else - ns = result[:ns] - _, ry = decode_year(year, ns.nonzero? ? -1 : 1) - end - - { nth: nth, ry: ry, rw: result[:rw], rd: result[:rd], rjd: rjd, ns: result[:ns] } - else - nth, ry = decode_year(year, style) - result = c_valid_commercial_p(ry, week, day, style) - return nil unless result - - { nth: nth, ry: ry, rw: result[:rw], rd: result[:rd], rjd: result[:jd], ns: result[:ns] } - end - end - - def guess_style(year, sg) - return sg if sg.infinite? - return year >= 0 ? GREGORIAN : JULIAN unless year.is_a?(Integer) && year.abs < (1 << 62) - - int_year = year.to_i - if int_year < REFORM_BEGIN_YEAR - JULIAN - elsif int_year > REFORM_END_YEAR - GREGORIAN - else - 0 - end - end - - def c_valid_commercial_p(year, week, day, sg) - day += 8 if day < 0 - - if week < 0 - rjd2, _ = c_commercial_to_jd(year + 1, 1, 1, sg) - ry2, rw2, _ = c_jd_to_commercial(rjd2 + week * 7, sg) - return nil if ry2 != year - - week = rw2 - end - - rjd, ns = c_commercial_to_jd(year, week, day, sg) - ry2, rw, rd = c_jd_to_commercial(rjd, sg) - - return nil if year != ry2 || week != rw || day != rd - - { jd: rjd, ns: ns, rw: rw, rd: rd } - end - - def c_commercial_to_jd(year, week, day, sg) - rjd2, _ = c_find_fdoy(year, sg) - rjd2 += 3 - - # Calcurate ISO week number. - rjd = (rjd2 - ((rjd2 - 1 + 1) % 7)) + 7 * (week - 1) + (day - 1) - ns = (rjd < sg) ? 0 : 1 - - [rjd, ns] - end - - def c_jd_to_commercial(jd, sg) - ry2, _, _ = c_jd_to_civil(jd - 3, sg) - a = ry2 - - rjd2, _ = c_commercial_to_jd(a + 1, 1, 1, sg) - if jd >= rjd2 - ry = a + 1 - else - rjd2, _ = c_commercial_to_jd(a, 1, 1, sg) - ry = a - end - - rw = 1 + (jd - rjd2) / 7 - rd = (jd + 1) % 7 - rd = 7 if rd.zero? - - [ry, rw, rd] - end - - def c_find_fdoy(year, sg) - if c_gregorian_only_p?(sg) - jd = c_gregorian_fdoy(year) - - return [jd, 1] - end - - # Keep existing loop for Julian/reform period - (1..30).each do |d| - result = c_valid_civil_p(year, 1, d, sg) - - return [result[:jd], result[:ns]] if result - end - - [nil, nil] - end - - def c_find_ldom(year, month, sg) - if c_gregorian_only_p?(sg) - jd = c_gregorian_ldom_jd(year, month) - - return [jd, 1] - end - - # Keep existing loop for Julian/reform period - (0..29).each do |i| - result = c_valid_civil_p(year, month, 31 - i, sg) - return [result[:jd], result[:ns]] if result - end - - nil - end - - def c_gregorian_fdoy(year) - c_gregorian_civil_to_jd(year, 1, 1) - end - - def c_jd_to_civil(jd, sg) - # Fast path: pure Gregorian or date after switchover, within safe range - if (c_gregorian_only_p?(sg) || jd >= sg) && ns_jd_in_range(jd) - return c_gregorian_jd_to_civil(jd) - end - - # Original algorithm for Julian calendar or extreme dates - if jd < sg - a = jd - else - x = ((jd - 1867216.25) / 36524.25).floor - a = jd + 1 + x - (x / 4.0).floor - end - - b = a + 1524 - c = ((b - 122.1) / 365.25).floor - d = (365.25 * c).floor - e = ((b - d) / 30.6001).floor - dom = b - d - (30.6001 * e).floor - - if e <= 13 - m = e - 1 - y = c - 4716 - else - m = e - 13 - y = c - 4715 - end - - [y.to_i, m.to_i, dom.to_i] - end - - # Optimized: Julian Day Number -> Gregorian date - def c_gregorian_jd_to_civil(jd) - # The argument jd of c_gregorian_jd_to_civil implemented in C is of type int, - # so it is converted to Integer. - jd = jd.to_i unless jd.is_a?(Integer) - - # Convert JDN to rata die (March 1, Year 0 epoch) - r0 = jd - NS_EPOCH - - # Extract century and day within 400-year cycle - # Use Euclidean (floor) division for negative values - n1 = 4 * r0 + 3 - q1 = n1 / NS_DAYS_IN_400_YEARS - r1 = (n1 % NS_DAYS_IN_400_YEARS) / 4 - - # Calculate year within century and day of year - n2 = 4 * r1 + 3 - # Use 64-bit arithmetic to avoid overflow - u2 = NS_YEAR_MULTIPLIER * n2 - q2 = u2 >> 32 - r2 = (u2 & 0xFFFFFFFF) / NS_YEAR_MULTIPLIER / 4 - - # Calculate month and day using integer arithmetic - n3 = NS_MONTH_COEFF * r2 + NS_MONTH_OFFSET - q3 = n3 >> 16 - r3 = (n3 & 0xFFFF) / NS_MONTH_COEFF - - # Combine century and year - y0 = NS_YEARS_PER_CENTURY * q1 + q2 - - # Adjust for January/February (shift from fiscal year) - j = (r2 >= NS_DAYS_BEFORE_NEW_YEAR) ? 1 : 0 - - ry = y0 + j - rm = j.nonzero? ? q3 - 12 : q3 - rd = r3 + 1 - - [ry, rm, rd] - end - - def c_gregorian_civil_to_jd(year, month, day) - j = (month < 3) ? 1 : 0 - y0 = year - j - m0 = j.nonzero? ? month + 12 : month - d0 = day - 1 - - q1 = y0 / 100 - yc = (NS_DAYS_IN_4_YEARS * y0) / 4 - q1 + q1 / 4 - - mc = (NS_DAYS_BEFORE_NEW_YEAR * m0 - 914) / 10 - - yc + mc + d0 + NS_EPOCH - end - - def valid_civil_p(y, m, d, sg) - style = guess_style(y, sg) - - if style.zero? - # If year is a Fixnum - int_year = y.to_i - - # Validate with c_valid_civil_p - result = c_valid_civil_p(int_year, m, d, sg) - return nil unless result - - # decode_jd - nth, rjd = decode_jd(result[:jd]) - - if f_zero_p?(nth) - ry = int_year - else - ns = result[:ns] - _, ry = decode_year(y, ns.nonzero? ? -1 : 1) - end - - return { nth: nth, ry: ry, rm: result[:rm], rd: result[:rd], rjd: rjd, ns: result[:ns] } - else - # If year is a large number - nth, ry = decode_year(y, style) - - result = style < 0 ? c_valid_gregorian_p(ry, m, d) : result = c_valid_julian_p(ry, m, d) - return nil unless result - - # Calculate JD from civil - rjd, ns = c_civil_to_jd(ry, result[:rm], result[:rd], style) - - return { nth: nth, ry: ry, rm: result[:rm], rd: result[:rd], rjd: rjd, ns: ns } - end - end - - def c_valid_civil_p(year, month, day, sg) - month += 13 if month < 0 - return nil if month < 1 || month > 12 - - rd = day - if rd < 0 - result = c_find_ldom(year, month, sg) - return nil unless result - - rjd2, _ = result - ry2, rm2, rd2 = c_jd_to_civil(rjd2 + rd + 1, sg) - return nil if ry2 != year || rm2 != month - - rd = rd2 - end - - rjd, ns = c_civil_to_jd(year, month, rd, sg) - ry2, rm2, rd2 = c_jd_to_civil(rjd, sg) - - return nil if ry2 != year || rm2 != month || rd2 != rd - - { jd: rjd, ns: ns, rm: rm2, rd: rd } - end - - def c_gregorian_ldom_jd(year, month) - last_day = c_gregorian_last_day_of_month(year, month) - c_gregorian_civil_to_jd(year, month, last_day) - end - - def c_gregorian_last_day_of_month(year, month) - MONTH_DAYS[gregorian_leap?(year) ? 1 : 0][month] - end - - def c_civil_to_jd(year, month, day, sg) - if c_gregorian_only_p?(sg) - jd = c_gregorian_civil_to_jd(year, month, day) - - return [jd, 1] - end - - # Calculate Gregorian JD using optimized algorithm - jd = c_gregorian_civil_to_jd(year, month, day) - - if jd < sg - y2 = year - m2 = month - if m2 <= 2 - y2 -= 1 - m2 += 12 - end - jd = (365.25 * (y2 + 4716)).floor + (30.6001 * (m2 + 1)).floor + day - 1524 - ns = 0 - else - ns = 1 - end - - [jd, ns] - end - - def decode_jd(jd) - nth = jd / CM_PERIOD - rjd = f_zero_p?(nth) ? jd : jd % CM_PERIOD - - [nth, rjd] - end - - def encode_jd(nth, rjd) - f_zero_p?(nth) ? rjd : nth * CM_PERIOD + rjd - end - - def decode_year(year, style) - period = (style < 0) ? CM_PERIOD_GCY : CM_PERIOD_JCY - - if year.is_a?(Integer) && year.abs < (1 << 30) - shifted = year + 4712 - nth = shifted / period - - shifted = shifted % period if f_nonzero_p?(nth) - - ry = shifted - 4712 - else - shifted = year + 4712 - nth = shifted / period - - shifted = shifted % period if f_nonzero_p?(nth) - - ry = shifted.to_i - 4712 - end - - [nth, ry] - end - - # Check if using pure Gregorian calendar (sg == -Infinity) - def c_gregorian_only_p?(sg) - sg.infinite? && sg < 0 - end - - def valid_ordinal_sub(year, day, start, need_jd) - day = convert_to_integer(day) - - valid_sg(start) - - result = valid_ordinal_p(year, day, start) - - return nil unless result - - return 0 unless need_jd - - encode_jd(result[:nth], result[:rjd]) - end - - def valid_ordinal_p(year, day, start) - style = guess_style(year, start) - - if style.zero? - int_year = year.to_i - result = c_valid_ordinal_p(int_year, day, start) - - return nil unless result - - nth, rjd = decode_jd(result[:jd]) - - if f_zero_p?(nth) - ry = int_year - else - ns = result[:ns] - _, ry = decode_year(year, ns.nonzero? ? -1 : 1) - end - - return { nth: nth, ry: ry, rd: result[:rd], rjd: rjd, ns: result[:ns] } - else - nth, ry = decode_year(year, style) - result = c_valid_ordinal_p(ry, day, style) - return nil unless result - - return { nth: nth, ry: ry, rd: result[:rd], rjd: result[:jd], ns: result[:ns] } - end - end - - def c_valid_ordinal_p(year, day, sg) - rd = day - if rd < 0 - result = c_find_ldoy(year, sg) - return nil unless result - - rjd2, _ = result - ry2, rd2 = c_jd_to_ordinal(rjd2 + rd + 1, sg) - return nil if ry2 != year - - rd = rd2 - end - - rjd, ns = c_ordinal_to_jd(year, rd, sg) - ry2, rd2 = c_jd_to_ordinal(rjd, sg) - - return nil if ry2 != year || rd2 != rd - - { jd: rjd, ns: ns, rd: rd } - end - - def c_find_ldoy(year, sg) - if c_gregorian_only_p?(sg) - jd = c_gregorian_ldoy(year) - - return [jd, 1] - end - - # Keep existing loop for Julian/reform period - (0..29).each do |i| - result = c_valid_civil_p(year, 12, 31 - i, sg) - - return [result[:jd], result[:ns]] if result - end - - nil - end - - # O(1) last day of year for Gregorian calendar - def c_gregorian_ldoy(year) - c_gregorian_civil_to_jd(year, 12, 31) - end - - def c_jd_to_ordinal(jd, sg) - ry, _, _ = c_jd_to_civil(jd, sg) - rjd, _ = c_find_fdoy(ry, sg) - - rd = (jd - rjd) + 1 - - [ry, rd] - end - - def c_ordinal_to_jd(year, day, sg) - rjd, _ = c_find_fdoy(year, sg) - rjd += day - 1 - ns = (rjd < sg) ? 0 : 1 - - [rjd, ns] - end - - def f_zero_p?(x) - case x - when Integer - x.zero? - when Rational - x.numerator == 0 - else - x == 0 - end - end - - def f_nonzero_p?(x) - !f_zero_p?(x) - end - - def c_gregorian_leap_p?(year) - !!(((year % 4).zero? && (year % 100).nonzero?) || (year % 400).zero?) - end - - def c_julian_leap_p?(year) - (year % 4).zero? - end - - def new_with_jd(nth, jd, start) - new_with_jd_and_time(nth, jd, nil, nil, nil, start) - end - - def new_with_jd_and_time(nth, jd, df, sf, of, start) - obj = allocate - obj.send(:_init_with_jd, nth, jd, df, sf, of, start) - obj - end - - def valid_gregorian_p(y, m, d) - decode_year(y, -1) - - c_valid_gregorian_p(y, m, d) - end - - def c_valid_gregorian_p(y, m, d) - m += 13 if m < 0 - return nil if m < 1 || m > 12 - - last = c_gregorian_last_day_of_month(y, m) - d = last + d + 1 if d < 0 - return nil if d < 1 || d > last - - { rm: m, rd: d } - end - - def c_valid_julian_p(y, m, d) - m += 13 if m < 0 - return nil if m < 1 || m > 12 - - last = c_julian_last_day_of_month(y, m) - d = last + d + 1 if d < 0 - return nil if d < 1 || d > last - - { rm: m, rd: d } - end - - def c_julian_last_day_of_month(y, m) - raise Error unless m >= 1 && m <= 12 - - MONTH_DAYS[julian_leap?(y) ? 1 : 0][m] - end - - # Create a simple Date object. - def d_lite_s_alloc_simple - obj = allocate - obj.instance_variable_set(:@nth, 0) - obj.instance_variable_set(:@jd, 0) - obj.instance_variable_set(:@sg, DEFAULT_SG) - obj.instance_variable_set(:@df, nil) - obj.instance_variable_set(:@sf, nil) - obj.instance_variable_set(:@of, nil) - obj.instance_variable_set(:@year, nil) - obj.instance_variable_set(:@month, nil) - obj.instance_variable_set(:@day, nil) - obj.instance_variable_set(:@has_jd, true) - obj.instance_variable_set(:@has_civil, false) - - obj - end - - # Create a complex Date object. - def d_lite_s_alloc_complex - obj = allocate - obj.instance_variable_set(:@nth, 0) - obj.instance_variable_set(:@jd, 0) - obj.instance_variable_set(:@sg, DEFAULT_SG) - obj.instance_variable_set(:@df, nil) - obj.instance_variable_set(:@sf, nil) - obj.instance_variable_set(:@of, nil) - obj.instance_variable_set(:@year, nil) - obj.instance_variable_set(:@month, nil) - obj.instance_variable_set(:@day, nil) - obj.instance_variable_set(:@hour, nil) - obj.instance_variable_set(:@min, nil) - obj.instance_variable_set(:@sec, nil) - obj.instance_variable_set(:@has_jd, true) - obj.instance_variable_set(:@has_civil, false) - - obj - end - - def value_trunc(value) - if value.is_a?(Integer) - [value, 0] - elsif value.is_a?(Float) || value.is_a?(Rational) - trunc = value.truncate - frac = value - trunc - - [trunc, frac] - else - [value.to_i, 0] - end - end - - def d_simple_new_internal(nth, jd, sg, year, mon, mday, flags) - obj = allocate - obj.instance_variable_set(:@nth, canon(nth)) - obj.instance_variable_set(:@jd, jd) - obj.instance_variable_set(:@sg, sg) - obj.instance_variable_set(:@year, year) - obj.instance_variable_set(:@month, mon) - obj.instance_variable_set(:@day, mday) - obj.instance_variable_set(:@has_jd, (flags & HAVE_JD).nonzero?) - obj.instance_variable_set(:@has_civil, (flags & HAVE_CIVIL).nonzero?) - obj.instance_variable_set(:@df, nil) - obj.instance_variable_set(:@sf, nil) - obj.instance_variable_set(:@of, nil) - - obj - end - - def canon(x) - x.is_a?(Rational) && x.denominator == 1 ? x.numerator : x - end - - def ns_jd_in_range(jd) - jd >= NS_JD_MIN && jd <= NS_JD_MAX - end - - def check_limit(str, limit) - unless str.is_a?(String) - begin - str = str.to_str - rescue NoMethodError - raise TypeError, "no implicit conversion of #{str.class} into String" - end - end - - if limit && str.length > limit - raise ArgumentError, "string length (#{str.length}) exceeds the limit #{limit}" - end - - str - end - end - - # Instance methods - - # call-seq: - # year -> integer - # - # Returns the year: - # - # Date.new(2001, 2, 3).year # => 2001 - # (Date.new(1, 1, 1) - 1).year # => 0 - def year - # Hot path: inline m_real_year for the common case (@nth=0, civil cached) - return @year if @nth == 0 && @has_civil - m_real_year - end - - # call-seq: - # mon -> integer - # - # Returns the month in range (1..12): - # - # Date.new(2001, 2, 3).mon # => 2 - def month - # Hot path: inline m_mon for the common case (civil cached) - return @month if @has_civil - m_mon - end - alias mon month - - def day - # Hot path: inline m_mday for the common case (civil cached) - return @day if @has_civil - m_mday - end - alias mday day - - # call-seq: - # d.jd -> integer - # - # Returns the Julian day number. This is a whole number, which is - # adjusted by the offset as the local time. - # - # DateTime.new(2001,2,3,4,5,6,'+7').jd #=> 2451944 - # DateTime.new(2001,2,3,4,5,6,'-7').jd #=> 2451944 - def jd - return @jd if @nth == 0 && @has_jd - m_real_jd - end - - # call-seq: - # start -> float - # - # Returns the Julian start date for calendar reform; - # if not an infinity, the returned value is suitable - # for passing to Date#jd: - # - # d = Date.new(2001, 2, 3, Date::ITALY) - # s = d.start # => 2299161.0 - # Date.jd(s).to_s # => "1582-10-15" - # - # d = Date.new(2001, 2, 3, Date::ENGLAND) - # s = d.start # => 2361222.0 - # Date.jd(s).to_s # => "1752-09-14" - # - # Date.new(2001, 2, 3, Date::GREGORIAN).start # => -Infinity - # Date.new(2001, 2, 3, Date::JULIAN).start # => Infinity - # - # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - def start - @sg - end - - # call-seq: - # self <=> other -> -1, 0, 1 or nil - # - # Compares +self+ and +other+, returning: - # - # - -1 if +other+ is larger. - # - 0 if the two are equal. - # - 1 if +other+ is smaller. - # - +nil+ if the two are incomparable. - # - # Argument +other+ may be: - # - # - Another \Date object: - # - # d = Date.new(2022, 7, 27) # => # - # prev_date = d.prev_day # => # - # next_date = d.next_day # => # - # d <=> next_date # => -1 - # d <=> d # => 0 - # d <=> prev_date # => 1 - # - # - A DateTime object: - # - # d <=> DateTime.new(2022, 7, 26) # => 1 - # d <=> DateTime.new(2022, 7, 27) # => 0 - # d <=> DateTime.new(2022, 7, 28) # => -1 - # - # - A numeric (compares self.ajd to +other+): - # - # d <=> 2459788 # => -1 - # d <=> 2459787 # => 1 - # d <=> 2459786 # => 1 - # d <=> d.ajd # => 0 - # - # - Any other object: - # - # d <=> Object.new # => nil - def <=>(other) - if other.is_a?(Date) && - @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && - other.instance_variable_get(:@nth) == 0 && - other.instance_variable_get(:@has_jd) && - other.instance_variable_get(:@df).nil? && - other.instance_variable_get(:@sf).nil? && - other.instance_variable_get(:@of).nil? - return @jd <=> other.instance_variable_get(:@jd) - end - - case other - when Date - m_canonicalize_jd - other.send(:m_canonicalize_jd) - - a_nth = m_nth - b_nth = other.send(:m_nth) - - cmp = a_nth <=> b_nth - return cmp if cmp.nonzero? - - a_jd = m_jd - b_jd = other.send(:m_jd) - - cmp = a_jd <=> b_jd - return cmp if cmp.nonzero? - - a_df = m_df - b_df = other.send(:m_df) - - cmp = a_df <=> b_df - return cmp if cmp.nonzero? - - a_sf = m_sf - b_sf = other.send(:m_sf) - - a_sf <=> b_sf - when Numeric - ajd <=> other - else - begin - l, r = other.coerce(self) - l <=> r - rescue NoMethodError - nil - end - end - end - - def <(other) # :nodoc: - if other.is_a?(Date) && - @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && - other.instance_variable_get(:@nth) == 0 && - other.instance_variable_get(:@has_jd) && - other.instance_variable_get(:@df).nil? && - other.instance_variable_get(:@sf).nil? && - other.instance_variable_get(:@of).nil? - return @jd < other.instance_variable_get(:@jd) - end - super - end - - def >(other) # :nodoc: - if other.is_a?(Date) && - @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && - other.instance_variable_get(:@nth) == 0 && - other.instance_variable_get(:@has_jd) && - other.instance_variable_get(:@df).nil? && - other.instance_variable_get(:@sf).nil? && - other.instance_variable_get(:@of).nil? - return @jd > other.instance_variable_get(:@jd) - end - super - end - - # call-seq: - # self === other -> true, false, or nil. - # - # Returns +true+ if +self+ and +other+ represent the same date, - # +false+ if not, +nil+ if the two are not comparable. - # - # Argument +other+ may be: - # - # - Another \Date object: - # - # d = Date.new(2022, 7, 27) # => # - # prev_date = d.prev_day # => # - # next_date = d.next_day # => # - # d === prev_date # => false - # d === d # => true - # d === next_date # => false - # - # - A DateTime object: - # - # d === DateTime.new(2022, 7, 26) # => false - # d === DateTime.new(2022, 7, 27) # => true - # d === DateTime.new(2022, 7, 28) # => false - # - # - A numeric (compares self.jd to +other+): - # - # d === 2459788 # => true - # d === 2459787 # => false - # d === 2459786 # => false - # d === d.jd # => true - # - # - An object not comparable: - # - # d === Object.new # => nil - def ===(other) - if other.is_a?(Date) && - @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && - @jd >= 0 && @jd < CM_PERIOD && - other.instance_variable_get(:@nth) == 0 && - other.instance_variable_get(:@has_jd) && - other.instance_variable_get(:@df).nil? && - other.instance_variable_get(:@sf).nil? && - other.instance_variable_get(:@of).nil? - return @jd == other.instance_variable_get(:@jd) - end - - return equal_gen(other) unless other.is_a?(Date) - - # Call equal_gen even if the Gregorian calendars do not match. - return equal_gen(other) unless m_gregorian_p? == other.send(:m_gregorian_p?) - - m_canonicalize_jd - other.send(:m_canonicalize_jd) - - a_nth = m_nth - b_nth = other.send(:m_nth) - a_jd = m_local_jd - b_jd = other.send(:m_local_jd) - - a_nth == b_nth && a_jd == b_jd - end - - # call-seq: - # d >> n -> new_date - # - # Returns a new \Date object representing the date - # +n+ months later; +n+ should be a numeric: - # - # (Date.new(2001, 2, 3) >> 1).to_s # => "2001-03-03" - # (Date.new(2001, 2, 3) >> -2).to_s # => "2000-12-03" - # - # When the same day does not exist for the new month, - # the last day of that month is used instead: - # - # (Date.new(2001, 1, 31) >> 1).to_s # => "2001-02-28" - # (Date.new(2001, 1, 31) >> -4).to_s # => "2000-09-30" - # - # This results in the following, possibly unexpected, behaviors: - # - # d0 = Date.new(2001, 1, 31) - # d1 = d0 >> 1 # => # - # d2 = d1 >> 1 # => # - # - # d0 = Date.new(2001, 1, 31) - # d1 = d0 >> 1 # => # - # d2 = d1 >> -1 # => # - def >>(n) - if n.is_a?(Integer) && @of.nil? && @nth == 0 && @has_civil - sg = @sg - gregorian_fast = if sg.is_a?(Float) && sg.infinite? - sg < 0 - elsif sg.is_a?(Integer) && sg >= REFORM_BEGIN_JD && sg <= REFORM_END_JD - @year > REFORM_END_YEAR - end - if gregorian_fast - t = @year * 12 + (@month - 1) + n - y = t / 12 - m = (t % 12) + 1 - d = @day - - leap = (y % 4 == 0) && (y % 100 != 0 || y % 400 == 0) - last = MONTH_DAYS[leap ? 1 : 0][m] - d = last if d > last - - obj = self.class.allocate - obj._init_simple_with_civil(y, m, d, sg) - return obj - end - end - - # Calculate years and months - t = m_real_year * 12 + (m_mon - 1) + n - - if t.is_a?(Integer) && t.abs < (1 << 62) - # Fixnum - y = t / 12 - m = (t % 12) + 1 - else - # Bignum - y = t.div(12) - m = (t % 12).to_i + 1 - end - - d = m_mday - sg = m_sg - - # Decrement days until a valid date. - result = nil - loop do - result = self.class.send(:valid_civil_p, y, m, d, sg) - break if result - - d -= 1 - raise Error if d < 1 - end - - nth = result[:nth] - rjd = result[:rjd] - rjd2 = self.class.send(:encode_jd, nth, rjd) - - self + (rjd2 - m_real_local_jd) - end - - # call-seq: - # d << n -> date - # - # Returns a new \Date object representing the date - # +n+ months earlier; +n+ should be a numeric: - # - # (Date.new(2001, 2, 3) << 1).to_s # => "2001-01-03" - # (Date.new(2001, 2, 3) << -2).to_s # => "2001-04-03" - # - # When the same day does not exist for the new month, - # the last day of that month is used instead: - # - # (Date.new(2001, 3, 31) << 1).to_s # => "2001-02-28" - # (Date.new(2001, 3, 31) << -6).to_s # => "2001-09-30" - # - # This results in the following, possibly unexpected, behaviors: - # - # d0 = Date.new(2001, 3, 31) - # d0 << 2 # => # - # d0 << 1 << 1 # => # - # - # d0 = Date.new(2001, 3, 31) - # d1 = d0 << 1 # => # - # d2 = d1 << -1 # => # - def <<(n) - if n.is_a?(Integer) && @of.nil? && @nth == 0 && @has_civil - sg = @sg - gregorian_fast = if sg.is_a?(Float) && sg.infinite? - sg < 0 - elsif sg.is_a?(Integer) && sg >= REFORM_BEGIN_JD && sg <= REFORM_END_JD - @year > REFORM_END_YEAR - end - if gregorian_fast - t = @year * 12 + (@month - 1) - n - y = t / 12 - m = (t % 12) + 1 - d = @day - - leap = (y % 4 == 0) && (y % 100 != 0 || y % 400 == 0) - last = MONTH_DAYS[leap ? 1 : 0][m] - d = last if d > last - - obj = self.class.allocate - obj._init_simple_with_civil(y, m, d, sg) - return obj - end - end - - raise TypeError, "expected numeric" unless n.is_a?(Numeric) - - t = m_real_year * 12 + (m_mon - 1) - n - - if t.is_a?(Integer) && t.abs < (1 << 62) - y = t / 12 - m = (t % 12) + 1 - else - y = t.div(12) - m = (t % 12).to_i + 1 - end - - d = m_mday - sg = m_sg - - result = nil - loop do - result = self.class.send(:valid_civil_p, y, m, d, sg) - break if result - - d -= 1 - raise Error if d < 1 - end - - nth = result[:nth] - rjd = result[:rjd] - rjd2 = self.class.send(:encode_jd, nth, rjd) - - self + (rjd2 - m_real_local_jd) - end - - def ==(other) # :nodoc: - if other.is_a?(Date) && - @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && - other.instance_variable_get(:@nth) == 0 && - other.instance_variable_get(:@has_jd) && - other.instance_variable_get(:@df).nil? && - other.instance_variable_get(:@sf).nil? && - other.instance_variable_get(:@of).nil? - return @jd == other.instance_variable_get(:@jd) - end - - return false unless other.is_a?(Date) - - m_canonicalize_jd - other.send(:m_canonicalize_jd) - - m_nth == other.send(:m_nth) && - m_jd == other.send(:m_jd) && - m_df == other.send(:m_df) && - m_sf == other.send(:m_sf) - end - - def eql?(other) # :nodoc: - if other.is_a?(Date) && - @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && - other.instance_variable_get(:@nth) == 0 && - other.instance_variable_get(:@has_jd) && - other.instance_variable_get(:@df).nil? && - other.instance_variable_get(:@sf).nil? && - other.instance_variable_get(:@of).nil? - return @jd == other.instance_variable_get(:@jd) && - @sg == other.instance_variable_get(:@sg) - end - - return false unless other.is_a?(Date) - - m_canonicalize_jd - other.send(:m_canonicalize_jd) - - m_nth == other.send(:m_nth) && - m_jd == other.send(:m_jd) && - @sg == other.instance_variable_get(:@sg) - end - - def hash # :nodoc: - if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_jd && - @jd >= 0 && @jd < CM_PERIOD - return [0, @jd, @sg].hash - end - m_canonicalize_jd - [m_nth, m_jd, @sg].hash - end - - # call-seq: - # d + other -> date - # - # Returns a date object pointing +other+ days after self. The other - # should be a numeric value. If the other is a fractional number, - # assumes its precision is at most nanosecond. - # - # Date.new(2001,2,3) + 1 #=> # - # DateTime.new(2001,2,3) + Rational(1,2) - # #=> # - # DateTime.new(2001,2,3) + Rational(-1,2) - # #=> # - # DateTime.jd(0,12) + DateTime.new(2001,2,3).ajd - # #=> # - def +(other) - if other.is_a?(Integer) && @of.nil? && @nth == 0 - if @has_jd - jd = @jd + other - elsif @has_civil - sg = @sg - gregorian_fast = if sg.is_a?(Float) && sg.infinite? - sg < 0 - elsif sg.is_a?(Integer) && sg >= REFORM_BEGIN_JD && sg <= REFORM_END_JD - @year > REFORM_END_YEAR - end - if gregorian_fast - j = (@month < 3) ? 1 : 0 - y0 = @year - j - m0 = j.nonzero? ? @month + 12 : @month - d0 = @day - 1 - q1 = y0 / 100 - yc = (NS_DAYS_IN_4_YEARS * y0) / 4 - q1 + q1 / 4 - mc = (NS_DAYS_BEFORE_NEW_YEAR * m0 - 914) / 10 - jd = yc + mc + d0 + NS_EPOCH + other - end - end - if jd && jd >= 0 && jd < CM_PERIOD - obj = self.class.allocate - obj._init_simple_with_jd(jd, @sg) - return obj - end - end - - case other - when Integer - nth = m_nth - jd = m_jd - - if (other / CM_PERIOD).nonzero? - nth = nth + (other / CM_PERIOD) - other = other % CM_PERIOD - end - - if other.nonzero? - jd = jd + other - nth, jd = canonicalize_jd(nth, jd) - end - - obj = self.class.allocate - if simple_dat_p? - obj._init_with_jd(nth, jd, nil, nil, nil, @sg) - else - obj._init_with_jd(nth, jd, @df || 0, @sf || 0, @of || 0, @sg) - end - obj - when Float - s = other >= 0 ? 1 : -1 - o = other.abs - - tmp, o = o.divmod(1.0) - - if (tmp / CM_PERIOD).floor.zero? - nth = 0 - jd = tmp.to_i - else - i, f = (tmp / CM_PERIOD).divmod(1.0) - nth = i.floor - jd = (f * CM_PERIOD).to_i - end - - o *= DAY_IN_SECONDS - df, o = o.divmod(1.0) - df = df.to_i - o *= SECOND_IN_NANOSECONDS - sf = o.round - - if s < 0 - jd = -jd - df = -df - sf = -sf - end - - if sf.nonzero? - sf = 0 + sf - if sf < 0 - df -= 1 - sf += SECOND_IN_NANOSECONDS - elsif sf >= SECOND_IN_NANOSECONDS - df += 1 - sf -= SECOND_IN_NANOSECONDS - end - end - - if df.nonzero? - df = 0 + df - if df < 0 - jd -= 1 - df += DAY_IN_SECONDS - elsif df >= DAY_IN_SECONDS - jd += 1 - df -= DAY_IN_SECONDS - end - end - - if jd.nonzero? - jd = m_jd + jd - nth, jd = canonicalize_jd(nth, jd) - else - jd = m_jd - end - - nth = nth.nonzero? ? @nth + nth : @nth - - obj = self.class.allocate - if df.zero? && sf.zero? && (@of.nil? || @of.zero?) - obj._init_with_jd(nth, jd, nil, nil, nil, @sg) - else - obj._init_with_jd(nth, jd, df, sf, @of || 0, @sg) - end - obj - when Rational - return self + other.numerator if other.denominator == 1 - - s = other >= 0 ? 1 : -1 - other = other.abs - - nth = other.div(CM_PERIOD) - t = other % CM_PERIOD - - jd = t.div(1).to_i - t = t % 1 - - t = t * DAY_IN_SECONDS - df = t.div(1).to_i - t = t % 1 - - sf = t * SECOND_IN_NANOSECONDS - - if s < 0 - nth = -nth - jd = -jd - df = -df - sf = -sf - end - - if sf.nonzero? - sf = (@sf || 0) + sf - if sf < 0 - df -= 1 - sf += SECOND_IN_NANOSECONDS - elsif sf >= SECOND_IN_NANOSECONDS - df += 1 - sf -= SECOND_IN_NANOSECONDS - end - else - sf = @sf || 0 - end - - if df.nonzero? - df = (@df || 0) + df - if df < 0 - jd -= 1 - df += DAY_IN_SECONDS - elsif df >= DAY_IN_SECONDS - jd += 1 - df -= DAY_IN_SECONDS - end - else - df = @df || 0 - end - - if jd.nonzero? - jd = m_jd + jd - nth, jd = canonicalize_jd(nth, jd) - else - jd = m_jd - end - - nth = nth.nonzero? ? @nth + nth : @nth - - obj = self.class.allocate - if df.zero? && sf.zero? - obj._init_with_jd(nth, jd, nil, nil, nil, @sg) - else - obj._init_with_jd(nth, jd, df, sf, @of || 0, @sg) - end - obj - else - raise TypeError, "expected numeric" unless other.is_a?(Numeric) - - other = other.to_r - raise TypeError, "expected numeric" unless other.is_a?(Rational) - - self + other - end - end - - # call-seq: - # d - other -> date or rational - # - # If the other is a date object, returns a Rational - # whose value is the difference between the two dates in days. - # If the other is a numeric value, returns a date object - # pointing +other+ days before self. - # If the other is a fractional number, - # assumes its precision is at most nanosecond. - # - # Date.new(2001,2,3) - 1 #=> # - # DateTime.new(2001,2,3) - Rational(1,2) #=> # - # Date.new(2001,2,3) - Date.new(2001) #=> (33/1) - # DateTime.new(2001,2,3) - DateTime.new(2001,2,2,12) #=> (1/2) - def -(other) - if other.is_a?(Integer) && @of.nil? && @nth == 0 && @has_jd - jd = @jd - other - if jd >= 0 && jd < CM_PERIOD - obj = self.class.allocate - obj._init_simple_with_jd(jd, @sg) - return obj - end - end - - if other.is_a?(Date) - # Hot path: both simple dates with @nth=0 and JD set. - # Result is always Rational(jd_self - jd_other, 1). - if @df.nil? && @sf.nil? && @of.nil? && @has_jd && @nth == 0 && - other.send(:simple_dat_p?) && - other.instance_variable_get(:@has_jd) && - other.instance_variable_get(:@nth) == 0 - return Rational(@jd - other.instance_variable_get(:@jd), 1) - end - return minus_dd(other) - end - - raise TypeError, "expected numeric" unless other.is_a?(Numeric) - - # Add a negative value for numbers. - # Works with all types: Integer, Float, Rational, Bignum, etc. - self + (-other) - end - - # call-seq: - # gregorian -> new_date - # - # Equivalent to Date#new_start with argument Date::GREGORIAN. - def gregorian - dup_obj_with_new_start(GREGORIAN) - end - - # call-seq: - # gregorian? -> true or false - # - # Returns +true+ if the date is on or after - # the date of calendar reform, +false+ otherwise: - # - # Date.new(1582, 10, 15).gregorian? # => true - # (Date.new(1582, 10, 15) - 1).gregorian? # => false - def gregorian? - m_gregorian_p? - end - - # call-seq: - # italy -> new_date - # - # Equivalent to Date#new_start with argument Date::ITALY. - def italy - dup_obj_with_new_start(ITALY) - end - - # call-seq: - # england -> new_date - # - # Equivalent to Date#new_start with argument Date::ENGLAND. - def england - dup_obj_with_new_start(ENGLAND) - end - - # call-seq: - # julian -> new_date - # - # Equivalent to Date#new_start with argument Date::JULIAN. - def julian - dup_obj_with_new_start(JULIAN) - end - - # call-seq: - # d.julian? -> true or false - # - # Returns +true+ if the date is before the date of calendar reform, - # +false+ otherwise: - # - # (Date.new(1582, 10, 15) - 1).julian? # => true - # Date.new(1582, 10, 15).julian? # => false - def julian? - m_julian_p? - end - - # call-seq: - # ld -> integer - # - # Returns the - # {Lilian day number}[https://en.wikipedia.org/wiki/Lilian_date], - # which is the number of days since the beginning of the Gregorian - # calendar, October 15, 1582. - # - # Date.new(2001, 2, 3).ld # => 152784 - def ld - # Hot path: simple Date with @nth=0 and JD already set. - if @df.nil? && @sf.nil? && @of.nil? && @has_jd && @nth == 0 - return @jd - 2299160 - end - m_real_local_jd - 2299160 - end - - # call-seq: - # leap? -> true or false - # - # Returns +true+ if the year is a leap year, +false+ otherwise: - # - # Date.new(2000).leap? # => true - # Date.new(2001).leap? # => false - def leap? - return @leap unless @leap.nil? - result = if gregorian? - self.class.send(:c_gregorian_leap_p?, m_year) - else - # For the Julian calendar, calculate JD for March 1st. - y = m_year - sg = m_virtual_sg - rjd, _ = self.class.send(:c_civil_to_jd, y, 3, 1, sg) - - # Get the date of the day before March 1st (the last day of February). - _, _, rd = self.class.send(:c_jd_to_civil, rjd - 1, sg) - - # If February 29th exists, it is a leap year. - rd == 29 - end - @leap = result unless frozen? - result - end - - # call-seq: - # new_start(start = Date::ITALY]) -> new_date - # - # Returns a copy of +self+ with the given +start+ value: - # - # d0 = Date.new(2000, 2, 3) - # d0.julian? # => false - # d1 = d0.new_start(Date::JULIAN) - # d1.julian? # => true - # - # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - def new_start(start = DEFAULT_SG) - sg = start ? val2sg(start) : DEFAULT_SG - - dup_obj_with_new_start(sg) - end - - # call-seq: - # next_day(n = 1) -> new_date - # - # Equivalent to Date#+ with argument +n+. - def next_day(n = 1) - self + n - end - - # call-seq: - # prev_day(n = 1) -> new_date - # - # Equivalent to Date#- with argument +n+. - def prev_day(n = 1) - self - n - end - - # call-seq: - # d.next -> new_date - # - # Returns a new \Date object representing the following day: - # - # d = Date.new(2001, 2, 3) - # d.to_s # => "2001-02-03" - # d.next.to_s # => "2001-02-04" - def next - next_day - end - alias_method :succ, :next - - # call-seq: - # next_year(n = 1) -> new_date - # - # Equivalent to #>> with argument n * 12. - def next_year(n = 1) - self >> (n * 12) - end - - # call-seq: - # prev_year(n = 1) -> new_date - # - # Equivalent to #<< with argument n * 12. - def prev_year(n = 1) - self << (n * 12) - end - - # call-seq: - # next_month(n = 1) -> new_date - # - # Equivalent to #>> with argument +n+. - def next_month(n = 1) - self >> n - end - - # call-seq: - # prev_month(n = 1) -> new_date - # - # Equivalent to #<< with argument +n+. - def prev_month(n = 1) - self << n - end - - # call-seq: - # sunday? -> true or false - # - # Returns +true+ if +self+ is a Sunday, +false+ otherwise. - def sunday? - m_wday.zero? - end - - # call-seq: - # monday? -> true or false - # - # Returns +true+ if +self+ is a Monday, +false+ otherwise. - def monday? - m_wday == 1 - end - - # call-seq: - # tuesday? -> true or false - # - # Returns +true+ if +self+ is a Tuesday, +false+ otherwise. - def tuesday? - m_wday == 2 - end - - # call-seq: - # wednesday? -> true or false - # - # Returns +true+ if +self+ is a Wednesday, +false+ otherwise. - def wednesday? - m_wday == 3 - end - - # call-seq: - # thursday? -> true or false - # - # Returns +true+ if +self+ is a Thursday, +false+ otherwise. - def thursday? - m_wday == 4 - end - - # call-seq: - # friday? -> true or false - # - # Returns +true+ if +self+ is a Friday, +false+ otherwise. - def friday? - m_wday == 5 - end - - # call-seq: - # saturday? -> true or false - # - # Returns +true+ if +self+ is a Saturday, +false+ otherwise. - def saturday? - m_wday == 6 - end - - # call-seq: - # wday -> integer - # - # Returns the day of week in range (0..6); Sunday is 0: - # - # Date.new(2001, 2, 3).wday # => 6 - def wday - # Hot path: inline m_wday for simple Date (C: (jd + 1) % 7) - return (@jd + 1) % 7 if @has_jd && @of.nil? - m_wday - end - - # call-seq: - # yday -> integer - # - # Returns the day of the year, in range (1..366): - # - # Date.new(2001, 2, 3).yday # => 34 - def yday - return @yday if @yday - val = m_yday - @yday = val unless frozen? - val - end - - # call-seq: - # deconstruct_keys(array_of_names_or_nil) -> hash - # - # Returns a hash of the name/value pairs, to use in pattern matching. - # Possible keys are: :year, :month, :day, - # :wday, :yday. - # - # Possible usages: - # - # d = Date.new(2022, 10, 5) - # - # if d in wday: 3, day: ..7 # uses deconstruct_keys underneath - # puts "first Wednesday of the month" - # end - # #=> prints "first Wednesday of the month" - # - # case d - # in year: ...2022 - # puts "too old" - # in month: ..9 - # puts "quarter 1-3" - # in wday: 1..5, month: - # puts "working day in month #{month}" - # end - # #=> prints "working day in month 10" - # - # Note that deconstruction by pattern can also be combined with class check: - # - # if d in Date(wday: 3, day: ..7) - # puts "first Wednesday of the month" - # end - def deconstruct_keys(keys) - if keys.nil? - return { - year: year, - month: month, - day: day, - yday: yday, - wday: wday - } - end - - raise TypeError, "wrong argument type #{keys.class} (expected Array or nil)" unless keys.is_a?(Array) - - h = {} - keys.each do |key| - case key - when :year then h[:year] = year - when :month then h[:month] = month - when :day then h[:day] = day - when :yday then h[:yday] = yday - when :wday then h[:wday] = wday - when :zone then h[:zone] = zone - end - end - h - end - - # call-seq: - # step(limit, step = 1){|date| ... } -> self - # - # Calls the block with specified dates; - # returns +self+. - # - # - The first +date+ is +self+. - # - Each successive +date+ is date + step, - # where +step+ is the numeric step size in days. - # - The last date is the last one that is before or equal to +limit+, - # which should be a \Date object. - # - # Example: - # - # limit = Date.new(2001, 12, 31) - # Date.new(2001).step(limit){|date| p date.to_s if date.mday == 31 } - # - # Output: - # - # "2001-01-31" - # "2001-03-31" - # "2001-05-31" - # "2001-07-31" - # "2001-08-31" - # "2001-10-31" - # "2001-12-31" - # - # Returns an Enumerator if no block is given. - def step(limit, step = 1) - raise ArgumentError, "step must be numeric" unless step.respond_to?(:<=>) - - return to_enum(:step, limit, step) unless block_given? - - date = self - cmp = step <=> 0 - - raise ArgumentError, "step must be numeric" if cmp.nil? - - case cmp - when -1 - # If step is negative (reverse order) - while (date <=> limit) >= 0 - yield date - date = date + step - end - when 0 - # If step is 0 (infinite loop) - loop do - yield date - end - else - # If step is positive (forward direction) - while (date <=> limit) <= 0 - yield date - date = date + step - end - end - - self - end - - # call-seq: - # upto(max){|date| ... } -> self - # - # Equivalent to #step with arguments +max+ and +1+. - def upto(max) - return to_enum(:upto, max) unless block_given? - - date = self - - while (date <=> max) <= 0 - yield date - date = date + 1 - end - - self - end - - # call-seq: - # downto(min){|date| ... } -> self - # - # Equivalent to #step with arguments +min+ and -1. - def downto(min) - return to_enum(:downto, min) unless block_given? - - date = self - - while (date <=> min) >= 0 - yield date - date = date - 1 - end - - self - end - - # call-seq: - # day_fraction -> rational - # - # Returns the fractional part of the day in range (Rational(0, 1)...Rational(1, 1)): - # - # DateTime.new(2001,2,3,12).day_fraction # => (1/2) - def day_fraction - simple_dat_p? ? 0 : m_fr - end - - # call-seq: - # d.mjd -> integer - # - # Returns the modified Julian day number. This is a whole number, - # which is adjusted by the offset as the local time. - # - # DateTime.new(2001,2,3,4,5,6,'+7').mjd #=> 51943 - # DateTime.new(2001,2,3,4,5,6,'-7').mjd #=> 51943 - def mjd - # Hot path: simple Date with @nth=0 and JD already set. - if @df.nil? && @sf.nil? && @of.nil? && @has_jd && @nth == 0 - return @jd - 2_400_001 - end - m_real_local_jd - 2_400_001 - end - - # call-seq: - # cwyear -> integer - # - # Returns commercial-date year for +self+ - # (see Date.commercial): - # - # Date.new(2001, 2, 3).cwyear # => 2001 - # Date.new(2000, 1, 1).cwyear # => 1999 - def cwyear - m_real_cwyear - end - - # call-seq: - # cweek -> integer - # - # Returns commercial-date week index for +self+ - # (see Date.commercial): - # - # Date.new(2001, 2, 3).cweek # => 5 - def cweek - m_cweek - end - - # call-seq: - # cwday -> integer - # - # Returns the commercial-date weekday index for +self+ - # (see Date.commercial); - # 1 is Monday: - # - # Date.new(2001, 2, 3).cwday # => 6 - def cwday - m_cwday - end - - # call-seq: - # to_time -> time - # - # Returns a new Time object with the same value as +self+; - # if +self+ is a Julian date, derives its Gregorian date - # for conversion to the \Time object: - # - # Date.new(2001, 2, 3).to_time # => 2001-02-03 00:00:00 -0600 - # Date.new(2001, 2, 3, Date::JULIAN).to_time # => 2001-02-16 00:00:00 -0600 - def to_time - # Julian calendar converted to Gregorian calendar. - date = m_julian_p? ? gregorian : self - - # Create a Time object using Time.local. - Time.local( - date.send(:m_real_year), - date.send(:m_mon), - date.send(:m_mday) - ) - end - - # call-seq: - # to_date -> self - # - # Returns +self+. - def to_date - self - end - - # call-seq: - # to_datetime -> datetime - # - # Returns a DateTime whose value is the same as +self+. - def to_datetime - # Hot path: simple Date with JD already set. - # C: d_lite_to_datetime passes @nth, @jd, @sg directly (no civil->JD conversion). - if @df.nil? && @sf.nil? && @of.nil? && @has_jd - return DateTime.send(:new_with_jd_and_time, @nth, @jd, 0, 0, 0, @sg) - end - - # Original path for complex dates or JD-less simple dates. - nth, ry = self.class.send(:decode_year, year, -1) - rjd, _ = self.class.send(:c_civil_to_jd, ry, month, day, Date::GREGORIAN) - obj = DateTime.send(:new_with_jd_and_time, nth, rjd, 0, 0, 0, Date::GREGORIAN) - obj.send(:set_sg, start) - obj - end - - # call-seq: - # d.ajd -> rational - # - # Returns the astronomical Julian day number. This is a fractional - # number, which is not adjusted by the offset. - # - # DateTime.new(2001,2,3,4,5,6,'+7').ajd #=> (11769328217/4800) - # DateTime.new(2001,2,2,14,5,6,'-7').ajd #=> (11769328217/4800) - def ajd - # Hot path: simple Date with @nth=0 and JD already set. - # ajd = jd - 1/2 = Rational(jd * 2 - 1, 2) - if @df.nil? && @sf.nil? && @of.nil? && @has_jd && @nth == 0 - return Rational(@jd * 2 - 1, 2) - end - m_ajd - end - - # call-seq: - # d.amjd -> rational - # - # Returns the astronomical modified Julian day number. This is - # a fractional number, which is not adjusted by the offset. - # - # DateTime.new(2001,2,3,4,5,6,'+7').amjd #=> (249325817/4800) - # DateTime.new(2001,2,2,14,5,6,'-7').amjd #=> (249325817/4800) - def amjd - # Hot path: simple Date with @nth=0 and JD already set. - # amjd = jd - 2400001 as Rational - if @df.nil? && @sf.nil? && @of.nil? && @has_jd && @nth == 0 - return Rational(@jd - 2400001, 1) - end - m_amjd - end - - # :nodoc: - # C: d_lite_initialize_copy - def initialize_copy(other) - unless other.is_a?(Date) - raise TypeError, "initialize_copy should take same class object" - end - @nth = other.instance_variable_get(:@nth) - @jd = other.instance_variable_get(:@jd) - @sg = other.instance_variable_get(:@sg) - @df = other.instance_variable_get(:@df) - @sf = other.instance_variable_get(:@sf) - @of = other.instance_variable_get(:@of) - @year = other.instance_variable_get(:@year) - @month = other.instance_variable_get(:@month) - @day = other.instance_variable_get(:@day) - @has_jd = other.instance_variable_get(:@has_jd) - @has_civil = other.instance_variable_get(:@has_civil) - self - end - - # :nodoc: - def marshal_dump - [ - m_nth, - m_jd, - m_df, - m_sf, - m_of, - @sg - ] - end - - # :nodoc: - # C: d_lite_marshal_load - # Supports 3 historical formats: - # 2 elements (1.4/1.6): [jd_like, sg_or_bool] - # 3 elements (1.8/1.9.2): [ajd, of, sg] - # 6 elements (current): [nth, jd, df, sf, of, sg] - def marshal_load(array) - raise TypeError, "expected an array" unless array.is_a?(Array) - - case array.size - when 2 # Ruby 1.4/1.6 - # C: ajd = f_sub(a[0], half_days_in_day); vof = 0; vsg = a[1] - ajd = array[0] - Rational(1, 2) - vof = 0 - vsg = array[1] - unless vsg.is_a?(Numeric) - vsg = vsg ? -Float::INFINITY : Float::INFINITY - end - nth, jd, df, sf, of_sec, sg = old_to_new(ajd, vof, vsg) - - when 3 # Ruby 1.8 / 1.9.2 - ajd = array[0] - vof = array[1] - vsg = array[2] - nth, jd, df, sf, of_sec, sg = old_to_new(ajd, vof, vsg) - - when 6 # Current format - nth, jd, df, sf, of_sec, sg = array - - else - raise TypeError, "invalid size" - end - - @nth = nth - @jd = jd - @df = (!df || df == 0) ? nil : df - @sf = (!sf || sf == 0) ? nil : sf - @of = (!of_sec || of_sec == 0) ? nil : of_sec - @sg = sg - - @has_jd = true - @has_civil = false - @year = nil - @month = nil - @day = nil - end + # --------------------------------------------------------------------------- + # Initializer + # --------------------------------------------------------------------------- # call-seq: - # asctime -> string + # Date.new(year = -4712, month = 1, mday = 1, start = Date::ITALY) -> date # - # Equivalent to #strftime with argument '%a %b %e %T %Y' - # (or its {shorthand form}[rdoc-ref:language/strftime_formatting.rdoc@Shorthand+Conversion+Specifiers] - # '%c'): + # Returns a new \Date object constructed from the given arguments: # - # Date.new(2001, 2, 3).asctime # => "Sat Feb 3 00:00:00 2001" + # Date.new(2022).to_s # => "2022-01-01" + # Date.new(2022, 2).to_s # => "2022-02-01" + # Date.new(2022, 2, 4).to_s # => "2022-02-04" # - # See {asctime}[https://linux.die.net/man/3/asctime]. + # Argument +month+ should be in range (1..12) or range (-12..-1); + # when the argument is negative, counts backward from the end of the year: # - def asctime - if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil && @has_jd - y = @year - wday = (@jd + 1) % 7 - ed = @day < 10 ? " #{@day}" : @day.to_s - y_str = if y >= 0 && y <= 9999 - FOUR_DIGIT[y] - elsif y >= 0 - sprintf("%04d", y) - else - sprintf("%05d", y) - end - str = "#{ABBR_DAYNAMES[wday]} #{ABBR_MONTHNAMES[@month]} #{ed} 00:00:00 #{y_str}" - str.force_encoding(Encoding::US_ASCII) - else - strftime('%a %b %e %H:%M:%S %Y') + # Date.new(2022, -11, 4).to_s # => "2022-02-04" + # + # Argument +mday+ should be in range (1..n) or range (-n..-1) + # where +n+ is the number of days in the month; + # when the argument is negative, counts backward from the end of the month. + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # + # Related: Date.jd. + def initialize(year = -4712, month = 1, day = 1, start = DEFAULT_SG) + if Integer === year && Integer === month && Integer === day + m = month + m += 13 if m < 0 + if m >= 1 && m <= 12 + dim = if m == 2 + if start == Float::INFINITY + year % 4 == 0 ? 29 : 28 + else + (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 29 : 28 + end + else + DAYS_IN_MONTH_GREGORIAN[m] + end + d = day + d += dim + 1 if d < 0 + if d >= 1 && d <= dim + gy = m <= 2 ? year - 1 : year + gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[m] + d + if start == Float::INFINITY + @jd = gjd_base - 1524 + elsif start == -Float::INFINITY + a = gy / 100 + @jd = gjd_base - 1524 + 2 - a + a / 4 + else + a = gy / 100 + gjd = gjd_base - 1524 + 2 - a + a / 4 + @jd = gjd >= start ? gjd : gjd_base - 1524 + end + @sg = start + @year = year + @month = m + @day = d + return + end + end + raise Date::Error, "invalid date" end + year = Integer(year) + month = Integer(month) + day = Integer(day) + jd = self.class.__send__(:internal_valid_civil?, year, month, day, start) + raise Date::Error, "invalid date" unless jd + _init_from_jd(jd, start) end - alias_method :ctime, :asctime + + # --------------------------------------------------------------------------- + # Instance methods - basic attributes + # --------------------------------------------------------------------------- # call-seq: - # iso8601 -> string + # year -> integer # - # Equivalent to #strftime with argument '%Y-%m-%d' - # (or its {shorthand form}[rdoc-ref:language/strftime_formatting.rdoc@Shorthand+Conversion+Specifiers] - # '%F'); + # Returns the year: # - # Date.new(2001, 2, 3).iso8601 # => "2001-02-03" - def iso8601 - if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil - y = @year - str = if y >= 0 && y <= 9999 - "#{FOUR_DIGIT[y]}-#{TWO_DIGIT[@month]}-#{TWO_DIGIT[@day]}" - elsif y >= 0 - sprintf("%04d-%02d-%02d", y, @month, @day) - else - sprintf("%05d-%02d-%02d", y, @month, @day) - end - str.force_encoding(Encoding::US_ASCII) - else - strftime('%Y-%m-%d') - end + # Date.new(2001, 2, 3).year # => 2001 + # (Date.new(1, 1, 1) - 1).year # => 0 + # + def year + _civil unless @year + @year end - alias_method :xmlschema, :iso8601 # call-seq: - # rfc3339 -> string + # mon -> integer # - # Equivalent to #strftime with argument '%FT%T%:z'; - # see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: + # Returns the month in range (1..12): # - # Date.new(2001, 2, 3).rfc3339 # => "2001-02-03T00:00:00+00:00" - def rfc3339 - if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil - y = @year - str = if y >= 0 && y <= 9999 - "#{FOUR_DIGIT[y]}-#{TWO_DIGIT[@month]}-#{TWO_DIGIT[@day]}T00:00:00+00:00" - elsif y >= 0 - sprintf("%04d-%02d-%02dT00:00:00+00:00", y, @month, @day) - else - sprintf("%05d-%02d-%02dT00:00:00+00:00", y, @month, @day) - end - str.force_encoding(Encoding::US_ASCII) - else - strftime('%Y-%m-%dT%H:%M:%S%:z') - end + # Date.new(2001, 2, 3).mon # => 2 + # + def month + _civil unless @year + @month end + alias mon month # call-seq: - # rfc2822 -> string + # mday -> integer # - # Equivalent to #strftime with argument '%a, %-d %b %Y %T %z'; - # see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: + # Returns the day of the month in range (1..31): # - # Date.new(2001, 2, 3).rfc2822 # => "Sat, 3 Feb 2001 00:00:00 +0000" - def rfc2822 - if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil && @has_jd - y = @year - wday = (@jd + 1) % 7 - y_str = if y >= 0 && y <= 9999 - FOUR_DIGIT[y] - elsif y >= 0 - sprintf("%04d", y) - else - sprintf("%05d", y) - end - str = "#{ABBR_DAYNAMES[wday]}, #{@day} #{ABBR_MONTHNAMES[@month]} #{y_str} 00:00:00 +0000" - str.force_encoding(Encoding::US_ASCII) - else - strftime('%a, %-d %b %Y %T %z') - end + # Date.new(2001, 2, 3).mday # => 3 + # + def day + _civil unless @year + @day end - alias_method :rfc822, :rfc2822 + alias mday day # call-seq: - # httpdate -> string - # - # Equivalent to #strftime with argument '%a, %d %b %Y %T GMT'; - # see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: + # d.jd -> integer # - # Date.new(2001, 2, 3).httpdate # => "Sat, 03 Feb 2001 00:00:00 GMT" + # Returns the Julian day number. This is a whole number, which is + # adjusted by the offset as the local time. # - def httpdate - if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil - get_s_jd - y = @year - wday = (@jd + 1) % 7 - y_str = if y >= 0 && y <= 9999 - FOUR_DIGIT[y] - elsif y >= 0 - sprintf("%04d", y) - else - sprintf("%05d", y) - end - str = "#{ABBR_DAYNAMES[wday]}, #{TWO_DIGIT[@day]} #{ABBR_MONTHNAMES[@month]} #{y_str} 00:00:00 GMT" - str.force_encoding(Encoding::US_ASCII) - else - strftime('%a, %d %b %Y %T GMT') - end + # DateTime.new(2001,2,3,4,5,6,'+7').jd #=> 2451944 + # DateTime.new(2001,2,3,4,5,6,'-7').jd #=> 2451944 + def jd + @jd end # call-seq: - # jisx0301 -> string + # start -> float # - # Returns a string representation of the date in +self+ - # in JIS X 0301 format. + # Returns the Julian start date for calendar reform; + # if not an infinity, the returned value is suitable + # for passing to Date#jd: # - # Date.new(2001, 2, 3).jisx0301 # => "H13.02.03" + # d = Date.new(2001, 2, 3, Date::ITALY) + # s = d.start # => 2299161.0 + # Date.jd(s).to_s # => "1582-10-15" # - def jisx0301 - if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil - get_s_jd - jd = @jd - y = @year - mm = TWO_DIGIT[@month] - dd = TWO_DIGIT[@day] - str = if !jd.is_a?(Integer) || jd < 2405160 - # Pre-Meiji or non-integer JD: ISO format - if y >= 0 && y <= 9999 - "#{FOUR_DIGIT[y]}-#{mm}-#{dd}" - elsif y >= 0 - sprintf("%04d-%02d-%02d", y, @month, @day) - else - sprintf("%05d-%02d-%02d", y, @month, @day) - end - elsif jd < 2419614 - ey = y - 1867 - "M#{ey < 100 ? TWO_DIGIT[ey] : sprintf('%02d', ey)}.#{mm}.#{dd}" - elsif jd < 2424875 - ey = y - 1911 - "T#{ey < 100 ? TWO_DIGIT[ey] : sprintf('%02d', ey)}.#{mm}.#{dd}" - elsif jd < 2447535 - ey = y - 1925 - "S#{ey < 100 ? TWO_DIGIT[ey] : sprintf('%02d', ey)}.#{mm}.#{dd}" - elsif jd < 2458605 - ey = y - 1988 - "H#{ey < 100 ? TWO_DIGIT[ey] : sprintf('%02d', ey)}.#{mm}.#{dd}" - else - ey = y - 2018 - "R#{ey < 100 ? TWO_DIGIT[ey] : sprintf('%02d', ey)}.#{mm}.#{dd}" - end - str.force_encoding(Encoding::US_ASCII) - else - jd = m_real_local_jd - y = m_real_year - fmt = jisx0301_date_format(jd, y) - strftime(fmt) - end - end - - def to_s - s = sprintf("%04d-%02d-%02d", year, month, day) - s.force_encoding(Encoding::US_ASCII) + # d = Date.new(2001, 2, 3, Date::ENGLAND) + # s = d.start # => 2361222.0 + # Date.jd(s).to_s # => "1752-09-14" + # + # Date.new(2001, 2, 3, Date::GREGORIAN).start # => -Infinity + # Date.new(2001, 2, 3, Date::JULIAN).start # => Infinity + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # + def start + @sg end # call-seq: - # inspect -> string + # d.ajd -> rational # - # Returns a string representation of +self+: + # Returns the astronomical Julian day number. This is a fractional + # number, which is not adjusted by the offset. # - # Date.new(2001, 2, 3).inspect - # # => "#" - def inspect - s = if simple_dat_p? - inspect_raw - else - # In the case of complex, time information is also displayed. - strftime("%Y-%m-%d %H:%M:%S") - end - s.force_encoding(Encoding::US_ASCII) if s.ascii_only? - s - end - - # override - def freeze - # Force lazy computation before freezing so Ractor-shared objects work. - if simple_dat_p? - get_s_jd - get_s_civil - canonicalize_s_jd - else - get_c_jd - get_c_civil - get_c_df - get_c_time - canonicalize_c_jd - end - super - end - - private - - def inspect_raw - # If @sg is infinity - if @sg.infinite? - if @sg < 0 - return "#" - else - return "#" - end - end - - date_str = strftime("%Y-%m-%d") - jd_val = @jd || 0 - sg_val = @sg.infinite? ? (@sg < 0 ? "Inf" : "-Inf") : @sg.to_i - - "#" - end - - def valid_civil?(y, m, d) - return false if m < 1 || m > 12 - - last = last_day_of_month(y, m) - d >= 1 && d <= last - end - - def last_day_of_month(y, m) - last_day_of_month_gregorian(y, m) - end - - def civil_to_jd(y, m, d, sg) - self.class.send(:gregorian_civil_to_jd, y, m, d) - end - - def jd_to_civil(jd, sg) - decode_jd(jd) - self.class.send(:c_jd_to_civil, jd, sg) - end - - def extract_fraction(value) - self.class.send(:extract_fraction, value) - end - - def decode_year(year, style) - self.class.send(:decode_year, year, style) - end - - def valid_gregorian?(y, m, d) - return false if m < 1 || m > 12 - - # Handling negative months and days - m = m + 13 if m < 0 - return false if m < 1 || m > 12 - - last_day = last_day_of_month_gregorian(y, m) - d = last_day + d + 1 if d < 0 - - d >= 1 && d <= last_day - end - - def add_with_fraction(n) - int_part = n.floor - frac_part = n - int_part - - result = add_days(int_part) - - result = result.send(:add_fraction, frac_part) if frac_part.nonzero? - - result - end - - def add_days(days) - new_jd = @jd + days - new_nth = @nth - - while new_jd < 0 - new_nth -= 1 - new_jd += CM_PERIOD - end - - while new_jd >= CM_PERIOD - new_nth += 1 - new_jd -= CM_PERIOD - end - - obj = self.class.allocate - obj.instance_variable_set(:@nth, new_nth) - obj.instance_variable_set(:@jd, new_jd) - obj.instance_variable_set(:@sg, @sg) - obj.instance_variable_set(:@flags, HAVE_JD) - obj.instance_variable_set(:@year, nil) - obj.instance_variable_set(:@month, nil) - obj.instance_variable_set(:@day, nil) - - obj - end - - def add_fraction(frac) - # In the C implementation, Date.jd(2451944.5) becomes 2451945, - # so if there is a decimal point, it will be rounded up by one day. - if frac > 0 - add_days(1) - else - self - end - end - - def last_day_of_month_gregorian(y, m) - self.class.send(:last_day_of_month_gregorian, y, m) - end - - def last_day_of_month_julian(y, m) - self.class.send(:last_day_of_month_julian, y, m) - end - - def valid_civil_date?(year, month, day, sg) - self.class.send(:valid_civil_date?, year, month, day, sg) - end - - protected - - def _init_with_jd(nth, jd, df, sf, of, start) - @nth = nth - @jd = jd - @sg = start - @df = df - @sf = sf - @of = of - @year = nil - @month = nil - @day = nil - @has_jd = true - @has_civil = false - end - - def _init_simple_with_jd(jd, start) - @nth = 0 - @jd = jd - @sg = start - @has_jd = true - end - - def _init_simple_with_civil(year, month, day, start) - @nth = 0 - @sg = start - @year = year - @month = month - @day = day - @has_civil = true - end - - private - - def canonicalize_jd(nth, jd) - if jd < 0 - nth = nth - 1 - jd += CM_PERIOD - end - if jd >= CM_PERIOD - nth = nth + 1 - jd -= CM_PERIOD - end - - [nth, jd] - end - - # If any of @df, @sf, or @of is not nil, it is considered complex. - def simple_dat_p? - @df.nil? && @sf.nil? && @of.nil? - end - - def complex_dat_p? - !simple_dat_p? - end - - def m_gregorian_p? - !m_julian_p? - end - - def m_julian_p? - # Divide the processing into simple and complex. - if simple_dat_p? - get_s_jd - jd = @jd - sg = s_virtual_sg - else - get_c_jd - jd = @jd - sg = c_virtual_sg - end - - return sg == JULIAN if sg.infinite? - - jd < sg - end - - def m_year - simple_dat_p? ? get_s_civil : get_c_civil - - @year + # DateTime.new(2001,2,3,4,5,6,'+7').ajd #=> (11769328217/4800) + # DateTime.new(2001,2,2,14,5,6,'-7').ajd #=> (11769328217/4800) + def ajd + r = Rational(@jd * 2 - 1, 2) + @df ? r + @df : r end - def m_virtual_sg - simple_dat_p? ? s_virtual_sg : c_virtual_sg + # call-seq: + # d.amjd -> rational + # + # Returns the astronomical modified Julian day number. This is + # a fractional number, which is not adjusted by the offset. + # + # DateTime.new(2001,2,3,4,5,6,'+7').amjd #=> (249325817/4800) + # DateTime.new(2001,2,2,14,5,6,'-7').amjd #=> (249325817/4800) + def amjd + ajd - Rational(4800001, 2) end - def get_s_jd - # For simple data, if JD has not yet been calculated. - return if @has_jd - - return unless simple_dat_p? - - return unless @has_civil - - # Calculate JD from civil. - jd, _ = self.class.send(:c_civil_to_jd, @year, @month, @day, s_virtual_sg) - @jd = jd - @has_jd = true + # call-seq: + # d.mjd -> integer + # + # Returns the modified Julian day number. This is a whole number, + # which is adjusted by the offset as the local time. + # + # DateTime.new(2001,2,3,4,5,6,'+7').mjd #=> 51943 + # DateTime.new(2001,2,3,4,5,6,'-7').mjd #=> 51943 + def mjd + @jd - 2400001 end - def get_s_civil - # For simple data, if civil has not yet been calculated. - return if @has_civil - - # If not simple or there is no JD, do nothing. - return unless simple_dat_p? - return unless @has_jd - - # Calculate civil from JD. - y, m, d = self.class.send(:c_jd_to_civil, @jd, s_virtual_sg) - @year = y - @month = m - @day = d - @has_civil = true + # call-seq: + # ld -> integer + # + # Returns the + # {Lilian day number}[https://en.wikipedia.org/wiki/Lilian_date], + # which is the number of days since the beginning of the Gregorian + # calendar, October 15, 1582. + # + # Date.new(2001, 2, 3).ld # => 152784 + # + def ld + @jd - 2299160 end - def get_c_jd - # For complex data, if JD has not yet been calculated. - return if @has_jd - - # Make sure you have civil data. - raise "No civil data" unless @has_civil - - # Calculate JD from civil. - jd, _ = self.class.send(:c_civil_to_jd, @year, @month, @day, c_virtual_sg) - - # Consider time data. - get_c_time - - # Convert from local to UTC. - @jd = jd_local_to_utc(jd, time_to_df(@hour || 0, @min || 0, @sec || 0), @of || 0) - @has_jd = true + # call-seq: + # yday -> integer + # + # Returns the day of the year, in range (1..366): + # + # Date.new(2001, 2, 3).yday # => 34 + # + def yday + return @yday if @yday + _civil unless @year + # inline civil_to_jd(@year, 1, 1, @sg): month=1 (<= 2 so y-=1), day=1 + yy = @year - 1 + gjd_base = (1461 * (yy + 4716)) / 4 + 429 # GJD_MONTH_OFFSET[1](=428) + 1 + a = yy / 100 + gjd = gjd_base - 1524 + 2 - a + a / 4 + jd_jan1 = gjd >= @sg ? gjd : gjd_base - 1524 + val = @jd - jd_jan1 + 1 + @yday = val unless frozen? + val end - def get_c_civil - # For complex data, if civil has not yet been calculated. - return if @has_civil - - # Make sure you have a JD. - raise "No JD data" unless @has_jd - - get_c_df - - # Convert UTC to local. - jd = jd_utc_to_local(@jd, @df || 0, @of || 0) - - # Calculate civil from JD. - y, m, d = self.class.send(:c_jd_to_civil, jd, c_virtual_sg) - @year = y - @month = m - @day = d - @has_civil = true + # call-seq: + # wday -> integer + # + # Returns the day of week in range (0..6); Sunday is 0: + # + # Date.new(2001, 2, 3).wday # => 6 + # + def wday + (@jd + 1) % 7 end - def get_c_df - # If df (day fraction) has not yet been calculated. - return if @df - - # Check that time data is available. - raise "No time data" if @hour.nil? && @min.nil? && @sec.nil? - - # Convert time to df - @df = df_local_to_utc(time_to_df(@hour, @min, @sec), @of || 0) + # call-seq: + # cwday -> integer + # + # Returns the commercial-date weekday index for +self+ + # (see Date.commercial); + # 1 is Monday: + # + # Date.new(2001, 2, 3).cwday # => 6 + # + def cwday + w = wday + w == 0 ? 7 : w end - def get_c_time - # If the time data has not yet been calculated. - return unless @hour.nil? - - # Make sure df exists. - raise "No df data" if @df.nil? - - # Convert df to time. - r = df_utc_to_local(@df, @of || 0) - - @hour, @min, @sec = df_to_time(r) + # call-seq: + # cweek -> integer + # + # Returns commercial-date week index for +self+ + # (see Date.commercial): + # + # Date.new(2001, 2, 3).cweek # => 5 + # + def cweek + @cweek || _compute_commercial[1] end - # For SimpleDateData (effectively a common implementation) - def s_virtual_sg - return @sg if @sg.infinite? - return @sg if self.class.send(:f_zero_p?, @nth) - - @nth < 0 ? JULIAN : GREGORIAN + # call-seq: + # cwyear -> integer + # + # Returns commercial-date year for +self+ + # (see Date.commercial): + # + # Date.new(2001, 2, 3).cwyear # => 2001 + # Date.new(2000, 1, 1).cwyear # => 1999 + # + def cwyear + @cwyear || _compute_commercial[0] end - # For ComplexDateData (effectively a common implementation) - def c_virtual_sg - return @sg if @sg.infinite? - return @sg if self.class.send(:f_zero_p?, @nth) - - @nth < 0 ? JULIAN : GREGORIAN + # call-seq: + # day_fraction -> rational + # + # Returns the fractional part of the day in range (Rational(0, 1)...Rational(1, 1)): + # + # DateTime.new(2001,2,3,12).day_fraction # => (1/2) + # + def day_fraction + @df || Rational(0) end - def jd_local_to_utc(jd, df, of) - df -= of - if df < 0 - jd -= 1 - elsif df >= DAY_IN_SECONDS - jd += 1 + # call-seq: + # leap? -> true or false + # + # Returns +true+ if the year is a leap year, +false+ otherwise: + # + # Date.new(2000).leap? # => true + # Date.new(2001).leap? # => false + # + def leap? + _civil unless @year + if @jd < @sg # julian? + @year % 4 == 0 + else + (@year % 4 == 0 && @year % 100 != 0) || @year % 400 == 0 end - - jd end - def jd_utc_to_local(jd, df, of) - df += of - if df < 0 - jd -= 1 - elsif df >= DAY_IN_SECONDS - jd += 1 - end - - jd + # call-seq: + # gregorian? -> true or false + # + # Returns +true+ if the date is on or after + # the date of calendar reform, +false+ otherwise: + # + # Date.new(1582, 10, 15).gregorian? # => true + # (Date.new(1582, 10, 15) - 1).gregorian? # => false + # + def gregorian? + jd >= @sg end - def df_local_to_utc(df, of) - df -= of - if df < 0 - df += DAY_IN_SECONDS - elsif df >= DAY_IN_SECONDS - df -= DAY_IN_SECONDS - end - - df + # call-seq: + # d.julian? -> true or false + # + # Returns +true+ if the date is before the date of calendar reform, + # +false+ otherwise: + # + # (Date.new(1582, 10, 15) - 1).julian? # => true + # Date.new(1582, 10, 15).julian? # => false + # + def julian? + !gregorian? end - def df_utc_to_local(df, of) - df += of - if df < 0 - df += DAY_IN_SECONDS - elsif df >= DAY_IN_SECONDS - df -= DAY_IN_SECONDS - end - - df + # call-seq: + # new_start(start = Date::ITALY]) -> new_date + # + # Returns a copy of +self+ with the given +start+ value: + # + # d0 = Date.new(2000, 2, 3) + # d0.julian? # => false + # d1 = d0.new_start(Date::JULIAN) + # d1.julian? # => true + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # + def new_start(start = DEFAULT_SG) + obj = self.class.allocate + obj.instance_variable_set(:@jd, @jd) + obj.instance_variable_set(:@sg, start) + obj end - def time_to_df(h, min, s) - h * HOUR_IN_SECONDS + min * MINUTE_IN_SECONDS + s + # call-seq: + # gregorian -> new_date + # + # Equivalent to Date#new_start with argument Date::GREGORIAN. + def gregorian + new_start(GREGORIAN) end - def df_to_time(df) - h = df / HOUR_IN_SECONDS - df %= HOUR_IN_SECONDS - min = df / MINUTE_IN_SECONDS - s = df % MINUTE_IN_SECONDS - - [h, min, s] + # call-seq: + # italy -> new_date + # + # Equivalent to Date#new_start with argument Date::ITALY. + # + def italy + new_start(ITALY) end - def minus_dd(other) - n = m_nth - other.send(:m_nth) - d = m_jd - other.send(:m_jd) - df = m_df - other.send(:m_df) - sf = m_sf - other.send(:m_sf) - - n, d = canonicalize_jd(n, d) - - # Canonicalize df - if df < 0 - d -= 1 - df += DAY_IN_SECONDS - elsif df >= DAY_IN_SECONDS - d += 1 - df -= DAY_IN_SECONDS - end - - # Canonicalize sf - if sf < 0 - df -= 1 - sf += SECOND_IN_NANOSECONDS - elsif sf >= SECOND_IN_NANOSECONDS - df += 1 - sf -= SECOND_IN_NANOSECONDS - end - - r = n.zero? ? 0 : n * CM_PERIOD - r = r + Rational(d, 1) if d.nonzero? - r = r + isec_to_day(df) if df.nonzero? - r = r + ns_to_day(sf) if sf.nonzero? - - r.is_a?(Rational) ? r : Rational(r, 1) + # call-seq: + # england -> new_date + # + # Equivalent to Date#new_start with argument Date::ENGLAND. + def england + new_start(ENGLAND) end - def m_jd - simple_dat_p? ? get_s_jd : get_c_jd - - @jd + # call-seq: + # julian -> new_date + # + # Equivalent to Date#new_start with argument Date::JULIAN. + def julian + new_start(JULIAN) end - def m_df - if simple_dat_p? - 0 - else - get_c_df - @df || 0 - end + # call-seq: + # sunday? -> true or false + # + # Returns +true+ if +self+ is a Sunday, +false+ otherwise. + def sunday? + wday == 0 end - - def m_sf - simple_dat_p? ? 0 : @sf || 0 + # call-seq: + # monday? -> true or false + # + # Returns +true+ if +self+ is a Monday, +false+ otherwise. + def monday? + wday == 1 end - - def m_of - if simple_dat_p? - 0 - else - get_c_jd - @of || 0 - end + # call-seq: + # tuesday? -> true or false + # + # Returns +true+ if +self+ is a Tuesday, +false+ otherwise. + def tuesday? + wday == 2 end - - def m_real_year - return @year if @nth == 0 && @has_civil - - nth = @nth - year = m_year - - return year if self.class.send(:f_zero_p?, nth) - - encode_year(nth, year, gregorian? ? -1 : 1) + # call-seq: + # wednesday? -> true or false + # + # Returns +true+ if +self+ is a Wednesday, +false+ otherwise. + def wednesday? + wday == 3 end - - def m_mon - return @month if @has_civil - - simple_dat_p? ? get_s_civil : get_c_civil - @month + # call-seq: + # thursday? -> true or false + # + # Returns +true+ if +self+ is a Thursday, +false+ otherwise. + def thursday? + wday == 4 end - - def m_mday - return @day if @has_civil - - simple_dat_p? ? get_s_civil : get_c_civil - @day + # call-seq: + # friday? -> true or false + # + # Returns +true+ if +self+ is a Friday, +false+ otherwise. + def friday? + wday == 5 end - - def m_sg - get_c_jd unless simple_dat_p? - - @sg + # call-seq: + # saturday? -> true or false + # + # Returns +true+ if +self+ is a Saturday, +false+ otherwise. + def saturday? + wday == 6 end - def encode_year(nth, y, style) - period = (style < 0) ? CM_PERIOD_GCY : CM_PERIOD_JCY - - self.class.send(:f_zero_p?, nth) ? y : period * nth + y + # :nodoc: + def nth_kday?(n, k) + return false if k != wday + jd_ref = self.class.__send__(:nth_kday_to_jd, year, month, n, k, @sg) + jd_ref == @jd end - def m_real_local_jd - nth = m_nth - jd = m_local_jd + # --------------------------------------------------------------------------- + # Comparison + # --------------------------------------------------------------------------- - self.class.send(:encode_jd, nth, jd) - end - - def m_local_jd - if simple_dat_p? - get_s_jd - @jd + # call-seq: + # self <=> other -> -1, 0, 1 or nil + # + # Compares +self+ and +other+, returning: + # + # - -1 if +other+ is larger. + # - 0 if the two are equal. + # - 1 if +other+ is smaller. + # - +nil+ if the two are incomparable. + # + # Argument +other+ may be: + # + # - Another \Date object: + # + # d = Date.new(2022, 7, 27) # => # + # prev_date = d.prev_day # => # + # next_date = d.next_day # => # + # d <=> next_date # => -1 + # d <=> d # => 0 + # d <=> prev_date # => 1 + # + # - A DateTime object: + # + # d <=> DateTime.new(2022, 7, 26) # => 1 + # d <=> DateTime.new(2022, 7, 27) # => 0 + # d <=> DateTime.new(2022, 7, 28) # => -1 + # + # - A numeric (compares self.ajd to +other+): + # + # d <=> 2459788 # => -1 + # d <=> 2459787 # => 1 + # d <=> 2459786 # => 1 + # d <=> d.ajd # => 0 + # + # - Any other object: + # + # d <=> Object.new # => nil + # + def <=>(other) + case other + when Date + d = @jd <=> other.jd + d != 0 ? d : day_fraction <=> other.day_fraction + when Numeric + ajd <=> other else - get_c_jd - get_c_df - local_jd + nil end end - def local_jd - jd = @jd - df = @df || 0 - of = @of || 0 - - df += of - if df < 0 - jd -= 1 - elsif df >= DAY_IN_SECONDS - jd += 1 + def <(other) + case other + when Date + d = @jd <=> other.jd + d != 0 ? d < 0 : day_fraction < other.day_fraction + when Numeric + r = ajd <=> other + raise ArgumentError, "comparison of #{self.class} with #{other.class} failed" if r.nil? + r < 0 + else + raise ArgumentError, "comparison of #{self.class} with #{other.class} failed" end - - jd - end - - def m_nth - # For complex, get civil data and then return nth. - get_c_civil unless simple_dat_p? - - @nth end - def equal_gen(other) - if other.is_a?(Numeric) - m_real_local_jd == other - elsif other.is_a?(Date) - m_real_local_jd == other.send(:m_real_local_jd) + def >(other) + case other + when Date + d = @jd <=> other.jd + d != 0 ? d > 0 : day_fraction > other.day_fraction + when Numeric + r = ajd <=> other + raise ArgumentError, "comparison of #{self.class} with #{other.class} failed" if r.nil? + r > 0 else - begin - coerced = other.coerce(self) - coerced[0] == coerced[1] - rescue - false - end + raise ArgumentError, "comparison of #{self.class} with #{other.class} failed" end end - def m_canonicalize_jd - if simple_dat_p? - get_s_jd - canonicalize_s_jd + def ==(other) + case other + when Date + @jd == other.jd && day_fraction == other.day_fraction + when Numeric + ajd == other else - get_c_jd - canonicalize_c_jd + false end end - # Simple - def canonicalize_s_jd - return if frozen? - - j = @jd - - @nth, @jd = canonicalize_jd(@nth, @jd) - - # Invalidate civil data if JD changes. - @has_civil = false if @jd != j + def eql?(other) + other.is_a?(Date) && @jd == other.jd && day_fraction == other.day_fraction end - # Complex - def canonicalize_c_jd - return if frozen? - - j = @jd - - @nth, @jd = canonicalize_jd(@nth, @jd) - - # Invalidate civil data if JD changes. - @has_civil = false if @jd != j + def hash + [@jd, @sg].hash end - def f_jd(other) - # Get JD from another Date object. - other.send(:m_real_local_jd) + # call-seq: + # self === other -> true, false, or nil. + # + # Returns +true+ if +self+ and +other+ represent the same date, + # +false+ if not, +nil+ if the two are not comparable. + # + # Argument +other+ may be: + # + # - Another \Date object: + # + # d = Date.new(2022, 7, 27) # => # + # prev_date = d.prev_day # => # + # next_date = d.next_day # => # + # d === prev_date # => false + # d === d # => true + # d === next_date # => false + # + # - A DateTime object: + # + # d === DateTime.new(2022, 7, 26) # => false + # d === DateTime.new(2022, 7, 27) # => true + # d === DateTime.new(2022, 7, 28) # => false + # + # - A numeric (compares self.jd to +other+): + # + # d === 2459788 # => true + # d === 2459787 # => false + # d === 2459786 # => false + # d === d.jd # => true + # + # - An object not comparable: + # + # d === Object.new # => nil + # + def ===(other) + case other + when Numeric + jd == other.to_i + when Date + jd == other.jd + else + nil + end end - def dup_obj_with_new_start(sg) - if @df.nil? && @sf.nil? && @of.nil? - # Fast path for simple Date (no time/offset components). - # Absolute hot path: nth==0 (common Gregorian date) with JD already cached. - if @nth == 0 && @has_jd - new_obj = self.class.send(:allocate) - new_obj.instance_variable_set(:@nth, 0) - new_obj.instance_variable_set(:@jd, @jd) - new_obj.instance_variable_set(:@sg, sg) - new_obj.instance_variable_set(:@df, nil) - new_obj.instance_variable_set(:@sf, nil) - new_obj.instance_variable_set(:@of, nil) - new_obj.instance_variable_set(:@year, nil) - new_obj.instance_variable_set(:@month, nil) - new_obj.instance_variable_set(:@day, nil) - new_obj.instance_variable_set(:@has_jd, true) - new_obj.instance_variable_set(:@has_civil, false) - return new_obj - end - # General simple path: inline get_s_jd and canon(@nth). - unless @has_jd - if @has_civil - jd, _ = self.class.send(:c_civil_to_jd, @year, @month, @day, s_virtual_sg) - @jd = jd - @has_jd = true - end + # --------------------------------------------------------------------------- + # Arithmetic + # --------------------------------------------------------------------------- + + # call-seq: + # d + other -> date + # + # Returns a date object pointing +other+ days after self. The other + # should be a numeric value. If the other is a fractional number, + # assumes its precision is at most nanosecond. + # + # Date.new(2001,2,3) + 1 #=> # + # DateTime.new(2001,2,3) + Rational(1,2) + # #=> # + # DateTime.new(2001,2,3) + Rational(-1,2) + # #=> # + # DateTime.jd(0,12) + DateTime.new(2001,2,3).ajd + # #=> # + def +(other) + case other + when Integer + if instance_of?(Date) + obj = Date.allocate + obj.instance_variable_set(:@jd, @jd + other) + obj.instance_variable_set(:@sg, @sg) + obj + else + self.class.__send__(:_new_from_jd, @jd + other, @sg, @df) end - nth = @nth - nth = nth.numerator if nth.is_a?(Rational) && nth.denominator == 1 - new_obj = self.class.send(:allocate) - new_obj.instance_variable_set(:@nth, nth) - new_obj.instance_variable_set(:@jd, @jd) - new_obj.instance_variable_set(:@sg, sg) - new_obj.instance_variable_set(:@df, nil) - new_obj.instance_variable_set(:@sf, nil) - new_obj.instance_variable_set(:@of, nil) - new_obj.instance_variable_set(:@year, nil) - new_obj.instance_variable_set(:@month, nil) - new_obj.instance_variable_set(:@day, nil) - new_obj.instance_variable_set(:@has_jd, @has_jd) - new_obj.instance_variable_set(:@has_civil, false) - new_obj + when Numeric + r = other.to_r + raise TypeError, "#{other.class} can't be coerced into Integer" unless r.is_a?(Rational) + total = r + (@df || 0) + days = total.floor + frac = total - days + self.class.__send__(:_new_from_jd, @jd + days, @sg, frac == 0 ? nil : frac) else - dup = dup_obj - dup.send(:set_sg, sg) - dup + raise TypeError, "expected numeric" end end - def dup_obj - if simple_dat_p? - # Simple data replication: allocate directly, avoid d_lite_s_alloc_simple overhead - new_obj = self.class.send(:allocate) - - new_obj.instance_variable_set(:@nth, canon(@nth)) - new_obj.instance_variable_set(:@jd, @jd) - new_obj.instance_variable_set(:@sg, @sg) - new_obj.instance_variable_set(:@df, nil) - new_obj.instance_variable_set(:@sf, nil) - new_obj.instance_variable_set(:@of, nil) - new_obj.instance_variable_set(:@year, @year) - new_obj.instance_variable_set(:@month, @month) - new_obj.instance_variable_set(:@day, @day) - new_obj.instance_variable_set(:@has_jd, @has_jd) - new_obj.instance_variable_set(:@has_civil, @has_civil) + # call-seq: + # d - other -> date or rational + # + # If the other is a date object, returns a Rational + # whose value is the difference between the two dates in days. + # If the other is a numeric value, returns a date object + # pointing +other+ days before self. + # If the other is a fractional number, + # assumes its precision is at most nanosecond. + # + # Date.new(2001,2,3) - 1 #=> # + # DateTime.new(2001,2,3) - Rational(1,2) + # #=> # + # Date.new(2001,2,3) - Date.new(2001) + # #=> (33/1) + # DateTime.new(2001,2,3) - DateTime.new(2001,2,2,12) + # #=> (1/2) + def -(other) + case other + when Date + Rational(@jd - other.jd) + (@df || 0) - other.day_fraction + when Integer + if instance_of?(Date) + obj = Date.allocate + obj.instance_variable_set(:@jd, @jd - other) + obj.instance_variable_set(:@sg, @sg) + obj + else + self.class.__send__(:_new_from_jd, @jd - other, @sg, @df) + end + when Numeric + r = other.to_r + raise TypeError, "#{other.class} can't be coerced into Integer" unless r.is_a?(Rational) + total = (@df || 0) - r + days = total.floor + frac = total - days + self.class.__send__(:_new_from_jd, @jd + days, @sg, frac == 0 ? nil : frac) + else + raise TypeError, "expected numeric" + end + end - new_obj + # call-seq: + # d >> n -> new_date + # + # Returns a new \Date object representing the date + # +n+ months later; +n+ should be a numeric: + # + # (Date.new(2001, 2, 3) >> 1).to_s # => "2001-03-03" + # (Date.new(2001, 2, 3) >> -2).to_s # => "2000-12-03" + # + # When the same day does not exist for the new month, + # the last day of that month is used instead: + # + # (Date.new(2001, 1, 31) >> 1).to_s # => "2001-02-28" + # (Date.new(2001, 1, 31) >> -4).to_s # => "2000-09-30" + # + # This results in the following, possibly unexpected, behaviors: + # + # d0 = Date.new(2001, 1, 31) + # d1 = d0 >> 1 # => # + # d2 = d1 >> 1 # => # + # + # d0 = Date.new(2001, 1, 31) + # d1 = d0 >> 1 # => # + # d2 = d1 >> -1 # => # + # + def >>(n) + _civil unless @year + m2 = @month + n.to_i + y2 = @year + (m2 - 1).div(12) + m2 = (m2 - 1) % 12 + 1 + # inline days_in_month + if m2 == 2 + if @sg == Float::INFINITY + dim = y2 % 4 == 0 ? 29 : 28 + else + dim = ((y2 % 4 == 0 && y2 % 100 != 0) || y2 % 400 == 0) ? 29 : 28 + end else - # Complex data replication - new_obj = self.class.send(:d_lite_s_alloc_complex) + dim = DAYS_IN_MONTH_GREGORIAN[m2] + end + d2 = @day < dim ? @day : dim + # inline civil_to_jd(y2, m2, d2, @sg) + offset = GJD_MONTH_OFFSET[m2] + yy = m2 <= 2 ? y2 - 1 : y2 + gjd_base = (1461 * (yy + 4716)) / 4 + offset + d2 + a = yy / 100 + gjd = gjd_base - 1524 + 2 - a + a / 4 + jd2 = gjd >= @sg ? gjd : gjd_base - 1524 + # inline _new_from_jd + obj = self.class.allocate + obj.instance_variable_set(:@jd, jd2) + obj.instance_variable_set(:@sg, @sg) + obj + end - new_obj.instance_variable_set(:@nth, canon(@nth)) - new_obj.instance_variable_set(:@jd, @jd) - new_obj.instance_variable_set(:@sg, @sg) - new_obj.instance_variable_set(:@year, @year) - new_obj.instance_variable_set(:@month, @month) - new_obj.instance_variable_set(:@day, @day) - new_obj.instance_variable_set(:@hour, @hour) - new_obj.instance_variable_set(:@min, @min) - new_obj.instance_variable_set(:@sec, @sec) - new_obj.instance_variable_set(:@df, @df) - new_obj.instance_variable_set(:@sf, canon(@sf)) - new_obj.instance_variable_set(:@of, @of) - new_obj.instance_variable_set(:@has_jd, @has_jd) - new_obj.instance_variable_set(:@has_civil, @has_civil) + # call-seq: + # d << n -> date + # + # Returns a new \Date object representing the date + # +n+ months earlier; +n+ should be a numeric: + # + # (Date.new(2001, 2, 3) << 1).to_s # => "2001-01-03" + # (Date.new(2001, 2, 3) << -2).to_s # => "2001-04-03" + # + # When the same day does not exist for the new month, + # the last day of that month is used instead: + # + # (Date.new(2001, 3, 31) << 1).to_s # => "2001-02-28" + # (Date.new(2001, 3, 31) << -6).to_s # => "2001-09-30" + # + # This results in the following, possibly unexpected, behaviors: + # + # d0 = Date.new(2001, 3, 31) + # d0 << 2 # => # + # d0 << 1 << 1 # => # + # + # d0 = Date.new(2001, 3, 31) + # d1 = d0 << 1 # => # + # d2 = d1 << -1 # => # + # + def <<(n) + self >> -n + end - new_obj - end + # call-seq: + # next_day(n = 1) -> new_date + # + # Equivalent to Date#+ with argument +n+. + def next_day(n = 1) + self + n end - def set_sg(sg) - if simple_dat_p? - get_s_jd if @has_jd || @has_civil - else - get_c_jd - get_c_df - end + # call-seq: + # prev_day(n = 1) -> new_date + # + # Equivalent to Date#- with argument +n+. + def prev_day(n = 1) + self - n + end - clear_civil + # call-seq: + # d.next -> new_date + # + # Returns a new \Date object representing the following day: + # + # d = Date.new(2001, 2, 3) + # d.to_s # => "2001-02-03" + # d.next.to_s # => "2001-02-04" + # + def next + self + 1 + end + alias_method :succ, :next - @sg = sg + # call-seq: + # next_year(n = 1) -> new_date + # + # Equivalent to #>> with argument n * 12. + def next_year(n = 1) + self >> n * 12 end - def clear_civil - @has_civil = false - @year = nil - @month = nil - @day = nil + # call-seq: + # prev_year(n = 1) -> new_date + # + # Equivalent to #<< with argument n * 12. + def prev_year(n = 1) + self << n * 12 end - # If the argument is Rational and the denominator is 1, return the numerator. - def canon(x) - x.is_a?(Rational) && x.denominator == 1 ? x.numerator : x + # call-seq: + # next_month(n = 1) -> new_date + # + # Equivalent to #>> with argument +n+. + def next_month(n = 1) + self >> n end - def val2sg(vsg) - # Convert to Number. - sg = vsg.to_f + # call-seq: + # prev_month(n = 1) -> new_date + # + # Equivalent to #<< with argument +n+. + def prev_month(n = 1) + self << n + end - # Check for a valid start. - unless c_valid_start_p?(sg) - warn "invalid start is ignored" - sg = DEFAULT_SG + # call-seq: + # step(limit, step = 1){|date| ... } -> self + # + # Calls the block with specified dates; + # returns +self+. + # + # - The first +date+ is +self+. + # - Each successive +date+ is date + step, + # where +step+ is the numeric step size in days. + # - The last date is the last one that is before or equal to +limit+, + # which should be a \Date object. + # + # Example: + # + # limit = Date.new(2001, 12, 31) + # Date.new(2001).step(limit){|date| p date.to_s if date.mday == 31 } + # + # Output: + # + # "2001-01-31" + # "2001-03-31" + # "2001-05-31" + # "2001-07-31" + # "2001-08-31" + # "2001-10-31" + # "2001-12-31" + # + # Returns an Enumerator if no block is given. + def step(limit, step = 1) + return to_enum(:step, limit, step) unless block_given? + if Integer === step && instance_of?(Date) && limit.instance_of?(Date) + raise ArgumentError, "step can't be 0" if step == 0 + limit_jd = limit.jd + sg = @sg + if step > 0 + jd = @jd + while jd <= limit_jd + obj = Date.allocate + obj.instance_variable_set(:@jd, jd) + obj.instance_variable_set(:@sg, sg) + yield obj + jd += step + end + else + jd = @jd + while jd >= limit_jd + obj = Date.allocate + obj.instance_variable_set(:@jd, jd) + obj.instance_variable_set(:@sg, sg) + yield obj + jd += step + end + end + return self + end + d = self + cmp = step <=> 0 + raise ArgumentError, "comparison of #{step.class} with 0 failed" if cmp.nil? + if cmp > 0 + while d <= limit + yield d + d = d + step + end + elsif cmp < 0 + while d >= limit + yield d + d = d + step + end + else + raise ArgumentError, "step can't be 0" end - - sg - end - - def c_valid_start_p?(sg) - # Invalid for NaN. - return false if sg.respond_to?(:nan?) && sg.nan? - - # Valid for Infinity. - return true if sg.respond_to?(:infinite?) && sg.infinite? - - # If it is a finite value, check if it is within the range - # from REFORM_BEGIN_JD to REFORM_END_JD - return false if sg < REFORM_BEGIN_JD || sg > REFORM_END_JD - - true - end - - def m_wday - return (@jd + 1) % 7 if @has_jd && @of.nil? - - c_jd_to_wday(m_local_jd) - end - - def c_jd_to_wday(jd) - (jd + 1) % 7 + self end - def m_yday - if @has_civil && @of.nil? + # call-seq: + # upto(max){|date| ... } -> self + # + # Equivalent to #step with arguments +max+ and +1+. + def upto(max, &block) + return to_enum(:upto, max) unless block_given? + if instance_of?(Date) && max.instance_of?(Date) + jd = @jd + max_jd = max.jd sg = @sg - if (sg.is_a?(Float) && sg.infinite? && sg < 0) || - (sg.is_a?(Integer) && @has_jd && (@jd - sg) > 366) - leap = self.class.send(:c_gregorian_leap_p?, @year) - return YEARTAB[leap ? 1 : 0][@month] + @day + while jd <= max_jd + obj = Date.allocate + obj.instance_variable_set(:@jd, jd) + obj.instance_variable_set(:@sg, sg) + yield obj + jd += 1 end + return self end - - jd = m_local_jd - sg = m_virtual_sg - - # proleptic gregorian or if more than 366 days have passed since the calendar change - return c_gregorian_to_yday(m_year, m_mon, m_mday) if m_proleptic_gregorian_p? || (jd - sg) > 366 - - # proleptic Julian - return c_julian_to_yday(m_year, m_mon, m_mday) if m_proleptic_julian_p? - - # Otherwise, convert from JD to ordinal. - _, rd = self.class.send(:c_jd_to_ordinal, jd, sg) - - rd + step(max, 1, &block) end - def m_proleptic_gregorian_p? - sg = @sg - - sg.infinite? && sg < 0 + # call-seq: + # downto(min){|date| ... } -> self + # + # Equivalent to #step with arguments +min+ and -1. + def downto(min, &block) + return to_enum(:downto, min) unless block_given? + if instance_of?(Date) && min.instance_of?(Date) + jd = @jd + min_jd = min.jd + sg = @sg + while jd >= min_jd + obj = Date.allocate + obj.instance_variable_set(:@jd, jd) + obj.instance_variable_set(:@sg, sg) + yield obj + jd -= 1 + end + return self + end + step(min, -1, &block) end - def m_proleptic_julian_p? - sg = @sg + # --------------------------------------------------------------------------- + # Calendar conversion + # --------------------------------------------------------------------------- - sg.infinite? && sg > 0 + # call-seq: + # to_date -> self + # + # Returns +self+. + def to_date + self end - def c_gregorian_to_yday(year, month, day) - leap = self.class.send(:c_gregorian_leap_p?, year) - - YEARTAB[leap ? 1 : 0][month] + day + # call-seq: + # d.to_datetime -> datetime + # + # Returns a DateTime whose value is the same as +self+: + # + # Date.new(2001, 2, 3).to_datetime # => # + # + def to_datetime + DateTime.new(year, month, day, 0, 0, 0, 0, @sg) end - def c_julian_to_yday(year, month, day) - leap = self.class.send(:c_julian_leap_p?, year) + # call-seq: + # to_time -> time + # + # Returns a new Time object with the same value as +self+; + # if +self+ is a Julian date, derives its Gregorian date + # for conversion to the \Time object: + # + # Date.new(2001, 2, 3).to_time # => 2001-02-03 00:00:00 -0600 + # Date.new(2001, 2, 3, Date::JULIAN).to_time # => 2001-02-16 00:00:00 -0600 + # + def to_time + # Use Gregorian date for Time (inline jd_to_gregorian) + a = @jd + 32044 + b = (4 * a + 3) / 146097 + c = a - (146097 * b) / 4 + dd = (4 * c + 3) / 1461 + e = c - (1461 * dd) / 4 + m = (5 * e + 2) / 153 + day = e - (153 * m + 2) / 5 + 1 + month = m + 3 - 12 * (m / 10) + year = 100 * b + dd - 4800 + m / 10 + Time.local(year, month, day) + end + + # --------------------------------------------------------------------------- + # Serialization + # --------------------------------------------------------------------------- - YEARTAB[leap ? 1 : 0][month] + day + # :nodoc: + def initialize_copy(other) + @jd = other.instance_variable_get(:@jd) + @sg = other.instance_variable_get(:@sg) + @df = other.instance_variable_get(:@df) + @year = other.instance_variable_get(:@year) + @month = other.instance_variable_get(:@month) + @day = other.instance_variable_get(:@day) end - def d_trunc_with_frac(value) - if value.is_a?(Integer) - [value, 0] - elsif value.is_a?(Float) - trunc = value.truncate - frac = value - trunc - - [trunc, frac] - elsif value.is_a?(Rational) - trunc = value.truncate - frac = value - trunc - - [trunc, frac] + # :nodoc: + def marshal_dump + # 6-element format: [nth, jd, df, sf, of, sg] + # df = seconds into day (Integer), sf = sub-second fraction (Rational) + if @df + total_sec = @df * 86400 + df_int = total_sec.floor + sf = total_sec - df_int + [0, @jd, df_int, sf, 0, @sg] else - [value.to_i, 0] + [0, @jd, 0, 0, 0, @sg] end end - def m_real_jd - # C: m_real_jd uses m_jd (raw/UTC JD), NOT m_local_jd - nth = m_nth - if simple_dat_p? - get_s_jd + # :nodoc: + def marshal_load(array) + case array.length + when 2 + # Format 1.4/1.6: [jd_like, sg_or_bool] + jd_like, sg_or_bool = array + sg = sg_or_bool == true ? GREGORIAN : (sg_or_bool == false ? JULIAN : sg_or_bool.to_f) + _init_from_jd(jd_like.to_i, sg) + when 3 + # Format 1.8: [ajd, of, sg] + ajd, _of, sg = array + raw_jd = ajd + Rational(1, 2) + jd = raw_jd.floor + df = raw_jd - jd + _init_from_jd(jd, sg, df == 0 ? nil : df) + when 6 + # Current format: [nth, jd, df, sf, of, sg] + _nth, jd, df, sf, _of, sg = array + if df != 0 || sf != 0 + day_frac = (Rational(df) + sf) / 86400 + _init_from_jd(jd, sg, day_frac) + else + _init_from_jd(jd, sg) + end else - get_c_jd + raise TypeError, "invalid marshal data" end - self.class.send(:encode_jd, nth, @jd) end - def m_fr - if simple_dat_p? - 0 + # call-seq: + # deconstruct_keys(array_of_names_or_nil) -> hash + # + # Returns a hash of the name/value pairs, to use in pattern matching. + # Possible keys are: :year, :month, :day, + # :wday, :yday. + # + # Possible usages: + # + # d = Date.new(2022, 10, 5) + # + # if d in wday: 3, day: ..7 # uses deconstruct_keys underneath + # puts "first Wednesday of the month" + # end + # #=> prints "first Wednesday of the month" + # + # case d + # in year: ...2022 + # puts "too old" + # in month: ..9 + # puts "quarter 1-3" + # in wday: 1..5, month: + # puts "working day in month #{month}" + # end + # #=> prints "working day in month 10" + # + # Note that deconstruction by pattern can also be combined with class check: + # + # if d in Date(wday: 3, day: ..7) + # puts "first Wednesday of the month" + # end + # + def deconstruct_keys(keys) + if keys + if keys.size == 1 + case keys[0] + when :year + _civil unless @year + { year: @year } + when :month + _civil unless @year + { month: @month } + when :day + _civil unless @year + { day: @day } + when :wday then { wday: (@jd + 1) % 7 } + when :yday then { yday: yday } + else {} + end + else + _civil unless @year + h = {} + keys.each do |k| + case k + when :year then h[:year] = @year + when :month then h[:month] = @month + when :day then h[:day] = @day + when :wday then h[:wday] = (@jd + 1) % 7 + when :yday then h[:yday] = yday + end + end + h + end else - df = m_local_df - sf = m_sf - - fr = isec_to_day(df) - fr = fr + ns_to_day(sf) if sf.nonzero? - - fr + _civil unless @year + { year: @year, month: @month, day: @day, wday: (@jd + 1) % 7, yday: yday } end end - def m_local_df - if simple_dat_p? - 0 + # --------------------------------------------------------------------------- + # String formatting (delegated to strftime.rb) + # --------------------------------------------------------------------------- + + # call-seq: + # asctime -> string + # + # Equivalent to #strftime with argument '%a %b %e %T %Y' + # (or its {shorthand form}[rdoc-ref:language/strftime_formatting.rdoc@Shorthand+Conversion+Specifiers] + # '%c'): + # + # Date.new(2001, 2, 3).asctime # => "Sat Feb 3 00:00:00 2001" + # + # See {asctime}[https://linux.die.net/man/3/asctime]. + # + def asctime + _civil unless @year + d = @day + d_s = d < 10 ? " #{d}" : d.to_s + y = @year + y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) + w = (@jd + 1) % 7 + if instance_of?(Date) + "#{ASCTIME_DAYS[w]} #{ASCTIME_MONS[@month]} #{d_s} 00:00:00 #{y_s}".force_encoding(Encoding::US_ASCII) else - get_c_df - local_df + "#{ASCTIME_DAYS[w]} #{ASCTIME_MONS[@month]} #{d_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} #{y_s}".force_encoding(Encoding::US_ASCII) end end + alias_method :ctime, :asctime - def local_df - df_utc_to_local(@df || 0, @of || 0) - end - - def isec_to_day(s) - sec_to_day(s) + # call-seq: + # iso8601 -> string + # + # Equivalent to #strftime with argument '%Y-%m-%d' + # (or its {shorthand form}[rdoc-ref:language/strftime_formatting.rdoc@Shorthand+Conversion+Specifiers] + # '%F'); + # + # Date.new(2001, 2, 3).iso8601 # => "2001-02-03" + # + def iso8601 + to_s end + alias_method :xmlschema, :iso8601 - def sec_to_day(s) - s.is_a?(Integer) ? Rational(s, DAY_IN_SECONDS) : s.quo(DAY_IN_SECONDS) + # call-seq: + # rfc3339 -> string + # + # Equivalent to #strftime with argument '%FT%T%:z'; + # see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: + # + # Date.new(2001, 2, 3).rfc3339 # => "2001-02-03T00:00:00+00:00" + # + def rfc3339 + (to_s << 'T00:00:00+00:00').force_encoding(Encoding::US_ASCII) end - def ns_to_day(n) - if n.is_a?(Integer) - Rational(n, DAY_IN_SECONDS * SECOND_IN_NANOSECONDS) + # call-seq: + # rfc2822 -> string + # + # Equivalent to #strftime with argument '%a, %-d %b %Y %T %z'; + # see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: + # + # Date.new(2001, 2, 3).rfc2822 # => "Sat, 3 Feb 2001 00:00:00 +0000" + # + def rfc2822 + _civil unless @year + w = (@jd + 1) % 7 + y = @year + y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) + if instance_of?(Date) + "#{RFC2822_DAYS[w]}, #{@day}#{RFC_MON_SPACE[@month]}#{y_s} 00:00:00 +0000".force_encoding(Encoding::US_ASCII) else - n.quo(DAY_IN_SECONDS * SECOND_IN_NANOSECONDS) - end - end - - def m_real_cwyear - nth = m_nth - year = m_cwyear - - nth.zero? ? year : encode_year(nth, year, m_gregorian_p? ? -1 : 1) - end - - def m_cwyear - return @cwyear if @has_commercial - ry, rw, _ = self.class.send(:c_jd_to_commercial, m_local_jd, m_virtual_sg) - unless frozen? - @cwyear = ry - @cweek = rw - @has_commercial = true + "#{RFC2822_DAYS[w]}, #{@day}#{RFC_MON_SPACE[@month]}#{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} +0000".force_encoding(Encoding::US_ASCII) end - ry end + alias_method :rfc822, :rfc2822 - def m_cweek - return @cweek if @has_commercial - ry, rw, _ = self.class.send(:c_jd_to_commercial, m_local_jd, m_virtual_sg) - unless frozen? - @cwyear = ry - @cweek = rw - @has_commercial = true + # call-seq: + # httpdate -> string + # + # Equivalent to #strftime with argument '%a, %d %b %Y %T GMT'; + # see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: + # + # Date.new(2001, 2, 3).httpdate # => "Sat, 03 Feb 2001 00:00:00 GMT" + # + def httpdate + _civil unless @year + w = (@jd + 1) % 7 + y = @year + y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) + if instance_of?(Date) + "#{ASCTIME_DAYS[w]}, #{PAD2[@day]}#{RFC_MON_SPACE[@month]}#{y_s} 00:00:00 GMT".force_encoding(Encoding::US_ASCII) + else + "#{ASCTIME_DAYS[w]}, #{PAD2[@day]}#{RFC_MON_SPACE[@month]}#{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} GMT".force_encoding(Encoding::US_ASCII) end - rw - end - - def m_cwday - w = m_wday - # ISO 8601 places Sunday at 7. - w.zero? ? 7 : w end - def m_ajd - if simple_dat_p? - # For simple date: - r = m_real_jd - - # Optimization: Integer operations within Fixnum range - if r.is_a?(Integer) && r <= (2**62 - 1) / 2 && r >= (-(2**62) + 1) / 2 - ir = r * 2 - 1 - return Rational(ir, 2) - else - return Rational(r * 2 - 1, 2) - end + # call-seq: + # jisx0301 -> string + # + # Returns a string representation of the date in +self+ + # in JIS X 0301 format. + # + # Date.new(2001, 2, 3).jisx0301 # => "H13.02.03" + # + def jisx0301 + _civil unless @year + jd = @jd + m = @month + d = @day + md = "#{PAD2[m]}.#{PAD2[d]}" + if jd >= 2458605 # Reiwa (2019-05-01) + "R#{PAD2[@year - 2018]}.#{md}" + elsif jd >= 2447535 # Heisei (1989-01-08) + "H#{PAD2[@year - 1988]}.#{md}" + elsif jd >= 2424875 # Showa (1926-12-25) + "S#{PAD2[@year - 1925]}.#{md}" + elsif jd >= 2419614 # Taisho (1912-07-30) + "T#{PAD2[@year - 1911]}.#{md}" + elsif jd >= 2405160 # Meiji (1873-01-01) + "M#{PAD2[@year - 1867]}.#{md}" + else + to_s end - - # For complex date: - r = m_real_jd - df = m_df - - # Subtract half a day (12 hours) from df. - df -= HALF_DAYS_IN_SECONDS - - # If df is not zero, add. - r = r + isec_to_day(df) if df != 0 - - # If sf is not zero, add. - sf = m_sf - r = r + ns_to_day(sf) if sf != 0 - - r end - def m_amjd - r = m_real_jd - - # Optimization: Integer operations within Fixnum range - if r.is_a?(Integer) && r >= (-(2**62) + 2400001) - ir = r - 2400001 - r = Rational(ir, 1) + # call-seq: + # to_s -> string + # + # Returns a string representation of the date in +self+ + # in {ISO 8601 extended date format}[rdoc-ref:language/strftime_formatting.rdoc@ISO+8601+Format+Specifications] + # ('%Y-%m-%d'): + # + # Date.new(2001, 2, 3).to_s # => "2001-02-03" + # + def to_s + _civil + suffix = MONTH_DAY_SUFFIX[@month][@day] + y = @year + if y >= 1000 + # Fast path: 4-digit year needs no zero-padding (most common case). + (y.to_s << suffix).force_encoding(Encoding::US_ASCII) + elsif y >= 0 + (format('%04d', y) << suffix).force_encoding(Encoding::US_ASCII) else - r = Rational(m_real_jd - 2400001, 1) + (format('-%04d', -y) << suffix).force_encoding(Encoding::US_ASCII) end - - # For simple date, stop here. - return r if simple_dat_p? - - # For complex date, add df and sf. - df = m_df - r = r + isec_to_day(df) if df != 0 - - sf = m_sf - r = r + ns_to_day(sf) if sf != 0 - - r end - def m_wnumx(f) - _, rw, _ = c_jd_to_weeknum(m_local_jd, f, m_virtual_sg) - - rw + # call-seq: + # inspect -> string + # + # Returns a string representation of +self+: + # + # Date.new(2001, 2, 3).inspect + # # => "#" + # + def inspect + sg = @sg.is_a?(Float) ? @sg.to_s : @sg + "#".force_encoding(Encoding::US_ASCII) end - def c_jd_to_weeknum(jd, f, sg) - ry, _, _ = self.class.send(:c_jd_to_civil, jd, sg) - rjd, _ = self.class.send(:c_find_fdoy, ry, sg) - - rjd += 6 - - mod_val = euclidean_mod((rjd - f) + 1, 7) - j = jd - (rjd - mod_val) + 7 - - rw = euclidean_div(j, 7) - rd = euclidean_mod(j, 7) - - [ry, rw, rd] + # override + def freeze + _civil # compute and cache civil date before freezing + super end - # Euclidean division (equivalent to the DIV macro in C) - def euclidean_div(a, b) - q = a / b - r = a % b - # In Ruby, a remainder of a negative number is negative, so adjust it accordingly. - if r < 0 - if b > 0 - q -= 1 - else - q += 1 - end - end - - q - end + # --------------------------------------------------------------------------- + # Private helpers + # --------------------------------------------------------------------------- - # Euclidean modulo (equivalent to the MOD macro in C) - def euclidean_mod(a, b) - r = a % b - # In Ruby, a remainder of a negative number is negative, so adjust it accordingly. - if r < 0 - if b > 0 - r += b - else - r -= b - end - end + private - r + def _init_from_jd(jd, sg, df = nil) + @jd = jd + @sg = sg + @df = df end - def jisx0301_date_format(jd, year) - # If jd is not a Fixnum (Integer in Ruby), use ISO format - return '%Y-%m-%d' unless jd.is_a?(Integer) - - # Determine the era based on Julian Day Number - if jd < 2405160 - # Before Meiji era (before 1868-01-25) - '%Y-%m-%d' - elsif jd < 2419614 - # Meiji era (M) 1868-01-25 to 1912-07-29 - era_char = 'M' - era_start = 1867 - format_era(era_char, year, era_start) - elsif jd < 2424875 - # Taisho era (T) 1912-07-30 to 1926-12-24 - era_char = 'T' - era_start = 1911 - format_era(era_char, year, era_start) - elsif jd < 2447535 - # Showa era (S) 1926-12-25 to 1989-01-07 - era_char = 'S' - era_start = 1925 - format_era(era_char, year, era_start) - elsif jd < 2458605 - # Heisei era (H) 1989-01-08 to 2019-04-30 - era_char = 'H' - era_start = 1988 - format_era(era_char, year, era_start) + def _civil + return if @year + jd = @jd + if @sg == Float::INFINITY # always Julian + b = 0 + c = jd + 32082 + elsif jd >= @sg # Gregorian (handles -Infinity too) + a = jd + 32044 + b = (4 * a + 3) / 146097 + c = a - (146097 * b) / 4 + else # Julian (before reform date) + b = 0 + c = jd + 32082 + end + d = (4 * c + 3) / 1461 + e = c - (1461 * d) / 4 + m = (5 * e + 2) / 153 + @day = e - (153 * m + 2) / 5 + 1 + @month = m + 3 - 12 * (m / 10) + @year = 100 * b + d - 4800 + m / 10 + end + + # Inline jd_to_commercial: compute and cache cwyear/cweek + def _compute_commercial + jd = @jd + wday_val = (jd + 1) % 7 + cwday_val = wday_val == 0 ? 7 : wday_val + thursday = jd + (4 - cwday_val) + sg = @sg + # inline jd_to_gregorian/jd_to_julian to get year only + if sg == Float::INFINITY + # Julian + c = thursday + 32082 + d = (4 * c + 3) / 1461 + e = c - (1461 * d) / 4 + m = (5 * e + 2) / 153 + y = d - 4800 + m / 10 + elsif thursday >= sg + # Gregorian + a = thursday + 32044 + b = (4 * a + 3) / 146097 + c = a - (146097 * b) / 4 + d = (4 * c + 3) / 1461 + e = c - (1461 * d) / 4 + m = (5 * e + 2) / 153 + y = 100 * b + d - 4800 + m / 10 else - # Reiwa era (R) 2019-05-01 onwards - era_char = 'R' - era_start = 2018 - format_era(era_char, year, era_start) + # Julian + c = thursday + 32082 + d = (4 * c + 3) / 1461 + e = c - (1461 * d) / 4 + m = (5 * e + 2) / 153 + y = d - 4800 + m / 10 + end + # inline civil_to_jd(y, 1, 4, sg): month=1 (<= 2), day=4 + yy = y - 1 + gjd_base = (1461 * (yy + 4716)) / 4 + 432 # GJD_MONTH_OFFSET[1](=428) + 4 + a2 = yy / 100 + gjd = gjd_base - 1524 + 2 - a2 + a2 / 4 + jd_jan4 = gjd >= sg ? gjd : gjd_base - 1524 + wday_jan4 = (jd_jan4 + 1) % 7 + iso_wday_jan4 = wday_jan4 == 0 ? 7 : wday_jan4 + mon_wk1 = jd_jan4 - (iso_wday_jan4 - 1) + cw = (jd - mon_wk1) / 7 + 1 + unless frozen? + @cweek = cw + @cwyear = y end + [y, cw] end - def format_era(era_char, year, era_start) - era_year = year - era_start - "#{era_char}%02d.%%m.%%d" % era_year - end - - def zone - of = @parsed_offset || 0 - s = of < 0 ? '-' : '+' - a = of.abs - h = a / HOUR_IN_SECONDS - m = a % HOUR_IN_SECONDS / MINUTE_IN_SECONDS - "%c%02d:%02d" % [s, h, m] - end - - # C: old_to_new — converts old ajd/of/sg format to new nth/jd/df/sf/of/sg - def old_to_new(ajd, of, sg) - # C: decode_day(ajd + half_days_in_day, &jd, &df, &sf) - d = ajd + Rational(1, 2) - - # div_day: jd = floor(d), f = d mod 1 - jd_full = d.floor - f = d - jd_full - - # div_df: df = floor(f * DAY_IN_SECONDS), remainder - df_rational = f * 86400 - df = df_rational.floor - sf_frac = df_rational - df - - # sec_to_ns: sf = round(sf_frac * SECOND_IN_NANOSECONDS) - sf = (sf_frac * 1_000_000_000).round - - # C: day_to_sec(of) then round - of_sec = (of * 86400).round.to_i - - # C: decode_jd(jd, &nth, &rjd) - nth = jd_full.div(CM_PERIOD) - rjd = (jd_full % CM_PERIOD).to_i - - # Validations (C: old_to_new) - raise Error, "invalid day fraction" if df < 0 || df >= 86400 - if of_sec < -86400 || of_sec > 86400 - of_sec = 0 - warn "invalid offset is ignored" - end - - # Convert Infinity to Float (C: NUM2DBL(sg)) - if sg.is_a?(Infinity) - sg = case sg.send(:d) - when -1 then -Float::INFINITY - when 1 then Float::INFINITY - else DEFAULT_SG - end - end - - [nth, rjd, df, sf, of_sec, sg] - end end diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 844447d6..aa68c08c 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -1,383 +1,486 @@ # frozen_string_literal: true -# Implementation of DateTime from ruby/date/ext/date/date_core.c -# DateTime is a subclass of Date that includes time-of-day and timezone. class DateTime < Date + + STRFTIME_DATETIME_DEFAULT_FMT = '%FT%T%:z'.encode(Encoding::US_ASCII) + private_constant :STRFTIME_DATETIME_DEFAULT_FMT + + # --------------------------------------------------------------------------- + # Initializer + # --------------------------------------------------------------------------- + # call-seq: # DateTime.new(year=-4712, month=1, day=1, hour=0, minute=0, second=0, offset=0, start=Date::ITALY) -> datetime - # - # Creates a new DateTime object. def initialize(year = -4712, month = 1, day = 1, hour = 0, minute = 0, second = 0, offset = 0, start = ITALY) - y = year - m = month - d = day - h = hour - min = minute - s = second - fr2 = 0 - - # argument type checking - raise TypeError, "invalid year (not numeric)" unless y.is_a?(Numeric) - raise TypeError, "invalid month (not numeric)" unless m.is_a?(Numeric) - raise TypeError, "invalid day (not numeric)" unless d.is_a?(Numeric) - raise TypeError, "invalid hour (not numeric)" unless h.is_a?(Numeric) - raise TypeError, "invalid minute (not numeric)" unless min.is_a?(Numeric) - raise TypeError, "invalid second (not numeric)" unless s.is_a?(Numeric) - - # Handle fractional day (C: d_trunc) - d_trunc, fr = d_trunc_with_frac(d) - d = d_trunc - fr2 = fr if fr.nonzero? - - # Handle fractional hour (C: h_trunc via num2int_with_frac) - h_int = h.to_i - h_frac = h - h_int - if h_frac.nonzero? - fr2 = fr2 + Rational(h_frac) / 24 - h = h_int - end + year = Integer(year) + month = Integer(month) + of_sec = _str_offset_to_sec(offset) - # Handle fractional minute (C: min_trunc) - min_int = min.to_i - min_frac = min - min_int - if min_frac.nonzero? - fr2 = fr2 + Rational(min_frac) / 1440 - min = min_int - end + raise TypeError, "expected numeric" unless day.is_a?(Numeric) - # Handle fractional second (C: s_trunc) - # C converts sub-second fraction to day fraction: fr2 = frac / DAY_IN_SECONDS - s_int = s.to_i - s_frac = s - s_int - if s_frac.nonzero? - fr2 = fr2 + Rational(s_frac) / DAY_IN_SECONDS - s = s_int - end + # Fractional day/hour/minute: propagate fraction to smaller units + day_r = day.to_r + day_i = day_r.floor + day_frac = day_r - day_i + day = day_i - # Convert offset to integer seconds (C: val2off → offset_to_sec) - rof = offset_to_sec(offset) + jd = self.class.__send__(:internal_valid_civil?, year, month, day, start) + raise Date::Error, "invalid date" unless jd - sg = self.class.send(:valid_sg, start) - style = self.class.send(:guess_style, y, sg) + raise TypeError, "expected numeric" unless hour.is_a?(Numeric) + raise TypeError, "expected numeric" unless minute.is_a?(Numeric) + raise TypeError, "expected numeric" unless second.is_a?(Numeric) - # Validate time (C: c_valid_time_p) - h, min, s = validate_time(h, min, s) + # Propagate fractions to smaller units + hour_r = hour.to_r + day_frac * 24 + hour_i = hour_r.floor + hour_frac = hour_r - hour_i - # Handle hour 24 (C: canon24oc) - if h == 24 - h = 0 - fr2 = fr2 + 1 - end - - if style < 0 - # gregorian calendar only - result = self.class.send(:valid_gregorian_p, y, m, d) - raise Error, "invalid date" unless result - - nth, ry = self.class.send(:decode_year, y, -1) - rm = result[:rm] - rd = result[:rd] - - rjd, _ = self.class.send(:c_civil_to_jd, ry, rm, rd, GREGORIAN) - rjd2 = jd_local_to_utc(rjd, time_to_df(h, min, s), rof) - - @nth = canon(nth) - @jd = rjd2 - @sg = sg - @year = ry - @month = rm - @day = rd - @has_jd = true - @has_civil = true - @hour = h - @min = min - @sec = s - @df = df_local_to_utc(time_to_df(h, min, s), rof) - @sf = 0 - @of = rof - else - # full validation - result = self.class.send(:valid_civil_p, y, m, d, sg) - raise Error, "invalid date" unless result - - nth = result[:nth] - ry = result[:ry] - rm = result[:rm] - rd = result[:rd] - rjd = result[:rjd] - - rjd2 = jd_local_to_utc(rjd, time_to_df(h, min, s), rof) - - @nth = canon(nth) - @jd = rjd2 - @sg = sg - @year = ry - @month = rm - @day = rd - @has_jd = true - @has_civil = true - @hour = h - @min = min - @sec = s - @df = df_local_to_utc(time_to_df(h, min, s), rof) - @sf = 0 - @of = rof - end + minute_r = minute.to_r + hour_frac * 60 + minute_i = minute_r.floor + minute_frac = minute_r - minute_i - # Add accumulated fractional parts (C: add_frac) - if fr2.nonzero? - new_date = self + fr2 - @nth = new_date.instance_variable_get(:@nth) - @jd = new_date.instance_variable_get(:@jd) - @sg = new_date.instance_variable_get(:@sg) - @year = new_date.instance_variable_get(:@year) - @month = new_date.instance_variable_get(:@month) - @day = new_date.instance_variable_get(:@day) - @has_jd = new_date.instance_variable_get(:@has_jd) - @has_civil = new_date.instance_variable_get(:@has_civil) - @hour = new_date.instance_variable_get(:@hour) - @min = new_date.instance_variable_get(:@min) - @sec = new_date.instance_variable_get(:@sec) - @df = new_date.instance_variable_get(:@df) || @df - @sf = new_date.instance_variable_get(:@sf) || @sf - @of = new_date.instance_variable_get(:@of) || @of - end + second_r = second.to_r + minute_frac * 60 + sec_i = second_r.floor + sec_f = second_r - sec_i + jd, hour, minute, sec_i = self.class.__send__(:_normalize_hms, jd, hour_i, minute_i, sec_i) - self + _init_datetime(jd, hour, minute, sec_i, sec_f, of_sec, start) end - # --- DateTime accessors (C: d_lite_hour etc.) --- + # --------------------------------------------------------------------------- + # Instance attributes + # --------------------------------------------------------------------------- # call-seq: # hour -> integer # - # Returns the hour in range (0..23). + # Returns the hour in range (0..23): + # + # DateTime.new(2001, 2, 3, 4, 5, 6).hour # => 4 def hour - if simple_dat_p? - 0 - else - get_c_time - @hour || 0 - end + @hour end # call-seq: # min -> integer # - # Returns the minute in range (0..59). + # Returns the minute in range (0..59): + # + # DateTime.new(2001, 2, 3, 4, 5, 6).min # => 5 def min - if simple_dat_p? - 0 - else - get_c_time - @min || 0 - end + @min end alias minute min # call-seq: # sec -> integer # - # Returns the second in range (0..59). + # Returns the second in range (0..59): + # + # DateTime.new(2001, 2, 3, 4, 5, 6).sec # => 6 def sec - if simple_dat_p? - 0 - else - get_c_time - @sec || 0 - end + @sec_i end alias second sec # call-seq: # sec_fraction -> rational # - # Returns the fractional part of the second: + # Returns the fractional part of the second in range + # (Rational(0, 1)...Rational(1, 1)): # # DateTime.new(2001, 2, 3, 4, 5, 6.5).sec_fraction # => (1/2) - # - # C: m_sf_in_sec = ns_to_sec(m_sf) def sec_fraction - ns = m_sf - ns.zero? ? Rational(0) : Rational(ns, SECOND_IN_NANOSECONDS) + @sec_frac end alias second_fraction sec_fraction # call-seq: - # offset -> rational - # - # Returns the offset as a fraction of day: + # d.offset -> rational # - # DateTime.parse('04pm+0730').offset # => (5/16) + # Returns the offset. # - # C: m_of_in_day = isec_to_day(m_of) + # DateTime.parse('04pm+0730').offset #=> (5/16) def offset - of = m_of - of.zero? ? Rational(0) : Rational(of, DAY_IN_SECONDS) + Rational(@of, 86400) end # call-seq: - # zone -> string + # d.zone -> string # - # Returns the timezone as a string: + # Returns the timezone. # - # DateTime.parse('04pm+0730').zone # => "+07:30" - # - # C: m_zone → of2str(m_of) + # DateTime.parse('04pm+0730').zone #=> "+07:30" def zone - if simple_dat_p? - "+00:00".encode(Encoding::US_ASCII) + _of2str(@of) + end + + # call-seq: + # day_fraction -> rational + # + # Returns the fractional part of the day in range (Rational(0, 1)...Rational(1, 1)): + # + # DateTime.new(2001,2,3,12).day_fraction # => (1/2) + def day_fraction + Rational(@hour * 3600 + @min * 60 + @sec_i, 86400) + + Rational(@sec_frac.numerator, @sec_frac.denominator * 86400) + end + + # call-seq: + # d.ajd -> rational + # + # Returns the astronomical Julian day number. This is a fractional + # number, which is not adjusted by the offset. + # + # DateTime.new(2001,2,3,4,5,6,'+7').ajd #=> (11769328217/4800) + # DateTime.new(2001,2,2,14,5,6,'-7').ajd #=> (11769328217/4800) + def ajd + jd_r = Rational(@jd) + time_r = Rational(@hour * 3600 + @min * 60 + @sec_i, 86400) + + Rational(@sec_frac.numerator, @sec_frac.denominator * 86400) + of_r = Rational(@of, 86400) + jd_r + time_r - of_r - Rational(1, 2) + end + + # --------------------------------------------------------------------------- + # Arithmetic (override for fractional day support) + # --------------------------------------------------------------------------- + + # call-seq: + # d + other -> date + # + # Returns a date object pointing +other+ days after self. The other + # should be a numeric value. If the other is a fractional number, + # assumes its precision is at most nanosecond. + # + # Date.new(2001,2,3) + 1 #=> # + # DateTime.new(2001,2,3) + Rational(1,2) + # #=> # + # DateTime.new(2001,2,3) + Rational(-1,2) + # #=> # + # DateTime.jd(0,12) + DateTime.new(2001,2,3).ajd + # #=> # + def +(other) + case other + when Integer + self.class.__send__(:_new_dt_from_jd_time,@jd + other, @hour, @min, @sec_i, @sec_frac, @of, @sg) + when Rational, Float + # other is days (may be fractional) — add as seconds + extra_sec = other.to_r * 86400 + total_r = Rational(@jd) * 86400 + @hour * 3600 + @min * 60 + @sec_i + @sec_frac + extra_sec + _from_total_sec_r(total_r) + when Numeric + r = other.to_r + raise TypeError, "#{other.class} can't be coerced into Integer" unless r.is_a?(Rational) + extra_sec = r * 86400 + total_r = Rational(@jd) * 86400 + @hour * 3600 + @min * 60 + @sec_i + @sec_frac + extra_sec + _from_total_sec_r(total_r) else - of = m_of - s = of < 0 ? '-' : '+' - a = of < 0 ? -of : of - h = a / HOUR_IN_SECONDS - m = a % HOUR_IN_SECONDS / MINUTE_IN_SECONDS - ("%c%02d:%02d" % [s, h, m]).encode(Encoding::US_ASCII) + raise TypeError, "expected numeric" end end - STRFTIME_DATETIME_DEFAULT_FMT = '%FT%T%:z'.encode(Encoding::US_ASCII) - private_constant :STRFTIME_DATETIME_DEFAULT_FMT + # call-seq: + # d - other -> date or rational + # + # If the other is a date object, returns a Rational + # whose value is the difference between the two dates in days. + # If the other is a numeric value, returns a date object + # pointing +other+ days before self. + # If the other is a fractional number, + # assumes its precision is at most nanosecond. + # + # Date.new(2001,2,3) - 1 #=> # + # DateTime.new(2001,2,3) - Rational(1,2) + # #=> # + # Date.new(2001,2,3) - Date.new(2001) + # #=> (33/1) + # DateTime.new(2001,2,3) - DateTime.new(2001,2,2,12) + # #=> (1/2) + def -(other) + case other + when Date + ajd - other.ajd + when Integer + self.class.__send__(:_new_dt_from_jd_time,@jd - other, @hour, @min, @sec_i, @sec_frac, @of, @sg) + when Rational, Float + self + (-other) + when Numeric + r = other.to_r + raise TypeError, "#{other.class} can't be coerced into Integer" unless r.is_a?(Rational) + self + (-r) + else + raise TypeError, "expected numeric" + end + end + + # call-seq: + # new_start(start = Date::ITALY]) -> new_date + # + # Returns a copy of +self+ with the given +start+ value: + # + # d0 = Date.new(2000, 2, 3) + # d0.julian? # => false + # d1 = d0.new_start(Date::JULIAN) + # d1.julian? # => true + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + def new_start(start = Date::ITALY) + self.class.__send__(:_new_dt_from_jd_time, @jd, @hour, @min, @sec_i, @sec_frac, @of, start) + end + + # call-seq: + # d.new_offset([offset=0]) -> date + # + # Duplicates self and resets its offset. + # + # d = DateTime.new(2001,2,3,4,5,6,'-02:00') + # #=> # + # d.new_offset('+09:00') #=> # + def new_offset(of = 0) + of_sec = _str_offset_to_sec(of) + self.class.__send__(:_new_dt_from_jd_time,@jd, @hour, @min, @sec_i, @sec_frac, of_sec, @sg) + end + + # --------------------------------------------------------------------------- + # String formatting + # --------------------------------------------------------------------------- - # Override Date#strftime with DateTime default format + # call-seq: + # strftime(format = '%FT%T%:z') -> string + # + # Returns a string representation of +self+, + # formatted according the given +format: + # + # DateTime.now.strftime # => "2022-07-01T11:03:19-05:00" + # + # For other formats, + # see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: def strftime(format = STRFTIME_DATETIME_DEFAULT_FMT) super(format) end - # Override Date#jisx0301 for DateTime (includes time) + # call-seq: + # dt.jisx0301([n=0]) -> string + # + # Returns a string in a JIS X 0301 format. + # The optional argument +n+ is the number of digits for fractional seconds. + # + # DateTime.parse('2001-02-03T04:05:06.123456789+07:00').jisx0301(9) + # #=> "H13.02.03T04:05:06.123456789+07:00" def jisx0301(n = 0) n = n.to_i - if n == 0 - jd_val = send(:m_real_local_jd) - y = send(:m_real_year) - fmt = jisx0301_date_format(jd_val, y) + 'T%T%:z' - strftime(fmt) - else - s = jisx0301(0) - # insert fractional seconds before timezone - tz = s[-6..] # "+00:00" - base = s[0...-6] - frac = sec_fraction - if frac != 0 - f = format("%.#{n}f", frac.to_f)[1..] - base += f - else - base += '.' + '0' * n + ERA_TABLE.each do |start_jd, era, base_year| + if @jd >= start_jd + era_year = year - base_year + if n == 0 + return format('%s%02d.%02d.%02dT%02d:%02d:%02d%s', + era, era_year, month, day, hour, min, sec, zone) + else + sf = sec_fraction + frac = '.' + (sf * (10**n)).to_i.to_s.rjust(n, '0') + return format('%s%02d.%02d.%02dT%02d:%02d:%02d%s%s', + era, era_year, month, day, hour, min, sec, frac, zone) + end end - base + tz end + iso8601(n) end - # DateTime instance method - overrides Date#iso8601 + # call-seq: + # dt.iso8601([n=0]) -> string + # dt.xmlschema([n=0]) -> string + # + # This method is equivalent to strftime('%FT%T%:z'). + # The optional argument +n+ is the number of digits for fractional seconds. + # + # DateTime.parse('2001-02-03T04:05:06.123456789+07:00').iso8601(9) + # #=> "2001-02-03T04:05:06.123456789+07:00" def iso8601(n = 0) n = n.to_i if n == 0 - strftime('%FT%T%:z') + strftime('%Y-%m-%dT%H:%M:%S%:z') else - s = strftime('%FT%T') - frac = sec_fraction - if frac != 0 - f = format("%.#{n}f", frac.to_f)[1..] - s += f - else - s += '.' + '0' * n - end - s + strftime('%:z') + sf = sec_fraction + frac = '.' + (sf * (10**n)).to_i.to_s.rjust(n, '0') + strftime("%Y-%m-%dT%H:%M:%S#{frac}%:z") end end alias_method :xmlschema, :iso8601 - alias_method :rfc3339, :iso8601 # call-seq: - # deconstruct_keys(array_of_names_or_nil) -> hash + # dt.rfc3339([n=0]) -> string # - # Returns name/value pairs for pattern matching. - # Includes Date keys (:year, :month, :day, :wday, :yday) - # plus DateTime keys (:hour, :min, :sec, :sec_fraction, :zone). + # This method is equivalent to strftime('%FT%T%:z'). + # The optional argument +n+ is the number of digits for fractional seconds. # - # C: dt_lite_deconstruct_keys (is_datetime=true) - def deconstruct_keys(keys) - if keys.nil? - return { - year: year, - month: month, - day: day, - yday: yday, - wday: wday, - hour: hour, - min: min, - sec: sec, - sec_fraction: sec_fraction, - zone: zone - } - end + # DateTime.parse('2001-02-03T04:05:06.123456789+07:00').rfc3339(9) + # #=> "2001-02-03T04:05:06.123456789+07:00" + alias_method :rfc3339, :iso8601 - raise TypeError, "wrong argument type #{keys.class} (expected Array or nil)" unless keys.is_a?(Array) - - h = {} - keys.each do |key| - case key - when :year then h[:year] = year - when :month then h[:month] = month - when :day then h[:day] = day - when :yday then h[:yday] = yday - when :wday then h[:wday] = wday - when :hour then h[:hour] = hour - when :min then h[:min] = min - when :sec then h[:sec] = sec - when :sec_fraction then h[:sec_fraction] = sec_fraction - when :zone then h[:zone] = zone + # call-seq: + # deconstruct_keys(array_of_names_or_nil) -> hash + # + # Returns a hash of the name/value pairs, to use in pattern matching. + # Possible keys are: :year, :month, :day, + # :wday, :yday, :hour, :min, + # :sec, :sec_fraction, :zone. + # + # Possible usages: + # + # dt = DateTime.new(2022, 10, 5, 13, 30) + # + # if d in wday: 1..5, hour: 10..18 # uses deconstruct_keys underneath + # puts "Working time" + # end + # #=> prints "Working time" + # + # case dt + # in year: ...2022 + # puts "too old" + # in month: ..9 + # puts "quarter 1-3" + # in wday: 1..5, month: + # puts "working day in month #{month}" + # end + # #=> prints "working day in month 10" + # + # Note that deconstruction by pattern can also be combined with class check: + # + # if d in DateTime(wday: 1..5, hour: 10..18, day: ..7) + # puts "Working time, first week of the month" + # end + def deconstruct_keys(keys) + if keys + if keys.size == 1 + case keys[0] + when :year + _civil unless @year + { year: @year } + when :month + _civil unless @year + { month: @month } + when :day + _civil unless @year + { day: @day } + when :wday then { wday: (@jd + 1) % 7 } + when :yday then { yday: yday } + when :hour then { hour: @hour } + when :min then { min: @min } + when :sec then { sec: @sec_i } + when :sec_fraction then { sec_fraction: @sec_frac } + when :zone then { zone: _of2str(@of) } + else {} + end + else + _civil unless @year + h = {} + keys.each do |k| + case k + when :year then h[:year] = @year + when :month then h[:month] = @month + when :day then h[:day] = @day + when :wday then h[:wday] = (@jd + 1) % 7 + when :yday then h[:yday] = yday + when :hour then h[:hour] = @hour + when :min then h[:min] = @min + when :sec then h[:sec] = @sec_i + when :sec_fraction then h[:sec_fraction] = @sec_frac + when :zone then h[:zone] = _of2str(@of) + end + end + h end + else + _civil unless @year + { year: @year, month: @month, day: @day, wday: (@jd + 1) % 7, yday: yday, + hour: @hour, min: @min, sec: @sec_i, sec_fraction: @sec_frac, zone: _of2str(@of) } end - h end + DATETIME_TO_S_FMT = '%Y-%m-%dT%H:%M:%S%:z'.encode(Encoding::US_ASCII).freeze + private_constant :DATETIME_TO_S_FMT + # call-seq: - # to_s -> string + # dt.to_s -> string # - # Returns a string in ISO 8601 DateTime format: + # Returns a string in an ISO 8601 format. (This method doesn't use the + # expanded representations.) # - # DateTime.new(2001, 2, 3, 4, 5, 6, '+7').to_s - # # => "2001-02-03T04:05:06+07:00" + # DateTime.new(2001,2,3,4,5,6,'-7').to_s + # #=> "2001-02-03T04:05:06-07:00" def to_s - sprintf("%04d-%02d-%02dT%02d:%02d:%02d%s".encode(Encoding::US_ASCII), year, month, day, hour, min, sec, zone) + strftime(DATETIME_TO_S_FMT) end - # call-seq: - # new_offset(offset = 0) -> datetime - # - # Returns a new DateTime object with the same date and time, - # but with the given +offset+. - # - # C: d_lite_new_offset - def new_offset(of = 0) - if of.is_a?(String) - of = Rational(offset_to_sec(of), DAY_IN_SECONDS) - elsif of.is_a?(Integer) && of == 0 - of = Rational(0) + def hash + if @hour == 0 && @min == 0 && @sec_i == 0 + [@jd, @sg].hash + else + [@jd, @hour, @min, @sec_i, @sg].hash end - raise TypeError, "invalid offset" unless of.is_a?(Rational) || of.is_a?(Integer) || of.is_a?(Float) - of = Rational(of) unless of.is_a?(Rational) - self.class.new(year, month, day, hour, min, sec + sec_fraction, of, start) end + # --------------------------------------------------------------------------- + # Serialization override + # --------------------------------------------------------------------------- + + # :nodoc: + def marshal_dump + # 6-element format: [nth, jd, df, sf, of, sg] + df = @hour * 3600 + @min * 60 + @sec_i + sf = (@sec_frac * 1_000_000_000).to_r # nanoseconds as Rational + [0, @jd, df, sf, @of, @sg] + end + + # :nodoc: + def marshal_load(array) + case array.length + when 2 + jd_like, sg_or_bool = array + sg = sg_or_bool == true ? ITALY : (sg_or_bool == false ? JULIAN : sg_or_bool.to_f) + _init_datetime(jd_like.to_i, 0, 0, 0, Rational(0), 0, sg) + when 3 + ajd, of_r, sg = array + of_sec = (of_r * 86400).to_i + # Reconstruct local JD and time from AJD + local_r = ajd + Rational(1, 2) + of_r + jd = local_r.floor + rem_r = (local_r - jd) * 86400 + h = rem_r.to_i / 3600 + rem_r -= h * 3600 + m = rem_r.to_i / 60 + s_r = rem_r - m * 60 + s_i, s_f = _split_second(s_r) + _init_datetime(jd, h, m, s_i, s_f, of_sec, sg) + when 6 + _nth, jd, df, sf, of, sg = array + h = df / 3600 + df -= h * 3600 + m = df / 60 + s = df % 60 + sf_r = sf.is_a?(Rational) ? (sf / 1_000_000_000) : Rational(sf.to_i, 1_000_000_000) + _init_datetime(jd, h, m, s, sf_r, of, sg) + else + raise TypeError, "invalid marshal data" + end + end + + # --------------------------------------------------------------------------- + # Type conversions + # --------------------------------------------------------------------------- + # call-seq: - # to_date -> date + # dt.to_date -> date # - # Returns a Date for this DateTime (time information is discarded). - # C: dt_lite_to_date → copy civil, reset time + # Returns a Date object which denotes self. def to_date - nth, ry = self.class.send(:decode_year, year, -1) - Date.send(:d_simple_new_internal, - nth, 0, - @sg, - ry, month, day, - 0x04) # HAVE_CIVIL + Date.__send__(:_new_from_jd, @jd, @sg) end # call-seq: - # to_datetime -> self + # dt.to_datetime -> self # # Returns self. def to_datetime @@ -385,442 +488,482 @@ def to_datetime end # call-seq: - # to_time -> time + # dt.to_time -> time # - # Returns a Time for this DateTime. - # C: dt_lite_to_time + # Returns a Time object which denotes self. def to_time - # C: dt_lite_to_time — converts Julian dates to Gregorian for Time compatibility - d = julian? ? gregorian : self - Time.new(d.year, d.month, d.day, d.hour, d.min, d.sec + d.sec_fraction, d.send(:m_of)) + y, m, d = self.class.__send__(:jd_to_gregorian, @jd) + if @of == 0 + Time.utc(y, m, d, @hour, @min, @sec_i + @sec_frac) + else + Time.new(y, m, d, @hour, @min, @sec_i + @sec_frac, @of) + end end + # --------------------------------------------------------------------------- + # Class methods + # --------------------------------------------------------------------------- + class << self - # Same as DateTime.new alias_method :civil, :new undef_method :today # call-seq: - # DateTime.jd(jd=0, hour=0, minute=0, second=0, offset=0, start=Date::ITALY) -> datetime + # DateTime._strptime(string[, format='%FT%T%z']) -> hash # - # Creates a new DateTime from a Julian Day Number. - # C: dt_lite_s_jd - def jd(jd = 0, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) - # Validate jd - raise TypeError, "invalid jd (not numeric)" unless jd.is_a?(Numeric) - raise TypeError, "invalid hour (not numeric)" unless hour.is_a?(Numeric) - raise TypeError, "invalid minute (not numeric)" unless minute.is_a?(Numeric) - raise TypeError, "invalid second (not numeric)" unless second.is_a?(Numeric) - - j, fr = value_trunc(jd) - nth, rjd = decode_jd(j) - - sg = valid_sg(start) - - # Validate time - h = hour.to_i - h_frac = hour - h - min_i = minute.to_i - min_frac = minute - min_i - s_i = second.to_i - s_frac = second - s_i - - fr2 = fr - fr2 = fr2 + Rational(h_frac) / 24 if h_frac.nonzero? - fr2 = fr2 + Rational(min_frac) / 1440 if min_frac.nonzero? - fr2 = fr2 + Rational(s_frac) / 86400 if s_frac.nonzero? - - rof = _offset_to_sec(offset) + # Parses the given representation of date and time with the given + # template, and returns a hash of parsed elements. _strptime does + # not support specification of flags and width unlike strftime. + # + # See also strptime(3) and #strftime. + def _strptime(string = JULIAN_EPOCH_DATETIME, format = '%FT%T%z') + Date._strptime(string, format) + end - h += 24 if h < 0 - min_i += 60 if min_i < 0 - s_i += 60 if s_i < 0 - unless (0..24).cover?(h) && (0..59).cover?(min_i) && (0..59).cover?(s_i) && - !(h == 24 && (min_i > 0 || s_i > 0)) - raise Date::Error, "invalid date" - end - if h == 24 - h = 0 - fr2 = fr2 + 1 - end + # call-seq: + # DateTime.strptime([string='-4712-01-01T00:00:00+00:00'[, format='%FT%T%z'[ ,start=Date::ITALY]]]) -> datetime + # + # Parses the given representation of date and time with the given + # template, and creates a DateTime object. strptime does not support + # specification of flags and width unlike strftime. + # + # DateTime.strptime('2001-02-03T04:05:06+07:00', '%Y-%m-%dT%H:%M:%S%z') + # #=> # + # DateTime.strptime('03-02-2001 04:05:06 PM', '%d-%m-%Y %I:%M:%S %p') + # #=> # + # DateTime.strptime('2001-W05-6T04:05:06+07:00', '%G-W%V-%uT%H:%M:%S%z') + # #=> # + # DateTime.strptime('2001 04 6 04 05 06 +7', '%Y %U %w %H %M %S %z') + # #=> # + # DateTime.strptime('2001 05 6 04 05 06 +7', '%Y %W %u %H %M %S %z') + # #=> # + # DateTime.strptime('-1', '%s') + # #=> # + # DateTime.strptime('-1000', '%Q') + # #=> # + # DateTime.strptime('sat3feb014pm+7', '%a%d%b%y%H%p%z') + # #=> # + # + # See also strptime(3) and #strftime. + def strptime(string = JULIAN_EPOCH_DATETIME, format = '%FT%T%z', start = Date::ITALY) + hash = _strptime(string, format) + _dt_new_by_frags(hash, start) + end - df = h * 3600 + min_i * 60 + s_i - df_utc = df - rof - jd_utc = rjd - if df_utc < 0 - jd_utc -= 1 - df_utc += 86400 - elsif df_utc >= 86400 - jd_utc += 1 - df_utc -= 86400 + # call-seq: + # DateTime.jd([jd=0[, hour=0[, minute=0[, second=0[, offset=0[, start=Date::ITALY]]]]]]) -> datetime + # + # Creates a DateTime object denoting the given chronological Julian + # day number. + # + # DateTime.jd(2451944) #=> # + # DateTime.jd(2451945) #=> # + # DateTime.jd(Rational('0.5')) + # #=> # + def jd(jd = 0, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) + raise TypeError, "no implicit conversion of #{jd.class} into Integer" unless jd.is_a?(Numeric) + jd_r = jd.to_r + jd_i = jd_r.floor + h = Integer(hour) + m = Integer(minute) + of_sec = _parse_of(offset) + if jd_i != jd_r + # Fractional JD: convert fraction to extra seconds and handle overflow + frac_sec = (jd_r - jd_i) * 86400 + second = second.to_r + frac_sec + sec_i, sec_f = _split_sec(second) + if sec_i >= 60 + carry_m, sec_i = sec_i.divmod(60) + m += carry_m + end + if m >= 60 + carry_h, m = m.divmod(60) + h += carry_h + end + if h >= 24 + carry_d, h = h.divmod(24) + jd_i += carry_d + end + else + # Integer JD: pass raw values to _normalize_hms (non-cascading) + sec_i, sec_f = _split_sec(second) end - - obj = new_with_jd_and_time(nth, jd_utc, df_utc, 0, rof, sg) - - obj = obj + fr2 if fr2.nonzero? - - obj + _new_dt_from_jd_time(jd_i, h, m, sec_i, sec_f, of_sec, start) end # call-seq: - # DateTime.ordinal(year=-4712, yday=1, hour=0, minute=0, second=0, offset=0, start=Date::ITALY) -> datetime + # DateTime.ordinal([year=-4712[, yday=1[, hour=0[, minute=0[, second=0[, offset=0[, start=Date::ITALY]]]]]]]) -> datetime + # + # Creates a DateTime object denoting the given ordinal date. # - # Creates a new DateTime from an ordinal date. - # C: dt_lite_s_ordinal + # DateTime.ordinal(2001,34) #=> # + # DateTime.ordinal(2001,34,4,5,6,'+7') + # #=> # + # DateTime.ordinal(2001,-332,-20,-55,-54,'+7') + # #=> # def ordinal(year = -4712, yday = 1, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) - raise TypeError, "invalid year (not numeric)" unless year.is_a?(Numeric) - raise TypeError, "invalid yday (not numeric)" unless yday.is_a?(Numeric) - raise TypeError, "invalid hour (not numeric)" unless hour.is_a?(Numeric) - raise TypeError, "invalid minute (not numeric)" unless minute.is_a?(Numeric) - raise TypeError, "invalid second (not numeric)" unless second.is_a?(Numeric) - - # Truncate fractional yday - yday_int = yday.to_i - yday_frac = yday.is_a?(Integer) ? 0 : yday - yday_int - - result = valid_ordinal_p(year, yday_int, start) - raise Date::Error, "invalid date" unless result + jd_v = internal_valid_ordinal?(Integer(year), Integer(yday), start) + raise Date::Error, "invalid date" unless jd_v + of_sec = _parse_of(offset) + sec_i, sec_f = _split_sec(second) + _new_dt_from_jd_time(jd_v, Integer(hour), Integer(minute), sec_i, sec_f, of_sec, start) + end - nth = result[:nth] - rjd = result[:rjd] - sg = valid_sg(start) + # call-seq: + # DateTime.commercial([cwyear=-4712[, cweek=1[, cwday=1[, hour=0[, minute=0[, second=0[, offset=0[, start=Date::ITALY]]]]]]]]) -> datetime + # + # Creates a DateTime object denoting the given week date. + # + # DateTime.commercial(2001) #=> # + # DateTime.commercial(2002) #=> # + # DateTime.commercial(2001,5,6,4,5,6,'+7') + # #=> # + def commercial(cwyear = -4712, cweek = 1, cwday = 1, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) + jd_v = internal_valid_commercial?(Integer(cwyear), Integer(cweek), Integer(cwday), start) + raise Date::Error, "invalid date" unless jd_v + of_sec = _parse_of(offset) + sec_i, sec_f = _split_sec(second) + _new_dt_from_jd_time(jd_v, Integer(hour), Integer(minute), sec_i, sec_f, of_sec, start) + end - rof = _offset_to_sec(offset) + # call-seq: + # DateTime.now([start=Date::ITALY]) -> datetime + # + # Creates a DateTime object denoting the present time. + # + # DateTime.now #=> # + def now(start = Date::ITALY) + t = Time.now + jd = civil_to_jd(t.year, t.mon, t.mday, start) + sec_f = Rational(t.subsec) + _new_dt_from_jd_time(jd, t.hour, t.min, t.sec, sec_f, t.utc_offset, start) + end - h = hour.to_i - h_frac = hour - h - min_i = minute.to_i - min_frac = minute - min_i - s_i = second.to_i - s_frac = second - s_i + # call-seq: + # DateTime.weeknum(year=-4712, week=0, wday=1, wstart=0, hour=0, min=0, sec=0, offset=0, start=Date::ITALY) -> datetime + def weeknum(year = -4712, week = 0, wday = 1, wstart = 0, + hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) + jd = weeknum_to_jd(Integer(year), Integer(week), Integer(wday), Integer(wstart), start) + of_sec = _parse_of(offset) + sec_i, sec_f = _split_sec(second) + _new_dt_from_jd_time(jd, Integer(hour), Integer(minute), sec_i, sec_f, of_sec, start) + end - fr2 = yday_frac.nonzero? ? Rational(yday_frac) : 0 - fr2 = fr2 + Rational(h_frac) / 24 if h_frac.nonzero? - fr2 = fr2 + Rational(min_frac) / 1440 if min_frac.nonzero? - fr2 = fr2 + Rational(s_frac) / 86400 if s_frac.nonzero? + # call-seq: + # DateTime.nth_kday(year=-4712, month=1, n=1, k=1, hour=0, min=0, sec=0, offset=0, start=Date::ITALY) -> datetime + def nth_kday(year = -4712, month = 1, n = 1, k = 1, + hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) + jd = nth_kday_to_jd(Integer(year), Integer(month), Integer(n), Integer(k), start) + of_sec = _parse_of(offset) + sec_i, sec_f = _split_sec(second) + _new_dt_from_jd_time(jd, Integer(hour), Integer(minute), sec_i, sec_f, of_sec, start) + end + + # :nodoc: + def _new_dt_from_jd_time(jd, h, m, s, sf, of, sg) + jd, h, m, s = _normalize_hms(jd, h, m, s) + obj = allocate + obj.__send__(:_init_datetime, jd, h, m, s, sf, of, sg) + obj + end + # Normalize hour/min/sec. + # Negative values: add one period (non-cascading, matching C's c_valid_time_f?). + # After normalization, validate ranges and raise Date::Error if out of range. + # 24:00:00 is valid (normalizes to next day 00:00:00). + def _normalize_hms(jd, h, m, s) + s += 60 if s < 0 + m += 60 if m < 0 h += 24 if h < 0 - min_i += 60 if min_i < 0 - s_i += 60 if s_i < 0 - unless (0..24).cover?(h) && (0..59).cover?(min_i) && (0..59).cover?(s_i) && - !(h == 24 && (min_i > 0 || s_i > 0)) - raise Date::Error, "invalid date" - end + raise Date::Error, "invalid date" if s >= 60 + raise Date::Error, "invalid date" if m >= 60 + raise Date::Error, "invalid date" if h > 24 || h < 0 + raise Date::Error, "invalid date" if h == 24 && (m != 0 || s != 0) if h == 24 + jd += 1 h = 0 - fr2 = fr2 + 1 end - - df = h * 3600 + min_i * 60 + s_i - df_utc = df - rof - jd_utc = rjd - if df_utc < 0 - jd_utc -= 1 - df_utc += 86400 - elsif df_utc >= 86400 - jd_utc += 1 - df_utc -= 86400 - end - - obj = new_with_jd_and_time(nth, jd_utc, df_utc, 0, rof, sg) - - obj = obj + fr2 if fr2.nonzero? - - obj + [jd, h, m, s] end # call-seq: - # DateTime.commercial(cwyear=-4712, cweek=1, cwday=1, hour=0, minute=0, second=0, offset=0, start=Date::ITALY) -> datetime + # DateTime.parse(string='-4712-01-01T00:00:00+00:00'[, comp=true[, start=Date::ITALY]], limit: 128) -> datetime # - # Creates a new DateTime from a commercial date. - # C: dt_lite_s_commercial - def commercial(cwyear = -4712, cweek = 1, cwday = 1, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) - raise TypeError, "invalid cwyear (not numeric)" unless cwyear.is_a?(Numeric) - raise TypeError, "invalid cweek (not numeric)" unless cweek.is_a?(Numeric) - raise TypeError, "invalid cwday (not numeric)" unless cwday.is_a?(Numeric) - raise TypeError, "invalid hour (not numeric)" unless hour.is_a?(Numeric) - raise TypeError, "invalid minute (not numeric)" unless minute.is_a?(Numeric) - raise TypeError, "invalid second (not numeric)" unless second.is_a?(Numeric) - - # Truncate fractional cwday - cwday_int = cwday.to_i - cwday_frac = cwday.is_a?(Integer) ? 0 : cwday - cwday_int - - result = valid_commercial_p(cwyear, cweek, cwday_int, start) - raise Date::Error, "invalid date" unless result - - nth = result[:nth] - rjd = result[:rjd] - sg = valid_sg(start) - - rof = _offset_to_sec(offset) - - h = hour.to_i - h_frac = hour - h - min_i = minute.to_i - min_frac = minute - min_i - s_i = second.to_i - s_frac = second - s_i - - fr2 = cwday_frac.nonzero? ? Rational(cwday_frac) : 0 - fr2 = fr2 + Rational(h_frac) / 24 if h_frac.nonzero? - fr2 = fr2 + Rational(min_frac) / 1440 if min_frac.nonzero? - fr2 = fr2 + Rational(s_frac) / 86400 if s_frac.nonzero? - - h += 24 if h < 0 - min_i += 60 if min_i < 0 - s_i += 60 if s_i < 0 - unless (0..24).cover?(h) && (0..59).cover?(min_i) && (0..59).cover?(s_i) && - !(h == 24 && (min_i > 0 || s_i > 0)) - raise Date::Error, "invalid date" - end - if h == 24 - h = 0 - fr2 = fr2 + 1 - end - - df = h * 3600 + min_i * 60 + s_i - df_utc = df - rof - jd_utc = rjd - if df_utc < 0 - jd_utc -= 1 - df_utc += 86400 - elsif df_utc >= 86400 - jd_utc += 1 - df_utc -= 86400 - end - - obj = new_with_jd_and_time(nth, jd_utc, df_utc, 0, rof, sg) - - obj = obj + fr2 if fr2.nonzero? - - obj + # Parses the given representation of date and time, and creates a + # DateTime object. + # + # This method *does* *not* function as a validator. If the input + # string does not match valid formats strictly, you may get a cryptic + # result. Should consider to use DateTime.strptime instead of this + # method as possible. + # + # If the optional second argument is true and the detected year is in + # the range "00" to "99", makes it full. + # + # DateTime.parse('2001-02-03T04:05:06+07:00') + # #=> # + # DateTime.parse('20010203T040506+0700') + # #=> # + # DateTime.parse('3rd Feb 2001 04:05:06 PM') + # #=> # + # + # Raise an ArgumentError when the string length is longer than _limit_. + # You can stop this check by passing limit: nil, but note + # that it may take a long time to parse. + def parse(string = '-4712-01-01T00:00:00+00:00', comp = true, start = Date::ITALY, limit: 128) + hash = Date._parse(string, comp, limit: limit) + _dt_new_by_frags(hash, start) end # call-seq: - # DateTime.strptime(string='-4712-01-01T00:00:00+00:00', format='%FT%T%z', start=Date::ITALY) -> datetime + # DateTime.iso8601(string='-4712-01-01T00:00:00+00:00'[, start=Date::ITALY], limit: 128) -> datetime # - # Parses +string+ according to +format+ and creates a DateTime. - # C: dt_lite_s_strptime - def strptime(string = '-4712-01-01T00:00:00+00:00', format = '%FT%T%z', start = Date::ITALY) - hash = _strptime(string, format) - dt_new_by_frags(hash, start) + # Creates a new DateTime object by parsing from a string according to + # some typical ISO 8601 formats. + # + # DateTime.iso8601('2001-02-03T04:05:06+07:00') + # #=> # + # DateTime.iso8601('20010203T040506+0700') + # #=> # + # DateTime.iso8601('2001-W05-6T04:05:06+07:00') + # #=> # + # + # Raise an ArgumentError when the string length is longer than _limit_. + # You can stop this check by passing limit: nil, but note + # that it may take a long time to parse. + def iso8601(string = '-4712-01-01T00:00:00+00:00', start = Date::ITALY, limit: 128) + hash = Date._iso8601(string, limit: limit) + _dt_new_by_frags(hash, start) end - # Override Date._strptime default format for DateTime - def _strptime(string, format = '%FT%T%z') - super(string, format) + # call-seq: + # DateTime.rfc3339(string='-4712-01-01T00:00:00+00:00'[, start=Date::ITALY], limit: 128) -> datetime + # + # Creates a new DateTime object by parsing from a string according to + # some typical RFC 3339 formats. + # + # DateTime.rfc3339('2001-02-03T04:05:06+07:00') + # #=> # + # + # Raise an ArgumentError when the string length is longer than _limit_. + # You can stop this check by passing limit: nil, but note + # that it may take a long time to parse. + def rfc3339(string = '-4712-01-01T00:00:00+00:00', start = Date::ITALY, limit: 128) + hash = Date._rfc3339(string, limit: limit) + _dt_new_by_frags(hash, start) end # call-seq: - # DateTime.now(start = Date::ITALY) -> datetime + # DateTime.xmlschema(string='-4712-01-01T00:00:00+00:00'[, start=Date::ITALY], limit: 128) -> datetime # - # Creates a DateTime for the current time. + # Creates a new DateTime object by parsing from a string according to + # some typical XML Schema formats. # - # C: datetime_s_now - def now(start = Date::ITALY) - t = Time.now - sg = valid_sg(start) - - of = t.utc_offset # integer seconds - - new( - t.year, t.mon, t.mday, - t.hour, t.min, t.sec + Rational(t.nsec, 1_000_000_000), - Rational(of, 86400), - sg - ) + # DateTime.xmlschema('2001-02-03T04:05:06+07:00') + # #=> # + # + # Raise an ArgumentError when the string length is longer than _limit_. + # You can stop this check by passing limit: nil, but note + # that it may take a long time to parse. + def xmlschema(string = '-4712-01-01T00:00:00+00:00', start = Date::ITALY, limit: 128) + hash = Date._xmlschema(string, limit: limit) + _dt_new_by_frags(hash, start) end # call-seq: - # DateTime.parse(string, comp = true, start = Date::ITALY, limit: 128) -> datetime + # DateTime.rfc2822(string='Mon, 1 Jan -4712 00:00:00 +0000'[, start=Date::ITALY], limit: 128) -> datetime + # DateTime.rfc822(string='Mon, 1 Jan -4712 00:00:00 +0000'[, start=Date::ITALY], limit: 128) -> datetime + # + # Creates a new DateTime object by parsing from a string according to + # some typical RFC 2822 formats. # - # Parses +string+ and creates a DateTime. + # DateTime.rfc2822('Sat, 3 Feb 2001 04:05:06 +0700') + # #=> # # - # C: date_parse → dt_new_by_frags - def parse(string = JULIAN_EPOCH_DATETIME, comp = true, start = Date::ITALY, limit: 128) - hash = _parse(string, comp, limit: limit) - dt_new_by_frags(hash, start) + # Raise an ArgumentError when the string length is longer than _limit_. + # You can stop this check by passing limit: nil, but note + # that it may take a long time to parse. + def rfc2822(string = 'Mon, 1 Jan -4712 00:00:00 +0000', start = Date::ITALY, limit: 128) + hash = Date._rfc2822(string, limit: limit) + _dt_new_by_frags(hash, start) end + alias rfc822 rfc2822 - # Format-specific constructors delegate to _xxx + dt_new_by_frags - - def iso8601(string = JULIAN_EPOCH_DATETIME, start = Date::ITALY, limit: 128) - hash = _iso8601(string, limit: limit) - dt_new_by_frags(hash, start) + # call-seq: + # DateTime.httpdate(string='Mon, 01 Jan -4712 00:00:00 GMT'[, start=Date::ITALY]) -> datetime + # + # Creates a new DateTime object by parsing from a string according to + # some RFC 2616 format. + # + # DateTime.httpdate('Sat, 03 Feb 2001 04:05:06 GMT') + # #=> # + # + # Raise an ArgumentError when the string length is longer than _limit_. + # You can stop this check by passing limit: nil, but note + # that it may take a long time to parse. + def httpdate(string = 'Mon, 01 Jan -4712 00:00:00 GMT', start = Date::ITALY, limit: 128) + hash = Date._httpdate(string, limit: limit) + _dt_new_by_frags(hash, start) end - def rfc3339(string = JULIAN_EPOCH_DATETIME, start = Date::ITALY, limit: 128) - hash = _rfc3339(string, limit: limit) - dt_new_by_frags(hash, start) + # call-seq: + # DateTime.jisx0301(string='-4712-01-01T00:00:00+00:00'[, start=Date::ITALY], limit: 128) -> datetime + # + # Creates a new DateTime object by parsing from a string according to + # some typical JIS X 0301 formats. + # + # DateTime.jisx0301('H13.02.03T04:05:06+07:00') + # #=> # + # + # For no-era year, legacy format, Heisei is assumed. + # + # DateTime.jisx0301('13.02.03T04:05:06+07:00') + # #=> # + # + # Raise an ArgumentError when the string length is longer than _limit_. + # You can stop this check by passing limit: nil, but note + # that it may take a long time to parse. + def jisx0301(string = '-4712-01-01T00:00:00+00:00', start = Date::ITALY, limit: 128) + hash = Date._jisx0301(string, limit: limit) + _dt_new_by_frags(hash, start) end - def xmlschema(string = JULIAN_EPOCH_DATETIME, start = Date::ITALY, limit: 128) - hash = _xmlschema(string, limit: limit) - dt_new_by_frags(hash, start) - end + private - def rfc2822(string = JULIAN_EPOCH_DATETIME_RFC2822, start = Date::ITALY, limit: 128) - hash = _rfc2822(string, limit: limit) - dt_new_by_frags(hash, start) + # Create a DateTime object from parsed fragment hash. + # Uses the same fragment rewrite/complete/validate logic as Date._new_by_frags + # but additionally extracts time components (hour, min, sec, offset, sec_fraction). + def _dt_new_by_frags(hash, sg) # rubocop:disable Metrics/MethodLength + raise Date::Error, 'invalid date' if hash.nil? + hash = _sp_rewrite_frags(hash) + orig_sec = hash[:sec] + hash = _sp_complete_frags(DateTime, hash) + jd = _sp_valid_date_frags_p(hash, sg) + raise Date::Error, 'invalid date' if jd.nil? + + h = hash[:hour] || 0 + m = hash[:min] || 0 + s = hash[:sec] || 0 + raise Date::Error, 'invalid date' if orig_sec && orig_sec > 60 + s = 59 if s > 59 + of = hash[:offset] || 0 + if of.is_a?(Numeric) && (of < -86400 || of > 86400) + warn("invalid offset is ignored: #{of}", uplevel: 0) + of = 0 + end + sf = hash[:sec_fraction] || Rational(0) + _new_dt_from_jd_time(jd, h, m, s, sf, of, sg) end - alias_method :rfc822, :rfc2822 - def httpdate(string = JULIAN_EPOCH_DATETIME_HTTPDATE, start = Date::ITALY, limit: 128) - hash = _httpdate(string, limit: limit) - dt_new_by_frags(hash, start) + def _parse_of(offset) + case offset + when String + Date.__send__(:_offset_str_to_sec, offset) + when Rational + (offset * 86400).to_i + when Numeric + (offset * 86400).to_i + else + 0 + end end - def jisx0301(string = JULIAN_EPOCH_DATETIME, start = Date::ITALY, limit: 128) - hash = _jisx0301(string, limit: limit) - dt_new_by_frags(hash, start) + def _split_sec(second) + if second.is_a?(Rational) || second.is_a?(Float) + s_r = second.to_r + s_i = s_r.floor + [s_i, s_r - s_i] + else + [Integer(second), Rational(0)] + end end - private + end - JULIAN_EPOCH_DATETIME = '-4712-01-01T00:00:00+00:00' - JULIAN_EPOCH_DATETIME_RFC2822 = 'Mon, 1 Jan -4712 00:00:00 +0000' - JULIAN_EPOCH_DATETIME_HTTPDATE = 'Mon, 01 Jan -4712 00:00:00 GMT' + # --------------------------------------------------------------------------- + # Private helpers (strftime overrides) + # --------------------------------------------------------------------------- - # C: offset_to_sec / val2off (class method version for use in class << self) - def _offset_to_sec(of) - case of - when Integer - of - when Rational - (of * 86400).to_i - when Float - (of * 86400).to_i - when String - if of.strip.upcase == 'Z' - 0 - elsif of =~ /\A([+-])(\d{1,2}):(\d{2})\z/ - sign = $1 == '-' ? -1 : 1 - sign * ($2.to_i * 3600 + $3.to_i * 60) - elsif of =~ /\A([+-])(\d{2})(\d{2})?\z/ - sign = $1 == '-' ? -1 : 1 - sign * ($2.to_i * 3600 + ($3 ? $3.to_i * 60 : 0)) - else - 0 - end - else - 0 - end - end + private - # C: dt_new_by_frags (date_core.c:8434) - # - # Structure matches C exactly: - # 1. Fast path: year+mon+mday present, no jd/yday - # - Validate civil, default time to 0, clamp sec==60 → 59 - # 2. Slow path: rt_rewrite_frags → rt_complete_frags → rt__valid_date_frags_p - # 3. Validate time (c_valid_time_p), handle sec_fraction, offset - # 4. Construct DateTime - def dt_new_by_frags(hash, sg) - raise Date::Error, "invalid date" if hash.nil? || hash.empty? - - # --- Fast path (C: lines 8447-8466) --- - if !hash.key?(:jd) && !hash.key?(:yday) && - hash[:year] && hash[:mon] && hash[:mday] - - y = hash[:year]; m = hash[:mon]; d = hash[:mday] - raise Date::Error, "invalid date" unless valid_civil?(y, m, d, sg) - - # C: default time fields, clamp sec==60 - hash[:hour] = 0 unless hash.key?(:hour) - hash[:min] = 0 unless hash.key?(:min) - if !hash.key?(:sec) - hash[:sec] = 0 - elsif hash[:sec] == 60 - hash[:sec] = 59 - end + def internal_hour + @hour + end - # --- Slow path (C: lines 8467-8470) --- - # rt_complete_frags needs DateTime as klass for time-only fill-in. - # rt__valid_date_frags_p needs Date for validation (calls ordinal/new). - else - hash = Date.send(:rt_rewrite_frags, hash) - hash = Date.send(:rt_complete_frags, self, hash) - jd_val = Date.send(:rt__valid_date_frags_p, hash, sg) - raise Date::Error, "invalid date" unless jd_val + def internal_min + @min + end - # Convert JD to civil for constructor - y, m, d = Date.send(:c_jd_to_civil, jd_val, sg) - end + def internal_sec + @sec_i + end - # --- Time validation (C: c_valid_time_p, lines 8473-8480) --- - h = hash[:hour] || 0 - min = hash[:min] || 0 - s = hash[:sec] || 0 - - # C: c_valid_time_p normalizes negative values and validates range. - rh = h < 0 ? h + 24 : h - rmin = min < 0 ? min + 60 : min - rs = s < 0 ? s + 60 : s - unless (0..24).cover?(rh) && (0..59).cover?(rmin) && (0..59).cover?(rs) && - !(rh == 24 && (rmin > 0 || rs > 0)) - raise Date::Error, "invalid date" - end + def _sec_frac + @sec_frac + end - # --- sec_fraction (C: lines 8482-8486) --- - sf = hash[:sec_fraction] - s_with_frac = sf ? rs + sf : rs + def _of_seconds + @of + end - # --- offset (C: lines 8488-8495) --- - of_sec = hash[:offset] || 0 - if of_sec.abs > 86400 - warn "invalid offset is ignored" - of_sec = 0 - end - of = Rational(of_sec, 86400) + def _zone_str + _of2str(@of) + end - # --- Construct DateTime --- - new(y, m, d, rh, rmin, s_with_frac, of, sg) - end + def _init_datetime(jd, h, m, s, sf, of, sg) + @jd = jd + @sg = sg + @hour = h + @min = m + @sec_i = s + @sec_frac = sf.is_a?(Rational) ? sf : Rational(sf) + @of = of.to_i end - private + def _split_second(second) + if second.is_a?(Rational) || second.is_a?(Float) + s_r = second.to_r + s_i = s_r.floor + [s_i, s_r - s_i] + else + [Integer(second), Rational(0)] + end + end - # Convert offset argument to integer seconds. - # Accepts: Integer (seconds), Rational (fraction of day), String ("+HH:MM"), 0 - # C: offset_to_sec / val2off - def offset_to_sec(of) - case of - when Integer - of - when Float - # Fraction of day to seconds - (of * DAY_IN_SECONDS).to_i - when Rational - # Fraction of day to seconds - (of * DAY_IN_SECONDS).to_i + def _str_offset_to_sec(offset) + case offset when String - if of.strip.upcase == 'Z' - 0 - elsif of =~ /\A([+-])(\d{2}):(\d{2})\z/ - sign = $1 == '-' ? -1 : 1 - sign * ($2.to_i * HOUR_IN_SECONDS + $3.to_i * MINUTE_IN_SECONDS) - elsif of =~ /\A([+-])(\d{2})(\d{2})?\z/ - sign = $1 == '-' ? -1 : 1 - sign * ($2.to_i * HOUR_IN_SECONDS + ($3 ? $3.to_i * MINUTE_IN_SECONDS : 0)) - else - 0 - end + self.class.__send__(:_parse_of, offset) + when Rational + (offset * 86400).to_i + when Numeric + r = offset.to_r + raise TypeError, "#{offset.class} can't be used as offset" unless r.is_a?(Rational) + (r * 86400).to_i else 0 end end - # Validate time fields (C: c_valid_time_p) - def validate_time(h, min, s) - h += 24 if h < 0 - min += 60 if min < 0 - s += 60 if s < 0 - unless (0..24).cover?(h) && (0..59).cover?(min) && (0..59).cover?(s) && - !(h == 24 && (min > 0 || s > 0)) - raise Error, "invalid date" - end - [h, min, s] + def _of2str(of) + sign = of < 0 ? '-' : '+' + abs = of.abs + h = abs / 3600 + m = (abs % 3600) / 60 + format('%s%02d:%02d'.encode(Encoding::US_ASCII), sign, h, m) + end + + def _from_total_sec_r(total_r) + jd = (total_r / 86400).floor + rem = total_r - jd * 86400 + h = rem.to_i / 3600 + rem -= h * 3600 + m = rem.to_i / 60 + s_r = rem - m * 60 + s_i = s_r.floor + s_f = s_r - s_i + self.class.__send__(:_new_dt_from_jd_time,jd, h, m, s_i, s_f, @of, @sg) end + end diff --git a/lib/date/parse.rb b/lib/date/parse.rb index e560b3bb..682f6b40 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -1,99 +1,123 @@ # frozen_string_literal: true -require_relative "patterns" require_relative "zonetab" -# Implementation of ruby/date/ext/date/date_parse.c class Date class << self - # call-seq: - # Date.parse(string = '-4712-01-01', comp = true, start = Date::ITALY, limit: 128) -> date - # - # Returns a new \Date object with values parsed from +string+. - # - # If +comp+ is +true+ and the given year is in the range (0..99), - # the current century is supplied; otherwise, the year is taken as given. - # - # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - # See argument {limit}[rdoc-ref:Date@Argument+limit]. - # - # Related: Date._parse (returns a hash). - def parse(string = JULIAN_EPOCH_DATE, comp = true, start = DEFAULT_SG, limit: 128) - hash = _parse(string, comp, limit: limit) - new_by_frags(hash, start) - end - - # call-seq: - # Date._parse(string, comp = true, limit: 128) -> hash - # - # Returns a hash of values parsed from +string+. - # - # If +comp+ is +true+ and the given year is in the range (0..99), - # the current century is supplied; otherwise, the year is taken as given. - # - # See argument {limit}[rdoc-ref:Date@Argument+limit]. - # - # Related: Date.parse (returns a \Date object). - def _parse(string, comp = true, limit: 128) - string = string_value(string) - str = string.strip - # Check limit - if limit && str.length > limit - raise ArgumentError, "string length (#{str.length}) exceeds the limit #{limit}" - end - - date__parse(str, comp) - end + # ------------------------------------------------------------------ + # _rfc3339 + # ------------------------------------------------------------------ # call-seq: - # Date._iso8601(string, limit: 128) -> hash + # Date._rfc3339(string, limit: 128) -> hash # - # Returns a hash of values parsed from +string+, which should contain - # an {ISO 8601 formatted date}[rdoc-ref:language/strftime_formatting.rdoc@ISO+8601+Format+Specifications]: + # Returns a hash of values parsed from +string+, which should be a valid + # {RFC 3339 format}[rdoc-ref:language/strftime_formatting.rdoc@RFC+3339+Format]: # # d = Date.new(2001, 2, 3) - # s = d.iso8601 # => "2001-02-03" - # Date._iso8601(s) # => {:mday=>3, :year=>2001, :mon=>2} + # s = d.rfc3339 # => "2001-02-03T00:00:00+00:00" + # Date._rfc3339(s) + # # => {:year=>2001, :mon=>2, :mday=>3, :hour=>0, :min=>0, :sec=>0, :zone=>"+00:00", :offset=>0} # # See argument {limit}[rdoc-ref:Date@Argument+limit]. # - # Related: Date.iso8601 (returns a \Date object). - def _iso8601(string, limit: 128) - return {} if string.nil? - string = string_value(string) - check_string_limit(string, limit) - - date__iso8601(string) - end - - # date__rfc3339 in date_parse.c + # Related: Date.rfc3339 (returns a \Date object). def _rfc3339(string, limit: 128) - return {} if string.nil? - string = string_value(string) - check_string_limit(string, limit) - - date__rfc3339(string) - end - - # date__xmlschema in date_parse.c - def _xmlschema(string, limit: 128) - return {} if string.nil? - string = string_value(string) - check_string_limit(string, limit) + unless String === string + raise TypeError if string.is_a?(Symbol) + return {} if string.nil? + string = string.to_str + end + return {} if string.empty? + raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit + + # Fast path: YYYY-MM-DDTHH:MM:SS+HH:MM (25 bytes) or YYYY-MM-DDTHH:MM:SSZ (20 bytes) + len = string.length + if len == 25 || len == 20 + b0 = string.getbyte(0) + if b0 >= 48 && b0 <= 57 && + string.getbyte(4) == 45 && string.getbyte(7) == 45 && + (string.getbyte(10) | 32) == 116 && # T or t + string.getbyte(13) == 58 && string.getbyte(16) == 58 + b1 = string.getbyte(1) + b2 = string.getbyte(2) + b3 = string.getbyte(3) + b5 = string.getbyte(5) + b6 = string.getbyte(6) + b8 = string.getbyte(8) + b9 = string.getbyte(9) + b11 = string.getbyte(11) + b12 = string.getbyte(12) + b14 = string.getbyte(14) + b15 = string.getbyte(15) + b17 = string.getbyte(17) + b18 = string.getbyte(18) + if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && + b5 >= 48 && b5 <= 57 && b6 >= 48 && b6 <= 57 && + b8 >= 48 && b8 <= 57 && b9 >= 48 && b9 <= 57 && + b11 >= 48 && b11 <= 57 && b12 >= 48 && b12 <= 57 && + b14 >= 48 && b14 <= 57 && b15 >= 48 && b15 <= 57 && + b17 >= 48 && b17 <= 57 && b18 >= 48 && b18 <= 57 + h = { + year: (b0 - 48) * 1000 + (b1 - 48) * 100 + (b2 - 48) * 10 + (b3 - 48), + mon: (b5 - 48) * 10 + (b6 - 48), + mday: (b8 - 48) * 10 + (b9 - 48), + hour: (b11 - 48) * 10 + (b12 - 48), + min: (b14 - 48) * 10 + (b15 - 48), + sec: (b17 - 48) * 10 + (b18 - 48) + } + b19 = string.getbyte(19) + if (b19 == 90 || b19 == 122) && len == 20 # Z or z + h[:zone] = string[19, 1] + h[:offset] = 0 + elsif (b19 == 43 || b19 == 45) && len == 25 && string.getbyte(22) == 58 + zone = string[19, 6] + h[:zone] = zone + b20 = string.getbyte(20) + b21 = string.getbyte(21) + b23 = string.getbyte(23) + b24 = string.getbyte(24) + if b20 >= 48 && b20 <= 57 && b21 >= 48 && b21 <= 57 && + b23 >= 48 && b23 <= 57 && b24 >= 48 && b24 <= 57 + h[:offset] = (b19 == 45 ? -1 : 1) * ((b20 - 48) * 36000 + (b21 - 48) * 3600 + (b23 - 48) * 600 + (b24 - 48) * 60) + return h + end + end + return h if h.key?(:zone) + end + end + end - date__xmlschema(string) + h = {} + if (m = RFC3339_RE.match(string)) + h[:year] = m[1].to_i + s = m[2] + h[:mon] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + s = m[3] + h[:mday] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + s = m[4] + h[:hour] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + s = m[5] + h[:min] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + s = m[6] + h[:sec] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + h[:sec_fraction] = Rational(m[7].to_i, 10 ** m[7].length) if m[7] + zone = m[8] + h[:zone] = zone + b0 = zone.getbyte(0) + if b0 == 90 || b0 == 122 # Z or z + h[:offset] = 0 + else + h[:offset] = (b0 == 45 ? -1 : 1) * ((zone.getbyte(1) - 48) * 36000 + (zone.getbyte(2) - 48) * 3600 + (zone.getbyte(4) - 48) * 600 + (zone.getbyte(5) - 48) * 60) + end + end + h end - # date__rfc2822 in date_parse.c - def _rfc2822(string, limit: 128) - return {} if string.nil? - string = string_value(string) - check_string_limit(string, limit) - - date__rfc2822(string) - end - alias _rfc822 _rfc2822 + # ------------------------------------------------------------------ + # _httpdate + # ------------------------------------------------------------------ # call-seq: # Date._httpdate(string, limit: 128) -> hash @@ -108,2497 +132,1572 @@ def _rfc2822(string, limit: 128) # # Related: Date.httpdate (returns a \Date object). def _httpdate(string, limit: 128) - return {} if string.nil? - string = string_value(string) - check_string_limit(string, limit) + unless String === string + raise TypeError if string.is_a?(Symbol) + return {} if string.nil? + string = string.to_str + end + return {} if string.empty? + raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit + + # Byte-level fast path for Type 1: "Dow, DD Mon YYYY HH:MM:SS GMT" (29 bytes) + # Avoids all regex and string allocation overhead + len = string.length + if len == 29 + b0 = string.getbyte(0) + if b0 >= 65 && string.getbyte(3) == 44 && string.getbyte(4) == 32 && # alpha, ',', ' ' + string.getbyte(7) == 32 && string.getbyte(11) == 32 && + string.getbyte(16) == 32 && string.getbyte(19) == 58 && + string.getbyte(22) == 58 && string.getbyte(25) == 32 && + string.getbyte(26) == 71 && string.getbyte(27) == 77 && string.getbyte(28) == 84 # 'G','M','T' + wkey = ((b0 | 32) << 16) | ((string.getbyte(1) | 32) << 8) | (string.getbyte(2) | 32) + wday_info = ABBR_DAY_3KEY[wkey] + if wday_info + mkey = ((string.getbyte(8) | 32) << 16) | ((string.getbyte(9) | 32) << 8) | (string.getbyte(10) | 32) + mon_info = ABBR_MONTH_3KEY[mkey] + if mon_info + return { + wday: wday_info[0], + mday: (string.getbyte(5) - 48) * 10 + (string.getbyte(6) - 48), + mon: mon_info[0], + year: (string.getbyte(12) - 48) * 1000 + (string.getbyte(13) - 48) * 100 + (string.getbyte(14) - 48) * 10 + (string.getbyte(15) - 48), + hour: (string.getbyte(17) - 48) * 10 + (string.getbyte(18) - 48), + min: (string.getbyte(20) - 48) * 10 + (string.getbyte(21) - 48), + sec: (string.getbyte(23) - 48) * 10 + (string.getbyte(24) - 48), + zone: 'GMT', offset: 0 + } + end + end + end + end - date__httpdate(string) - end + h = {} + if (m = HTTPDATE_TYPE1_RE.match(string)) + h[:wday] = HTTPDATE_WDAY[m[1].downcase] + s = m[2] + h[:mday] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + h[:mon] = ABBR_MONTH_NUM[m[3].downcase] + h[:year] = m[4].to_i + s = m[5] + h[:hour] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + s = m[6] + h[:min] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + s = m[7] + h[:sec] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + h[:zone] = m[8] + h[:offset] = 0 + elsif (m = HTTPDATE_TYPE2_RE.match(string)) + h[:wday] = HTTPDATE_FULL_WDAY[m[1].downcase] + s = m[2] + h[:mday] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + h[:mon] = ABBR_MONTH_NUM[m[3].downcase] + y = m[4].to_i + h[:year] = y >= 69 ? y + 1900 : y + 2000 + s = m[5] + h[:hour] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + s = m[6] + h[:min] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + s = m[7] + h[:sec] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + h[:zone] = m[8] + h[:offset] = 0 + elsif (m = HTTPDATE_TYPE3_RE.match(string)) + h[:wday] = HTTPDATE_WDAY[m[1].downcase] + h[:mon] = ABBR_MONTH_NUM[m[2].downcase] + h[:mday] = m[3].to_i + s = m[4] + h[:hour] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + s = m[5] + h[:min] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + s = m[6] + h[:sec] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + h[:year] = m[7].to_i + end + h + end + + # ------------------------------------------------------------------ + # _rfc2822 + # ------------------------------------------------------------------ # call-seq: - # Date._jisx0301(string, limit: 128) -> hash + # Date._rfc2822(string, limit: 128) -> hash # # Returns a hash of values parsed from +string+, which should be a valid - # {JIS X 0301 date format}[rdoc-ref:language/strftime_formatting.rdoc@JIS+X+0301+Format]: + # {RFC 2822 date format}[rdoc-ref:language/strftime_formatting.rdoc@RFC+2822+Format]: # # d = Date.new(2001, 2, 3) - # s = d.jisx0301 # => "H13.02.03" - # Date._jisx0301(s) # => {:year=>2001, :mon=>2, :mday=>3} + # s = d.rfc2822 # => "Sat, 3 Feb 2001 00:00:00 +0000" + # Date._rfc2822(s) + # # => {:wday=>6, :mday=>3, :mon=>2, :year=>2001, :hour=>0, :min=>0, :sec=>0, :zone=>"+0000", :offset=>0} # # See argument {limit}[rdoc-ref:Date@Argument+limit]. # - # Related: Date.jisx0301 (returns a \Date object). - def _jisx0301(string, limit: 128) - return {} if string.nil? - string = string_value(string) - check_string_limit(string, limit) - - date__jisx0301(string) - end - - # --- Constructor methods --- - - def iso8601(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) - hash = _iso8601(string, limit: limit) - - new_by_frags(hash, start) - end - - def rfc3339(string = JULIAN_EPOCH_DATETIME, start = DEFAULT_SG, limit: 128) - hash = _rfc3339(string, limit: limit) - - new_by_frags(hash, start) - end - - def xmlschema(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) - hash = _xmlschema(string, limit: limit) - - new_by_frags(hash, start) - end - - def rfc2822(string = JULIAN_EPOCH_DATETIME_RFC2822, start = DEFAULT_SG, limit: 128) - hash = _rfc2822(string, limit: limit) - - new_by_frags(hash, start) - end - alias rfc822 rfc2822 - - def httpdate(string = JULIAN_EPOCH_DATETIME_HTTPDATE, start = DEFAULT_SG, limit: 128) - hash = _httpdate(string, limit: limit) - - new_by_frags(hash, start) - end - - def jisx0301(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) - hash = _jisx0301(string, limit: limit) - - new_by_frags(hash, start) - end - - private - - def date__parse(str, comp) - hash = {} - - # Preprocessing: duplicate and replace non-allowed characters. - # Non-TIGHT: Replace [^-+',./:@[:alnum:]\[\]]+ with a single space - str = str.dup.gsub(%r{[^-+',./:@[:alnum:]\[\]]+}, ' ') - - hash[:_comp] = comp - - # Parser invocation (non-TIGHT order) - # Note: C's HAVE_ELEM_P calls check_class(str) every time because - # str is modified by subx after each successful parse. - - # parse_day and parse_time always run (no goto ok). - if have_elem_p?(str, HAVE_ALPHA) - parse_day(str, hash) - end - - if have_elem_p?(str, HAVE_DIGIT) - parse_time(str, hash) - end - - # Date parsers: first success skips the rest (C's "goto ok"). - # In C, all paths converge at ok: for post-processing. - catch(:date_parsed) do - if have_elem_p?(str, HAVE_ALPHA | HAVE_DIGIT) - throw :date_parsed if parse_eu(str, hash) - throw :date_parsed if parse_us(str, hash) - end - - if have_elem_p?(str, HAVE_DIGIT | HAVE_DASH) - throw :date_parsed if parse_iso(str, hash) - end - - if have_elem_p?(str, HAVE_DIGIT | HAVE_DOT) - throw :date_parsed if parse_jis(str, hash) - end - - if have_elem_p?(str, HAVE_ALPHA | HAVE_DIGIT | HAVE_DASH) - throw :date_parsed if parse_vms(str, hash) - end - - if have_elem_p?(str, HAVE_DIGIT | HAVE_SLASH) - throw :date_parsed if parse_sla(str, hash) - end - - if have_elem_p?(str, HAVE_DIGIT | HAVE_DOT) - throw :date_parsed if parse_dot(str, hash) - end - - if have_elem_p?(str, HAVE_DIGIT) - throw :date_parsed if parse_iso2(str, hash) + # Related: Date.rfc2822 (returns a \Date object). + def _rfc2822(string, limit: 128) + unless String === string + raise TypeError if string.is_a?(Symbol) + return {} if string.nil? + string = string.to_str + end + return {} if string.empty? + raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit + + # Byte-level fast path: "Dow, DD Mon YYYY HH:MM:SS +ZZZZ" (31 bytes, 2-digit day) + # Avoids all regex and string allocation overhead + len = string.length + if len == 31 + b0 = string.getbyte(0) + if b0 >= 65 && string.getbyte(3) == 44 && string.getbyte(4) == 32 && # alpha, ',', ' ' + string.getbyte(7) == 32 && string.getbyte(11) == 32 && + string.getbyte(16) == 32 && string.getbyte(19) == 58 && + string.getbyte(22) == 58 && string.getbyte(25) == 32 + bz0 = string.getbyte(26) + if bz0 == 43 || bz0 == 45 # '+' or '-' + wkey = ((b0 | 32) << 16) | ((string.getbyte(1) | 32) << 8) | (string.getbyte(2) | 32) + wday_info = ABBR_DAY_3KEY[wkey] + if wday_info + mkey = ((string.getbyte(8) | 32) << 16) | ((string.getbyte(9) | 32) << 8) | (string.getbyte(10) | 32) + mon_info = ABBR_MONTH_3KEY[mkey] + if mon_info + bz1 = string.getbyte(27) + bz2 = string.getbyte(28) + bz3 = string.getbyte(29) + bz4 = string.getbyte(30) + sign = bz0 == 45 ? -1 : 1 + offset_val = sign * ((bz1 - 48) * 36000 + (bz2 - 48) * 3600 + (bz3 - 48) * 600 + (bz4 - 48) * 60) + zone = (bz0 == 43 && bz1 == 48 && bz2 == 48 && bz3 == 48 && bz4 == 48) ? '+0000' : string.byteslice(26, 5) + return { + wday: wday_info[0], + mday: (string.getbyte(5) - 48) * 10 + (string.getbyte(6) - 48), + mon: mon_info[0], + year: (string.getbyte(12) - 48) * 1000 + (string.getbyte(13) - 48) * 100 + (string.getbyte(14) - 48) * 10 + (string.getbyte(15) - 48), + hour: (string.getbyte(17) - 48) * 10 + (string.getbyte(18) - 48), + min: (string.getbyte(20) - 48) * 10 + (string.getbyte(21) - 48), + sec: (string.getbyte(23) - 48) * 10 + (string.getbyte(24) - 48), + zone: zone, offset: offset_val + } + end + end + end end + end - if have_elem_p?(str, HAVE_DIGIT) - throw :date_parsed if parse_year(str, hash) + # Preprocess: remove obs-FWS (\r\n and \0) - skip if not needed + s = (string.include?("\r") || string.include?("\n") || string.include?("\0")) ? + string.gsub(/[\r\n\0]+/, ' ') : string + h = {} + if (m = RFC2822_RE.match(s)) + h[:wday] = HTTPDATE_WDAY[m[1].downcase] if m[1] + h[:mday] = m[2].to_i + h[:mon] = ABBR_MONTH_NUM[m[3].downcase] + y_s = m[4] + y = y_s.to_i + ylen = y_s.getbyte(0) == 45 ? y_s.length - 1 : y_s.length + if ylen < 4 + if ylen == 3 + h[:year] = y + 1900 + else + h[:year] = y >= 50 ? y + 1900 : y + 2000 + end + else + h[:year] = y end - - if have_elem_p?(str, HAVE_ALPHA) - throw :date_parsed if parse_mon(str, hash) + s5 = m[5] + h[:hour] = (s5.getbyte(0) - 48) * 10 + (s5.getbyte(1) - 48) + s6 = m[6] + h[:min] = (s6.getbyte(0) - 48) * 10 + (s6.getbyte(1) - 48) + if m[7] + s7 = m[7] + h[:sec] = (s7.getbyte(0) - 48) * 10 + (s7.getbyte(1) - 48) end + h[:zone] = m[8] + h[:offset] = fast_zone_offset(m[8]) + end + h + end + alias _rfc822 _rfc2822 - if have_elem_p?(str, HAVE_DIGIT) - throw :date_parsed if parse_mday(str, hash) - end + # ------------------------------------------------------------------ + # _xmlschema + # ------------------------------------------------------------------ - if have_elem_p?(str, HAVE_DIGIT) - throw :date_parsed if parse_ddd(str, hash) + # call-seq: + # Date._xmlschema(string, limit: 128) -> hash + # + # Returns a hash of values parsed from +string+, which should be a valid + # XML date format: + # + # d = Date.new(2001, 2, 3) + # s = d.xmlschema # => "2001-02-03" + # Date._xmlschema(s) # => {:year=>2001, :mon=>2, :mday=>3} + # + # See argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date.xmlschema (returns a \Date object). + def _xmlschema(string, limit: 128) + unless String === string + raise TypeError if string.is_a?(Symbol) + return {} if string.nil? + string = string.to_str + end + return {} if string.empty? + raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit + + # Fast path: YYYY-MM-DD (exactly 10 bytes, all ASCII) + if string.length == 10 + b0 = string.getbyte(0) + if b0 >= 48 && b0 <= 57 + b1 = string.getbyte(1) + b2 = string.getbyte(2) + b3 = string.getbyte(3) + if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && + string.getbyte(4) == 45 && string.getbyte(7) == 45 + b5 = string.getbyte(5) + b6 = string.getbyte(6) + b8 = string.getbyte(8) + b9 = string.getbyte(9) + if b5 >= 48 && b5 <= 57 && b6 >= 48 && b6 <= 57 && + b8 >= 48 && b8 <= 57 && b9 >= 48 && b9 <= 57 + return { + year: (b0 - 48) * 1000 + (b1 - 48) * 100 + (b2 - 48) * 10 + (b3 - 48), + mon: (b5 - 48) * 10 + (b6 - 48), + mday: (b8 - 48) * 10 + (b9 - 48) + } + end + end end end - # ok: (post-processing — always runs, matching C's ok: label) - if have_elem_p?(str, HAVE_ALPHA) - parse_bc(str, hash) - end - if have_elem_p?(str, HAVE_DIGIT) - parse_frag(str, hash) + h = {} + if (m = XMLSCHEMA_DATETIME_RE.match(string)) + h[:year] = m[1].to_i + h[:mon] = m[2].to_i if m[2] + h[:mday] = m[3].to_i if m[3] + h[:hour] = m[4].to_i if m[4] + h[:min] = m[5].to_i if m[5] + h[:sec] = m[6].to_i if m[6] + h[:sec_fraction] = parse_sec_fraction(m[7]) if m[7] + parse_zone_and_offset(m[8], h) if m[8] + elsif (m = XMLSCHEMA_TIME_RE.match(string)) + h[:hour] = m[1].to_i + h[:min] = m[2].to_i + h[:sec] = m[3].to_i + h[:sec_fraction] = parse_sec_fraction(m[4]) if m[4] + parse_zone_and_offset(m[5], h) if m[5] + elsif (m = XMLSCHEMA_TRUNC_RE.match(string)) + if m[3] + h[:mday] = m[3].to_i + else + h[:mon] = m[1].to_i if m[1] + h[:mday] = m[2].to_i if m[2] + end + parse_zone_and_offset(m[4], h) if m[4] end - - apply_comp(hash) - hash - end - - # asctime format with timezone: Sat Aug 28 02:29:34 JST 1999 - def parse_asctime_with_zone(str, hash) - return false unless str =~ /\b(sun|mon|tue|wed|thu|fri|sat)[[:space:]]+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)[[:space:]]+(\d{1,2})[[:space:]]+(\d{2}):(\d{2}):(\d{2})[[:space:]]+(.*?)[[:space:]]+(-?\d+)[[:space:]]*$/i - - wday_str = $1 - mon_str = $2 - mday_str = $3 - hour_str = $4 - min_str = $5 - sec_str = $6 - zone_part = $7 - year_str = $8 - - hash[:wday] = day_num(wday_str) - hash[:mon] = mon_num(mon_str) - hash[:mday] = mday_str.to_i - hash[:hour] = hour_str.to_i - hash[:min] = min_str.to_i - hash[:sec] = sec_str.to_i - - zone_part = zone_part.strip - unless zone_part.empty? - zone = zone_part.gsub(/\s+/, ' ') - hash[:zone] = zone - hash[:offset] = parse_zone_offset(zone) - end - - hash[:_year_str] = year_str - hash[:year] = year_str.to_i - apply_comp(hash) - - true + h end - # asctime format without timezone: Sat Aug 28 02:55:50 1999 - def parse_asctime(str, hash) - return false unless str =~ /\b(sun|mon|tue|wed|thu|fri|sat)\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})\s+(-?\d+)\s*$/i - - wday_str = $1 - mon_str = $2 - mday_str = $3 - hour_str = $4 - min_str = $5 - sec_str = $6 - year_str = $7 - - hash[:wday] = day_num(wday_str) - hash[:mon] = mon_num(mon_str) - hash[:mday] = mday_str.to_i - hash[:hour] = hour_str.to_i - hash[:min] = min_str.to_i - hash[:sec] = sec_str.to_i - hash[:_year_str] = year_str - hash[:year] = year_str.to_i - apply_comp(hash) - - true - end - - # HTTP date type 1: "Sat, 03 Feb 2001 00:00:00 GMT" - def httpdate_type1(str, hash) - pattern = /\A\s*(#{ABBR_DAYS_PATTERN})\s*,\s+ - (\d{2})\s+ - (#{ABBR_MONTHS_PATTERN})\s+ - (-?\d{4})\s+ - (\d{2}):(\d{2}):(\d{2})\s+ - (gmt)\s*\z/ix - - match = pattern.match(str) - return false unless match - - hash[:wday] = day_num(match[1]) - hash[:mday] = match[2].to_i - hash[:mon] = mon_num(match[3]) - hash[:year] = match[4].to_i - hash[:hour] = match[5].to_i - hash[:min] = match[6].to_i - hash[:sec] = match[7].to_i - hash[:zone] = match[8] - hash[:offset] = 0 - - true - end + # ------------------------------------------------------------------ + # _iso8601 + # ------------------------------------------------------------------ - # HTTP date type 2: "Saturday, 03-Feb-01 00:00:00 GMT" - def httpdate_type2(str, hash) - pattern = /\A\s*(#{DAYS_PATTERN})\s*,\s+ - (\d{2})\s*-\s* - (#{ABBR_MONTHS_PATTERN})\s*-\s* - (\d{2})\s+ - (\d{2}):(\d{2}):(\d{2})\s+ - (gmt)\s*\z/ix - - match = pattern.match(str) - return false unless match - - hash[:wday] = day_num(match[1]) - hash[:mday] = match[2].to_i - hash[:mon] = mon_num(match[3]) - - # Year completion for 2-digit year - year = match[4].to_i - year = comp_year69(year) if year >= 0 && year <= 99 - hash[:year] = year - - hash[:hour] = match[5].to_i - hash[:min] = match[6].to_i - hash[:sec] = match[7].to_i - hash[:zone] = match[8] - hash[:offset] = 0 - - true - end - - # HTTP date type 3: "Sat Feb 3 00:00:00 2001" - def httpdate_type3(str, hash) - pattern = /\A\s*(#{ABBR_DAYS_PATTERN})\s+ - (#{ABBR_MONTHS_PATTERN})\s+ - (\d{1,2})\s+ - (\d{2}):(\d{2}):(\d{2})\s+ - (\d{4})\s*\z/ix - - match = pattern.match(str) - return false unless match - - hash[:wday] = day_num(match[1]) - hash[:mon] = mon_num(match[2]) - hash[:mday] = match[3].to_i - hash[:hour] = match[4].to_i - hash[:min] = match[5].to_i - hash[:sec] = match[6].to_i - hash[:year] = match[7].to_i - - true - end - - # parse_day in date_parse.c. - # Non-TIGHT pattern: \b(sun|mon|tue|wed|thu|fri|sat)[^-/\d\s]* - # The [^-/\d\s]* part consumes trailing characters (e.g., "urday" - # in "Saturday") so they get replaced by subx, but only the - # abbreviation in $1 is used. - def parse_day(str, hash) - m = subx(str, PARSE_DAY_PAT) - return false unless m - - hash[:wday] = day_num(m[1]) - - true - end - - # parse_time in date_parse.c. - # Uses subx to replace the matched time portion with " " so - # subsequent parsers (parse_us, etc.) won't re-match it. - def parse_time(str, hash) - m = subx(str, TIME_PAT) - return false unless m - - time_str = m[1] - zone_str = m[2] + # call-seq: + # Date._iso8601(string, limit: 128) -> hash + # + # Returns a hash of values parsed from +string+, which should contain + # an {ISO 8601 formatted date}[rdoc-ref:language/strftime_formatting.rdoc@ISO+8601+Format+Specifications]: + # + # d = Date.new(2001, 2, 3) + # s = d.iso8601 # => "2001-02-03" + # Date._iso8601(s) # => {:mday=>3, :year=>2001, :mon=>2} + # + # See argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date.iso8601 (returns a \Date object). + def _iso8601(string, limit: 128) + unless String === string + raise TypeError if string.is_a?(Symbol) + return {} if string.nil? + string = string.to_str + end + return {} if string.empty? + raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit + + # Fast path: YYYY-MM-DD (exactly 10 bytes, all ASCII) + if string.length == 10 + b0 = string.getbyte(0) + if b0 >= 48 && b0 <= 57 + b1 = string.getbyte(1) + b2 = string.getbyte(2) + b3 = string.getbyte(3) + if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && + string.getbyte(4) == 45 && string.getbyte(7) == 45 + b5 = string.getbyte(5) + b6 = string.getbyte(6) + b8 = string.getbyte(8) + b9 = string.getbyte(9) + if b5 >= 48 && b5 <= 57 && b6 >= 48 && b6 <= 57 && + b8 >= 48 && b8 <= 57 && b9 >= 48 && b9 <= 57 + return { + mday: (b8 - 48) * 10 + (b9 - 48), + year: (b0 - 48) * 1000 + (b1 - 48) * 100 + (b2 - 48) * 10 + (b3 - 48), + mon: (b5 - 48) * 10 + (b6 - 48) + } + end + end + end + end - parse_time_detail(time_str, hash) + h = {} - if zone_str && !zone_str.empty? - hash[:zone] = zone_str - hash[:offset] = date_zone_to_diff(zone_str) + if (m = ISO8601_EXT_DATETIME_RE.match(string)) + iso8601_ext_datetime(m, h) + elsif (m = ISO8601_BAS_DATETIME_RE.match(string)) + iso8601_bas_datetime(m, h) + elsif (m = ISO8601_EXT_TIME_RE.match(string)) + h[:hour] = m[1].to_i + h[:min] = m[2].to_i + h[:sec] = m[3].to_i if m[3] + h[:sec_fraction] = parse_sec_fraction(m[4]) if m[4] + parse_zone_and_offset(m[5], h) if m[5] + elsif (m = ISO8601_BAS_TIME_RE.match(string)) + h[:hour] = m[1].to_i + h[:min] = m[2].to_i + h[:sec] = m[3].to_i if m[3] + h[:sec_fraction] = parse_sec_fraction(m[4]) if m[4] + parse_zone_and_offset(m[5], h) if m[5] end - - true + h end - # parse_ddd in date_parse.c. - def parse_ddd(str, hash) - m = subx(str, PARSE_DDD_PAT) - return false unless m - - sign = m[1] - digits = m[2] - time_digits = m[3] - fraction = m[4] - zone = m[5] + # ------------------------------------------------------------------ + # _jisx0301 + # ------------------------------------------------------------------ - l = digits.length - - # Branches based on the length of the main number string. - case l - when 2 - if time_digits.nil? && !fraction.nil? - hash[:sec] = digits[-2, 2].to_i - else - hash[:mday] = digits[0, 2].to_i - end - when 4 - if time_digits.nil? && !fraction.nil? - hash[:sec] = digits[-2, 2].to_i - hash[:min] = digits[-4, 2].to_i - else - hash[:mon] = digits[0, 2].to_i - hash[:mday] = digits[2, 2].to_i - end - when 6 - if time_digits.nil? && !fraction.nil? - hash[:sec] = digits[-2, 2].to_i - hash[:min] = digits[-4, 2].to_i - hash[:hour] = digits[-6, 2].to_i - else - y = digits[0, 2].to_i - y = -y if sign == '-' - hash[:year] = y - hash[:mon] = digits[2, 2].to_i - hash[:mday] = digits[4, 2].to_i - hash[:_year_str] = digits[0, 2] # year completion - end - when 8, 10, 12, 14 - if time_digits.nil? && !fraction.nil? - # Interpreted as time - hash[:sec] = digits[-2, 2].to_i - hash[:min] = digits[-4, 2].to_i - hash[:hour] = digits[-6, 2].to_i - hash[:mday] = digits[-8, 2].to_i - hash[:mon] = digits[-10, 2].to_i if l >= 10 - if l == 12 - y = digits[-12, 2].to_i - y = -y if sign == '-' - hash[:year] = y - hash[:_year_str] = digits[-12, 2] - elsif l == 14 - y = digits[-14, 4].to_i - y = -y if sign == '-' - hash[:year] = y - hash[:_comp] = false + # call-seq: + # Date._jisx0301(string, limit: 128) -> hash + # + # Returns a hash of values parsed from +string+, which should be a valid + # {JIS X 0301 date format}[rdoc-ref:language/strftime_formatting.rdoc@JIS+X+0301+Format]: + # + # d = Date.new(2001, 2, 3) + # s = d.jisx0301 # => "H13.02.03" + # Date._jisx0301(s) # => {:year=>2001, :mon=>2, :mday=>3} + # + # See argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date.jisx0301 (returns a \Date object). + def _jisx0301(string, limit: 128) + unless String === string + raise TypeError if string.is_a?(Symbol) + return {} if string.nil? + string = string.to_str + end + return {} if string.empty? + raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit + + # Fast path: X##.##.## (9 bytes: era + YY.MM.DD) + if string.length == 9 + b0 = string.getbyte(0) | 32 # downcase + era_offset = JISX0301_ERA[b0.chr] + if era_offset && + string.getbyte(3) == 46 && string.getbyte(6) == 46 # '.' + b1 = string.getbyte(1) + b2 = string.getbyte(2) + b4 = string.getbyte(4) + b5 = string.getbyte(5) + b7 = string.getbyte(7) + b8 = string.getbyte(8) + if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && + b4 >= 48 && b4 <= 57 && b5 >= 48 && b5 <= 57 && + b7 >= 48 && b7 <= 57 && b8 >= 48 && b8 <= 57 + return { + year: (b1 - 48) * 10 + (b2 - 48) + era_offset, + mon: (b4 - 48) * 10 + (b5 - 48), + mday: (b7 - 48) * 10 + (b8 - 48) + } end - else - # Interpret as date - y = digits[0, 4].to_i - y = -y if sign == '-' - hash[:year] = y - hash[:mon] = digits[4, 2].to_i - hash[:mday] = digits[6, 2].to_i - hash[:hour] = digits[8, 2].to_i if l >= 10 - hash[:min] = digits[10, 2].to_i if l >= 12 - hash[:sec] = digits[12, 2].to_i if l >= 14 - hash[:_comp] = false - end - when 3 - if time_digits.nil? && !fraction.nil? - hash[:sec] = digits[-2, 2].to_i - hash[:min] = digits[-3, 1].to_i - else - hash[:yday] = digits[0, 3].to_i - end - when 5 - if time_digits.nil? && !fraction.nil? - hash[:sec] = digits[-2, 2].to_i - hash[:min] = digits[-4, 2].to_i - hash[:hour] = digits[-5, 1].to_i - else - y = digits[0, 2].to_i - y = -y if sign == '-' - hash[:year] = y - hash[:yday] = digits[2, 3].to_i - hash[:_year_str] = digits[0, 2] - end - when 7 - if time_digits.nil? && !fraction.nil? - hash[:sec] = digits[-2, 2].to_i - hash[:min] = digits[-4, 2].to_i - hash[:hour] = digits[-6, 2].to_i - hash[:mday] = digits[-7, 1].to_i - else - y = digits[0, 4].to_i - y = -y if sign == '-' - hash[:year] = y - hash[:yday] = digits[4, 3].to_i - # No need to complete because it is a 4-digit year end end - # Processing time portion - if time_digits && !time_digits.empty? - tl = time_digits.length - if !fraction.nil? - # Interpreted as time - case tl - when 2, 4, 6 - hash[:sec] = time_digits[-2, 2].to_i - hash[:min] = time_digits[-4, 2].to_i if tl >= 4 - hash[:hour] = time_digits[-6, 2].to_i if tl >= 6 - end - else - # Interpreted as time - case tl - when 2, 4, 6 - hash[:hour] = time_digits[0, 2].to_i - hash[:min] = time_digits[2, 2].to_i if tl >= 4 - hash[:sec] = time_digits[4, 2].to_i if tl >= 6 - end - end + h = {} + if (m = JISX0301_RE.match(string)) + era_char = m[1] ? m[1].downcase : 'h' + era_offset = JISX0301_ERA[era_char] + h[:year] = m[2].to_i + era_offset + h[:mon] = m[3].to_i + h[:mday] = m[4].to_i + h[:hour] = m[5].to_i if m[5] + h[:min] = m[6].to_i if m[6] + h[:sec] = m[7].to_i if m[7] + h[:sec_fraction] = parse_sec_fraction(m[8]) if m[8] && !m[8].empty? + parse_zone_and_offset(m[9], h) if m[9] + else + h = _iso8601(string, limit: limit) end + h + end - # Handling fractional seconds - if fraction && !fraction.empty? - hash[:sec_fraction] = Rational(fraction.to_i, 10 ** fraction.length) - end + # ------------------------------------------------------------------ + # _parse + # ------------------------------------------------------------------ - # Handling time zone - if zone && !zone.empty? - if zone[0] == '[' - # Bracket-enclosed zone: C's parse_ddd_cb special handling. - # Strip '[' and ']', then check for ':' separator. - inner = zone[1..-2] # content between [ and ] - colon_pos = inner.index(':') - if colon_pos - # e.g., "[-5:EST]" → zone_name="EST", offset_str="-5:" - # C: zone = part after ':', s5 = part from start to after ':' - zone_name = inner[(colon_pos + 1)..] - offset_str = inner[0, colon_pos + 1] # includes ':' - else - # e.g., "[-9]" → zone_name="-9", offset_str="-9" - # e.g., "[9]" → zone_name="9", offset_str="+9" (digit→prepend '+') - zone_name = inner - if inner[0] && inner[0] =~ /\d/ - offset_str = "+" + zone_name - else - offset_str = zone_name + # call-seq: + # Date._parse(string, comp = true, limit: 128) -> hash + # + # Note: + # This method recognizes many forms in +string+, + # but it is not a validator. + # For formats, see + # {"Specialized Format Strings" in Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc@Specialized+Format+Strings] + # + # If +string+ does not specify a valid date, + # the result is unpredictable; + # consider using Date._strptime instead. + # + # Returns a hash of values parsed from +string+: + # + # Date._parse('2001-02-03') # => {:year=>2001, :mon=>2, :mday=>3} + # + # If +comp+ is +true+ and the given year is in the range (0..99), + # the current century is supplied; + # otherwise, the year is taken as given: + # + # Date._parse('01-02-03', true) # => {:year=>2001, :mon=>2, :mday=>3} + # Date._parse('01-02-03', false) # => {:year=>1, :mon=>2, :mday=>3} + # + # See argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date.parse(returns a \Date object). + def _parse(string, comp = true, limit: 128) + unless String === string + raise TypeError, "no implicit conversion of #{string.class} into String" if string.is_a?(Symbol) || string.nil? + string = string.to_str + end + return {} if string.empty? + raise ArgumentError, "string length (#{string.length}) exceeds limit (#{limit})" if limit && string.length > limit + + # === Fast paths for common date formats === + len = string.length + + # Fast ISO: YYYY-MM-DD (exactly 10 ASCII bytes) + if len == 10 + b0 = string.getbyte(0) + if b0 >= 48 && b0 <= 57 + b1 = string.getbyte(1) + b2 = string.getbyte(2) + b3 = string.getbyte(3) + if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && + string.getbyte(4) == 45 && string.getbyte(7) == 45 + b5 = string.getbyte(5) + b6 = string.getbyte(6) + b8 = string.getbyte(8) + b9 = string.getbyte(9) + if b5 >= 48 && b5 <= 57 && b6 >= 48 && b6 <= 57 && + b8 >= 48 && b8 <= 57 && b9 >= 48 && b9 <= 57 + return { + year: (b0 - 48) * 1000 + (b1 - 48) * 100 + (b2 - 48) * 10 + (b3 - 48), + mon: (b5 - 48) * 10 + (b6 - 48), + mday: (b8 - 48) * 10 + (b9 - 48) + } end end - hash[:zone] = zone_name - hash[:offset] = date_zone_to_diff(offset_str) - else - # Non-bracket zone: just set zone. - # Offset will be resolved in apply_comp if not already set. - hash[:zone] = zone - hash[:offset] = date_zone_to_diff(zone) end end - true - end - - # Parse $1 (time string) further and set hash to hour/min/sec/sec_fraction. - # - # Internal pattern: - # $1 hour - # $2 min (colon format) - # $3 sec (colon format) - # $4 frac ([,.]\d*) - # $5 min (h format) - # $6 sec (h format) - # $7 am/pm (a or p) - def parse_time_detail(time_str, hash) - return unless time_str =~ TIME_DETAIL_PAT - - hour = $1.to_i - min_colon = $2 - sec_colon = $3 - frac = $4 # "[,.] number string" or nil - min_h = $5 - sec_h = $6 - ampm = $7 - - if min_colon - # Branch A: HH:MM[:SS[.frac]] - hash[:hour] = hour - hash[:min] = min_colon.to_i - if sec_colon - hash[:sec] = sec_colon.to_i - if frac && frac.length > 1 - # Since frac is a "[,.] number string", the first character (delimiter) is omitted. - frac_digits = frac[1..] - hash[:sec_fraction] = Rational(frac_digits.to_i, 10 ** frac_digits.length) + # Fast compact: YYYYMMDD (exactly 8 ASCII digit bytes) + if len == 8 + b0 = string.getbyte(0) + if b0 >= 48 && b0 <= 57 + b1 = string.getbyte(1) + b2 = string.getbyte(2) + b3 = string.getbyte(3) + b4 = string.getbyte(4) + b5 = string.getbyte(5) + b6 = string.getbyte(6) + b7 = string.getbyte(7) + if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && + b4 >= 48 && b4 <= 57 && b5 >= 48 && b5 <= 57 && + b6 >= 48 && b6 <= 57 && b7 >= 48 && b7 <= 57 + return { + year: (b0 - 48) * 1000 + (b1 - 48) * 100 + (b2 - 48) * 10 + (b3 - 48), + mon: (b4 - 48) * 10 + (b5 - 48), + mday: (b6 - 48) * 10 + (b7 - 48) + } end end - elsif min_h - # Branch B: HHh[MMm[SSs]](with min) - hash[:hour] = hour - hash[:min] = min_h.to_i - hash[:sec] = sec_h.to_i if sec_h - elsif time_str.match?(/h/i) - # Branch B: Only HHh (no min/sec) - hash[:hour] = hour - elsif ampm - # Branch C: Only AM/PM => Set only hour (converted to AM/PM below) - hash[:hour] = hour - end - - # AM/PM conversion - if ampm - h = hash[:hour] || hour - if ampm.downcase == 'p' && h != 12 - hash[:hour] = h + 12 - elsif ampm.downcase == 'a' && h == 12 - hash[:hour] = 0 - end end - end - # parse_era in date_parse.c. - def parse_era(str, hash) - if str =~ ERA1_PAT - hash[:bc] = false - return true + # Fast US: "Month DD, YYYY" + if (m = FAST_PARSE_US_RE.match(string)) + mon = ABBR_MONTH_NUM[m[1].downcase] + return {year: m[3].to_i, mon: mon, mday: m[2].to_i} if mon end - if str =~ ERA2_PAT - hash[:bc] = $1.downcase.delete('.') != 'ce' - return true + # Fast EU: "DD Month YYYY" + if (m = FAST_PARSE_EU_RE.match(string)) + mon = ABBR_MONTH_NUM[m[2].downcase] + return {year: m[3].to_i, mon: mon, mday: m[1].to_i} if mon end - false - end - - # parse_eu in date_parse.c. - def parse_eu(str, hash) - m = subx(str, PARSE_EU_PAT) - return false unless m - - mday_str = m[1] - mon_str = m[2] - era_str = m[3] - year_str = m[4] - - # Determine bc flag from era. - # AD/A.D./CE/C.E. => false, BC/B.C./BCE/B.C.E. => true - bc = if era_str - era_str.downcase.delete('.') !~ /\A(ad|ce)\z/ - else - false - end - - # Normalize y/m/d and set to hash in s3e. - # 'mon' is converted to an Integer using 'mon_num' and then passed. - s3e(hash, year_str, mon_num(mon_str), mday_str, bc) - - true - end - - # parse_us in date_parse.c. - def parse_us(str, hash) - m = subx(str, PARSE_US_PAT) - return false unless m - - mon_str = m[1] - mday_str = m[2] - era_str = m[3] - year_str = m[4] - - # Determine bc flag from era (same logic as parse_eu). - bc = if era_str - era_str.downcase.delete('.') !~ /\A(ad|ce)\z/ - else - false - end - - # Normalize y/m/d and set to hash using s3e. - # Difference from parse_eu: mon=$1, mday=$2 (only the $ numbers are swapped). - s3e(hash, year_str, mon_num(mon_str), mday_str, bc) - - true - end - - # parse_iso in date_parse.c - def parse_iso(str, hash) - m = subx(str, PARSE_ISO_PAT) - return false unless m - - # Normalize y/m/d and set to hash in s3e. - # bc is always false (there is no era symbol in ISO format). - s3e(hash, m[1], m[2], m[3], false) - - true - end - - # parse_iso2 in date_parse.c - def parse_iso2(str, hash) - return true if parse_iso21(str, hash) - return true if parse_iso22(str, hash) - return true if parse_iso23(str, hash) - return true if parse_iso24(str, hash) - return true if parse_iso25(str, hash) - return true if parse_iso26(str, hash) - - false - end - - def parse_iso21(str, hash) - m = subx(str, PARSE_ISO21_PAT) - return false unless m - - hash[:cwyear] = m[1].to_i if m[1] - hash[:cweek] = m[2].to_i - hash[:cwday] = m[3].to_i if m[3] - - true - end - - def parse_iso22(str, hash) - m = subx(str, PARSE_ISO22_PAT) - return false unless m - - hash[:cwday] = m[1].to_i - - true - end - - def parse_iso23(str, hash) - m = subx(str, PARSE_ISO23_PAT) - return false unless m - - hash[:mon] = m[1].to_i if m[1] - hash[:mday] = m[2].to_i - - true - end - - def parse_iso24(str, hash) - m = subx(str, PARSE_ISO24_PAT) - return false unless m - - hash[:mon] = m[1].to_i - hash[:mday] = m[2].to_i if m[2] - - true - end - - def parse_iso25(str, hash) - # Skip if exclude pattern matches (uses match, not subx). - return false if str =~ PARSE_ISO25_PAT0 - - m = subx(str, PARSE_ISO25_PAT) - return false unless m - - hash[:year] = m[1].to_i - hash[:yday] = m[2].to_i - - true - end - - def parse_iso26(str, hash) - # Skip if exclude pattern matches (uses match, not subx). - return false if str =~ PARSE_ISO26_PAT0 - - m = subx(str, PARSE_ISO26_PAT) - return false unless m - - hash[:yday] = m[1].to_i - - true - end - - # parse_jis in date_parse.c - def parse_jis(str, hash) - m = subx(str, PARSE_JIS_PAT) - return false unless m - - era = m[1].upcase - year = m[2].to_i - mon = m[3].to_i - mday = m[4].to_i - - # Convert the era symbol and year number to Gregorian calendar - # and set it to hash. - hash[:year] = gengo(era) + year - hash[:mon] = mon - hash[:mday] = mday - - true - end - - # parse_vms in date_parse.c - def parse_vms(str, hash) - return true if parse_vms11(str, hash) - return true if parse_vms12(str, hash) - - false - end - - def parse_vms11(str, hash) - m = subx(str, PARSE_VMS11_PAT) - return false unless m - - mday_str = m[1] - mon_str = m[2] - year_str = m[3] - - # Normalize y/m/d and set to hash in s3e. - s3e(hash, year_str, mon_num(mon_str), mday_str, false) - - true - end - - def parse_vms12(str, hash) - m = subx(str, PARSE_VMS12_PAT) - return false unless m - - mon_str = m[1] - mday_str = m[2] - year_str = m[3] - - # Normalize y/m/d and set to hash in s3e. - s3e(hash, year_str, mon_num(mon_str), mday_str, false) - - true - end - - # parse_sla in date_parse.c - def parse_sla(str, hash) - m = subx(str, PARSE_SLA_PAT) - return false unless m - - # Normalize y/m/d and set to hash in s3e. - # bc is always false. - s3e(hash, m[1], m[2], m[3], false) - - true - end - - # parse_dot in date_parse.c - def parse_dot(str, hash) - m = subx(str, PARSE_DOT_PAT) - return false unless m - - # Normalize y/m/d and set to hash in s3e. - # bc is always false. - s3e(hash, m[1], m[2], m[3], false) - - true - end - - # parse_year in date_parse.c - def parse_year(str, hash) - m = subx(str, PARSE_YEAR_PAT) - return false unless m - - hash[:year] = m[1].to_i - - true - end - - # parse_mon in date_parse.c - def parse_mon(str, hash) - m = subx(str, PARSE_MON_PAT) - return false unless m - - hash[:mon] = mon_num(m[1]) - - true - end - - # parse_mday in date_parse.c - def parse_mday(str, hash) - m = subx(str, PARSE_MDAY_PAT) - return false unless m - - hash[:mday] = m[1].to_i - - true - end - - # parse_bc in date_parse.c (non-TIGHT post-processing). - # Matches standalone BC/BCE/B.C./B.C.E. and sets _bc flag. - def parse_bc(str, hash) - m = subx(str, PARSE_BC_PAT) - return false unless m - - hash[:_bc] = true + # Fast RFC2822-like: "Dow, DD Mon YYYY HH:MM:SS +ZZZZ" + if (m = FAST_PARSE_RFC2822_RE.match(string)) + wday = ABBR_DAY_NUM[m[1].downcase] + mon = ABBR_MONTH_NUM[m[3].downcase] + if wday && mon + zone = m[8] + return { + wday: wday, mday: m[2].to_i, mon: mon, year: m[4].to_i, + hour: m[5].to_i, min: m[6].to_i, sec: m[7].to_i, + zone: zone, offset: fast_zone_offset(zone) + } + end + end - true - end + # Preprocessing: replace non-date chars with space + str = string.dup + str.gsub!(/[^-+',.\/:\@\[\][:alnum:]]+/, ' ') - # parse_frag in date_parse.c (non-TIGHT post-processing). - # If the remaining string (after all other parsers have consumed - # their portions) is a standalone 1-2 digit number: - # - If we have hour but no mday, and the number is 1-31, set mday - # - If we have mday but no hour, and the number is 0-24, set hour - def parse_frag(str, hash) - m = subx(str, PARSE_FRAG_PAT) - return false unless m + # check_class (byte-level for speed) + cc = 0 + str.each_byte do |b| + if b >= 65 && b <= 90 || b >= 97 && b <= 122 || b > 127 + cc |= HAVE_ALPHA + elsif b >= 48 && b <= 57 + cc |= HAVE_DIGIT + elsif b == 45 + cc |= HAVE_DASH + elsif b == 46 + cc |= HAVE_DOT + elsif b == 47 + cc |= HAVE_SLASH + elsif b == 58 + cc |= HAVE_COLON + end + end - n = m[1].to_i + h = {} - if hash.key?(:hour) && !hash.key?(:mday) - hash[:mday] = n if n >= 1 && n <= 31 + # parse_day (always runs) + if (cc & HAVE_ALPHA) != 0 + parse_day(str, h) end - if hash.key?(:mday) && !hash.key?(:hour) - hash[:hour] = n if n >= 0 && n <= 24 - end - - true - end - # Helper: Convert day name to number (0=Sunday, 6=Saturday) - def day_num(day_name) - abbr_days = %w[sun mon tue wed thu fri sat] - abbr_days.index(day_name[0, 3].downcase) || 0 - end + # parse_time (needs colon or alpha for h/am/pm patterns) + if (cc & HAVE_DIGIT) != 0 && (cc & (HAVE_COLON | HAVE_ALPHA)) != 0 + parse_time(str, h) + end - # Helper: Convert month name to number (1=January, 12=December) - def mon_num(month_name) - abbr_months = %w[jan feb mar apr may jun jul aug sep oct nov dec] - (abbr_months.index(month_name[0, 3].downcase) || 0) + 1 - end + # Date parsers: first match wins (goto ok) + matched = false - # ISO 8601 extended datetime: 2001-02-03T04:05:06+09:00 - def iso8601_ext_datetime(str, hash) - pattern = /\A\s* - (?: - ([-+]?\d{2,}|-)-(\d{2})?(?:-(\d{2}))?| # YYYY-MM-DD or --MM-DD - ([-+]?\d{2,})?-(\d{3})| # YYYY-DDD - (\d{4}|\d{2})?-w(\d{2})-(\d)| # YYYY-Www-D - -w-(\d) # -W-D - ) - (?:t - (\d{2}):(\d{2})(?::(\d{2})(?:[,.](\d+))?)? # HH:MM:SS.fraction - (z|[-+]\d{2}(?::?\d{2})?)? # timezone - )? - \s*\z/ix - - match = pattern.match(str) - return false unless match - - # Calendar date (YYYY-MM-DD) - if match[1] - unless match[1] == '-' - year = match[1].to_i - # Complete 2-digit year - year = comp_year69(year) if match[1].length < 4 - hash[:year] = year - end - hash[:mon] = match[2].to_i if match[2] - hash[:mday] = match[3].to_i if match[3] - # Ordinal date (YYYY-DDD) - elsif match[5] - if match[4] - year = match[4].to_i - year = comp_year69(year) if match[4].length < 4 - hash[:year] = year - end - hash[:yday] = match[5].to_i - # Week date (YYYY-Www-D) - elsif match[8] - if match[6] - year = match[6].to_i - year = comp_year69(year) if match[6].length < 4 - hash[:cwyear] = year - end - hash[:cweek] = match[7].to_i - hash[:cwday] = match[8].to_i - # Week day only (-W-D) - elsif match[9] - hash[:cwday] = match[9].to_i + if !matched && (cc & (HAVE_ALPHA | HAVE_DIGIT)) == (HAVE_ALPHA | HAVE_DIGIT) + matched = parse_eu(str, h) end - # Time - if match[10] - hash[:hour] = match[10].to_i - hash[:min] = match[11].to_i - hash[:sec] = match[12].to_i if match[12] - hash[:sec_fraction] = parse_fraction(match[13]) if match[13] + if !matched && (cc & (HAVE_ALPHA | HAVE_DIGIT)) == (HAVE_ALPHA | HAVE_DIGIT) + matched = parse_us(str, h) end - # Timezone - if match[14] - hash[:zone] = match[14] - hash[:offset] = parse_zone_offset(match[14]) + if !matched && (cc & (HAVE_DIGIT | HAVE_DASH)) == (HAVE_DIGIT | HAVE_DASH) + matched = parse_iso(str, h) end - true - end - - # ISO 8601 basic datetime: 20010203T040506 - def iso8601_bas_datetime(str, hash) - # Try full basic datetime: YYYYMMDD or YYMMDD - pattern = /\A\s* - ([-+]?(?:\d{4}|\d{2})|--) # Year (YYYY, YY, --, or signed) - (\d{2}|-) # Month (MM or -) - (\d{2}) # Day (DD) - (?:t? - (\d{2})(\d{2}) # Hour and minute (HHMM) - (?:(\d{2}) # Second (SS) - (?:[,.](\d+))? # Fraction - )? - (z|[-+]\d{2}(?:\d{2})?)? # Timezone - )? - \s*\z/ix - - match = pattern.match(str) - if match - # Calendar date - unless match[1] == '--' - year = match[1].to_i - year = comp_year69(year) if match[1].length == 2 && match[1] !~ /^[-+]/ - hash[:year] = year - end - hash[:mon] = match[2].to_i unless match[2] == '-' - hash[:mday] = match[3].to_i - - # Time - if match[4] - hash[:hour] = match[4].to_i - hash[:min] = match[5].to_i - hash[:sec] = match[6].to_i if match[6] - hash[:sec_fraction] = parse_fraction(match[7]) if match[7] - end - - # Timezone - if match[8] - hash[:zone] = match[8] - hash[:offset] = parse_zone_offset(match[8]) - end + if !matched && (cc & (HAVE_DIGIT | HAVE_DOT)) == (HAVE_DIGIT | HAVE_DOT) + matched = parse_jis(str, h) + end - return true + if !matched && (cc & (HAVE_ALPHA | HAVE_DIGIT | HAVE_DASH)) == (HAVE_ALPHA | HAVE_DIGIT | HAVE_DASH) + matched = parse_vms(str, h) end - # Try ordinal date: YYYYDDD or YYDDD - pattern = /\A\s* - ([-+]?(?:\d{4}|\d{2})) # Year - (\d{3}) # Day of year - (?:t? - (\d{2})(\d{2}) # Hour and minute - (?:(\d{2}) # Second - (?:[,.](\d+))? # Fraction - )? - (z|[-+]\d{2}(?:\d{2})?)? # Timezone - )? - \s*\z/ix - - match = pattern.match(str) - if match - year = match[1].to_i - year = comp_year69(year) if match[1].length == 2 && match[1] !~ /^[-+]/ - hash[:year] = year - hash[:yday] = match[2].to_i - - # Time - if match[3] - hash[:hour] = match[3].to_i - hash[:min] = match[4].to_i - hash[:sec] = match[5].to_i if match[5] - hash[:sec_fraction] = parse_fraction(match[6]) if match[6] - end + if !matched && (cc & (HAVE_DIGIT | HAVE_SLASH)) == (HAVE_DIGIT | HAVE_SLASH) + matched = parse_sla(str, h) + end - # Timezone - if match[7] - hash[:zone] = match[7] - hash[:offset] = parse_zone_offset(match[7]) - end + if !matched && (cc & (HAVE_DIGIT | HAVE_DOT)) == (HAVE_DIGIT | HAVE_DOT) + matched = parse_dot(str, h) + end - return true + if !matched && (cc & HAVE_DIGIT) != 0 + matched = parse_iso2(str, h) end - # Try -DDD (ordinal without year) - pattern = /\A\s* - -(\d{3}) # Day of year - (?:t? - (\d{2})(\d{2}) # Hour and minute - (?:(\d{2}) # Second - (?:[,.](\d+))? # Fraction - )? - (z|[-+]\d{2}(?:\d{2})?)? # Timezone - )? - \s*\z/ix - - match = pattern.match(str) - if match - hash[:yday] = match[1].to_i - - # Time - if match[2] - hash[:hour] = match[2].to_i - hash[:min] = match[3].to_i - hash[:sec] = match[4].to_i if match[4] - hash[:sec_fraction] = parse_fraction(match[5]) if match[5] - end + if !matched && (cc & HAVE_DIGIT) != 0 + matched = parse_year(str, h) + end - # Timezone - if match[6] - hash[:zone] = match[6] - hash[:offset] = parse_zone_offset(match[6]) - end + if !matched && (cc & HAVE_ALPHA) != 0 + matched = parse_mon(str, h) + end - return true + if !matched && (cc & HAVE_DIGIT) != 0 + matched = parse_mday(str, h) end - # Try week date: YYYYWwwD or YYWwwD - pattern = /\A\s* - (\d{4}|\d{2}) # Year - w(\d{2}) # Week - (\d) # Day of week - (?:t? - (\d{2})(\d{2}) # Hour and minute - (?:(\d{2}) # Second - (?:[,.](\d+))? # Fraction - )? - (z|[-+]\d{2}(?:\d{2})?)? # Timezone - )? - \s*\z/ix - - match = pattern.match(str) - if match - year = match[1].to_i - year = comp_year69(year) if match[1].length == 2 - hash[:cwyear] = year - hash[:cweek] = match[2].to_i - hash[:cwday] = match[3].to_i - - # Time - if match[4] - hash[:hour] = match[4].to_i - hash[:min] = match[5].to_i - hash[:sec] = match[6].to_i if match[6] - hash[:sec_fraction] = parse_fraction(match[7]) if match[7] - end + if !matched && (cc & HAVE_DIGIT) != 0 + parse_ddd(str, h) + end - # Timezone - if match[8] - hash[:zone] = match[8] - hash[:offset] = parse_zone_offset(match[8]) - end + # Post-processing (always runs after ok label) + # parse_bc + if (cc & HAVE_ALPHA) != 0 + parse_bc_post(str, h) + end - return true + # parse_frag + if (cc & HAVE_DIGIT) != 0 + parse_frag(str, h) end - # Try -WwwD (week date without year) - pattern = /\A\s* - -w(\d{2}) # Week - (\d) # Day of week - (?:t? - (\d{2})(\d{2}) # Hour and minute - (?:(\d{2}) # Second - (?:[,.](\d+))? # Fraction - )? - (z|[-+]\d{2}(?:\d{2})?)? # Timezone - )? - \s*\z/ix - - match = pattern.match(str) - if match - hash[:cweek] = match[1].to_i - hash[:cwday] = match[2].to_i - - # Time - if match[3] - hash[:hour] = match[3].to_i - hash[:min] = match[4].to_i - hash[:sec] = match[5].to_i if match[5] - hash[:sec_fraction] = parse_fraction(match[6]) if match[6] - end + # BC handling + if h.delete(:_bc) + h[:cwyear] = -h[:cwyear] + 1 if h[:cwyear] + h[:year] = -h[:year] + 1 if h[:year] + end - # Timezone - if match[7] - hash[:zone] = match[7] - hash[:offset] = parse_zone_offset(match[7]) + # comp (century completion) + if comp && h.delete(:_comp) != false + [:cwyear, :year].each do |key| + y = h[key] + if y && y >= 0 && y <= 99 + h[key] = y >= 69 ? y + 1900 : y + 2000 + end end + end - return true + # zone -> offset + if h[:zone] && !h.key?(:offset) + h[:offset] = fast_zone_offset(h[:zone]) end - # Try -W-D (day of week only) - pattern = /\A\s* - -w-(\d) # Day of week - (?:t? - (\d{2})(\d{2}) # Hour and minute - (?:(\d{2}) # Second - (?:[,.](\d+))? # Fraction - )? - (z|[-+]\d{2}(?:\d{2})?)? # Timezone - )? - \s*\z/ix - - match = pattern.match(str) - if match - hash[:cwday] = match[1].to_i - - # Time - if match[2] - hash[:hour] = match[2].to_i - hash[:min] = match[3].to_i - hash[:sec] = match[4].to_i if match[4] - hash[:sec_fraction] = parse_fraction(match[5]) if match[5] - end + h + end - # Timezone - if match[6] - hash[:zone] = match[6] - hash[:offset] = parse_zone_offset(match[6]) - end + # ------------------------------------------------------------------ + # parse constructor + # ------------------------------------------------------------------ - return true - end + # call-seq: + # Date.parse(string = '-4712-01-01', comp = true, start = Date::ITALY, limit: 128) -> date + # + # Note: + # This method recognizes many forms in +string+, + # but it is not a validator. + # For formats, see + # {"Specialized Format Strings" in Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc@Specialized+Format+Strings] + # If +string+ does not specify a valid date, + # the result is unpredictable; + # consider using Date._strptime instead. + # + # Returns a new \Date object with values parsed from +string+: + # + # Date.parse('2001-02-03') # => # + # Date.parse('20010203') # => # + # Date.parse('3rd Feb 2001') # => # + # + # If +comp+ is +true+ and the given year is in the range (0..99), + # the current century is supplied; + # otherwise, the year is taken as given: + # + # Date.parse('01-02-03', true) # => # + # Date.parse('01-02-03', false) # => # + # + # See: + # + # - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # - Argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date._parse (returns a hash). + def parse(string = '-4712-01-01', comp = true, start = DEFAULT_SG, limit: 128) + hash = _parse(string, comp, limit: limit) + fast_new_date(hash, start) + end - false + # ------------------------------------------------------------------ + # Specialized constructors + # ------------------------------------------------------------------ + + # call-seq: + # Date.iso8601(string = '-4712-01-01', start = Date::ITALY, limit: 128) -> date + # + # Returns a new \Date object with values parsed from +string+, + # which should contain + # an {ISO 8601 formatted date}[rdoc-ref:language/strftime_formatting.rdoc@ISO+8601+Format+Specifications]: + # + # d = Date.new(2001, 2, 3) + # s = d.iso8601 # => "2001-02-03" + # Date.iso8601(s) # => # + # + # See: + # + # - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # - Argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date._iso8601 (returns a hash). + def iso8601(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) + hash = _iso8601(string, limit: limit) + fast_new_date(hash, start) end - # ISO 8601 extended time: 04:05:06+09:00 - def iso8601_ext_time(str, hash) - # Pattern: HH:MM:SS.fraction or HH:MM:SS,fraction - pattern = /\A\s*(\d{2}):(\d{2})(?::(\d{2})(?:[,.](\d+))?)?(z|[-+]\d{2}(?::?\d{2})?)?\s*\z/ix + # call-seq: + # Date.rfc3339(string = '-4712-01-01T00:00:00+00:00', start = Date::ITALY, limit: 128) -> date + # + # Returns a new \Date object with values parsed from +string+, + # which should be a valid + # {RFC 3339 format}[rdoc-ref:language/strftime_formatting.rdoc@RFC+3339+Format]: + # + # d = Date.new(2001, 2, 3) + # s = d.rfc3339 # => "2001-02-03T00:00:00+00:00" + # Date.rfc3339(s) # => # + # + # See: + # + # - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # - Argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date._rfc3339 (returns a hash). + def rfc3339(string = JULIAN_EPOCH_DATETIME, start = DEFAULT_SG, limit: 128) + hash = _rfc3339(string, limit: limit) + fast_new_date(hash, start) + end - match = pattern.match(str) - return false unless match + # call-seq: + # Date.xmlschema(string = '-4712-01-01', start = Date::ITALY, limit: 128) -> date + # + # Returns a new \Date object with values parsed from +string+, + # which should be a valid XML date format: + # + # d = Date.new(2001, 2, 3) + # s = d.xmlschema # => "2001-02-03" + # Date.xmlschema(s) # => # + # + # See: + # + # - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # - Argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date._xmlschema (returns a hash). + def xmlschema(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) + hash = _xmlschema(string, limit: limit) + fast_new_date(hash, start) + end - hash[:hour] = match[1].to_i - hash[:min] = match[2].to_i - hash[:sec] = match[3].to_i if match[3] - hash[:sec_fraction] = parse_fraction(match[4]) if match[4] + # call-seq: + # Date.rfc2822(string = 'Mon, 1 Jan -4712 00:00:00 +0000', start = Date::ITALY, limit: 128) -> date + # + # Returns a new \Date object with values parsed from +string+, + # which should be a valid + # {RFC 2822 date format}[rdoc-ref:language/strftime_formatting.rdoc@RFC+2822+Format]: + # + # d = Date.new(2001, 2, 3) + # s = d.rfc2822 # => "Sat, 3 Feb 2001 00:00:00 +0000" + # Date.rfc2822(s) # => # + # + # See: + # + # - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # - Argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date._rfc2822 (returns a hash). + def rfc2822(string = JULIAN_EPOCH_DATETIME_RFC2822, start = DEFAULT_SG, limit: 128) + hash = _rfc2822(string, limit: limit) + fast_new_date(hash, start) + end + alias rfc822 rfc2822 - if match[5] - hash[:zone] = match[5] - hash[:offset] = parse_zone_offset(match[5]) - end + # call-seq: + # Date.httpdate(string = 'Mon, 01 Jan -4712 00:00:00 GMT', start = Date::ITALY, limit: 128) -> date + # + # Returns a new \Date object with values parsed from +string+, + # which should be a valid + # {HTTP date format}[rdoc-ref:language/strftime_formatting.rdoc@HTTP+Format]: + # + # d = Date.new(2001, 2, 3) + # s = d.httpdate # => "Sat, 03 Feb 2001 00:00:00 GMT" + # Date.httpdate(s) # => # + # + # See: + # + # - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # - Argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date._httpdate (returns a hash). + def httpdate(string = JULIAN_EPOCH_DATETIME_HTTPDATE, start = DEFAULT_SG, limit: 128) + hash = _httpdate(string, limit: limit) + fast_new_date(hash, start) + end - true + # call-seq: + # Date.jisx0301(string = '-4712-01-01', start = Date::ITALY, limit: 128) -> date + # + # Returns a new \Date object with values parsed from +string+, + # which should be a valid {JIS X 0301 format}[rdoc-ref:language/strftime_formatting.rdoc@JIS+X+0301+Format]: + # + # d = Date.new(2001, 2, 3) + # s = d.jisx0301 # => "H13.02.03" + # Date.jisx0301(s) # => # + # + # For no-era year, legacy format, Heisei is assumed. + # + # Date.jisx0301('13.02.03') # => # + # + # See: + # + # - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # - Argument {limit}[rdoc-ref:Date@Argument+limit]. + # + # Related: Date._jisx0301 (returns a hash). + def jisx0301(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) + hash = _jisx0301(string, limit: limit) + fast_new_date(hash, start) end - # ISO 8601 basic time: 040506 - def iso8601_bas_time(str, hash) - # Pattern: HHMMSS.fraction or HHMMSS,fraction - pattern = /\A\s*(\d{2})(\d{2})(?:(\d{2})(?:[,.](\d+))?)?(z|[-+]\d{2}(?:\d{2})?)?\s*\z/ix + private - match = pattern.match(str) - return false unless match + # ------------------------------------------------------------------ + # Shared infrastructure + # ------------------------------------------------------------------ - hash[:hour] = match[1].to_i - hash[:min] = match[2].to_i - hash[:sec] = match[3].to_i if match[3] - hash[:sec_fraction] = parse_fraction(match[4]) if match[4] + def parse_check_limit(str, limit) + raise ArgumentError, "string length (#{str.length}) exceeds limit (#{limit})" if limit && str.length > limit + end - if match[5] - hash[:zone] = match[5] - hash[:offset] = parse_zone_offset(match[5]) - end + def parse_to_str(obj) + return nil if obj.nil? + raise TypeError, "no implicit conversion of #{obj.class} into String" if obj.is_a?(Symbol) + String === obj ? obj : obj.to_str + end - true + def parse_zone_and_offset(zone_str, hash) + return unless zone_str + hash[:zone] = zone_str + hash[:offset] = fast_zone_offset(zone_str) end - # Parse fractional seconds - def parse_fraction(frac_str) - return nil unless frac_str + def parse_sec_fraction(frac_str) Rational(frac_str.to_i, 10 ** frac_str.length) end - # Parse timezone offset (Z, +09:00, -0500, etc.) - def parse_zone_offset(zone_str) - return nil if zone_str.nil? || zone_str.empty? - - zone = zone_str.strip - - # Handle [+9] or [-9] or [9 ] format (brackets around offset) - if zone =~ /^\[(.*)\]$/ - zone = $1.strip - end - - # Handle Z (UTC) - return 0 if zone.upcase == 'Z' - - # Handle unsigned numeric offset: 9, 09 (assume positive) - if zone =~ /^(\d{1,2})$/ - hours = $1.to_i - return hours * HOUR_IN_SECONDS - end - - # Handle simple numeric offsets with sign: +9, -9, +09, -05, etc. - if zone =~ /^([-+])(\d{1,2})$/ - sign = $1 == '-' ? -1 : 1 - hours = $2.to_i - return sign * (hours * HOUR_IN_SECONDS) - end - - # Handle +09:00, -05:30 format (with colon) - if zone =~ /^([-+])(\d{2}):(\d{2})$/ - sign = $1 == '-' ? -1 : 1 - hours = $2.to_i - minutes = $3.to_i - return sign * (hours * HOUR_IN_SECONDS + minutes * MINUTE_IN_SECONDS) - end - - # Handle +0900, -0500 format (4 digits, no colon) - if zone =~ /^([-+])(\d{4})$/ - sign = $1 == '-' ? -1 : 1 - hours = $2[0, 2].to_i - minutes = $2[2, 2].to_i - return sign * (hours * HOUR_IN_SECONDS + minutes * MINUTE_IN_SECONDS) - end - - # Handle +0900 format (4 digits without colon) - if zone =~ /^([-+])(\d{4})$/ - sign = $1 == '-' ? -1 : 1 - hours = $2[0, 2].to_i - minutes = $2[2, 2].to_i - return sign * (hours * HOUR_IN_SECONDS + minutes * MINUTE_IN_SECONDS) - end - - # Handle fractional hours: +9.5, -5.5 - if zone =~ /^([-+])(\d+)[.,](\d+)$/ - sign = $1 == '-' ? -1 : 1 - hours = $2.to_i - fraction = "0.#{$3}".to_f - return sign * ((hours + fraction) * HOUR_IN_SECONDS).to_i - end - - # Handle GMT+9, GMT-5, etc. - if zone =~ /^(?:gmt|utc)?([-+])(\d{1,2})(?::?(\d{2}))?(?::?(\d{2}))?$/i - sign = $1 == '-' ? -1 : 1 - hours = $2.to_i - minutes = $3 ? $3.to_i : 0 - seconds = $4 ? $4.to_i : 0 - return sign * (hours * HOUR_IN_SECONDS + minutes * MINUTE_IN_SECONDS + seconds) - end - - # Known timezone abbreviations - zone_offsets = { - 'JST' => 9 * HOUR_IN_SECONDS, - 'GMT' => 0, - 'UTC' => 0, - 'UT' => 0, - 'EST' => -5 * HOUR_IN_SECONDS, - 'EDT' => -4 * HOUR_IN_SECONDS, - 'CST' => -6 * HOUR_IN_SECONDS, - 'CDT' => -5 * HOUR_IN_SECONDS, - 'MST' => -7 * HOUR_IN_SECONDS, - 'MDT' => -6 * HOUR_IN_SECONDS, - 'PST' => -8 * HOUR_IN_SECONDS, - 'PDT' => -7 * HOUR_IN_SECONDS, - 'AEST' => 10 * HOUR_IN_SECONDS, - 'MET DST' => 2 * HOUR_IN_SECONDS, - 'GMT STANDARD TIME' => 0, - 'MOUNTAIN STANDARD TIME' => -7 * HOUR_IN_SECONDS, - 'MOUNTAIN DAYLIGHT TIME' => -6 * HOUR_IN_SECONDS, - 'MEXICO STANDARD TIME' => -6 * HOUR_IN_SECONDS, - 'E. AUSTRALIA STANDARD TIME' => 10 * HOUR_IN_SECONDS, - 'W. CENTRAL AFRICA STANDARD TIME' => 1 * HOUR_IN_SECONDS, - } - - # Handle military timezones (single letters A-Z except J) - if zone =~ /^([A-Z])$/i - letter = zone.upcase - return 0 if letter == 'Z' - return nil if letter == 'J' # J is not used - - if letter <= 'I' - # A-I: +1 to +9 - offset = letter.ord - 'A'.ord + 1 - elsif letter >= 'K' && letter <= 'M' - # K-M: +10 to +12 (skip J) - offset = letter.ord - 'A'.ord # K is 10th letter (ord-'A'=10) - elsif letter >= 'N' && letter <= 'Y' - # N-Y: -1 to -12 - offset = -(letter.ord - 'N'.ord + 1) - else - return nil + # Fast zone offset calculation for common patterns. + # Handles: Z/z, +HH:MM/-HH:MM, +HHMM/-HHMM, short named zones. + # Falls back to _sp_zone_to_diff for complex cases. + def fast_zone_offset(zone_str) # rubocop:disable Metrics/CyclomaticComplexity + len = zone_str.length + b0 = zone_str.getbyte(0) + + # Z/z + return 0 if len == 1 && (b0 == 90 || b0 == 122) + + if b0 == 43 || b0 == 45 # '+' or '-' + sign = b0 == 45 ? -1 : 1 + if len == 6 && zone_str.getbyte(3) == 58 # +HH:MM + b1 = zone_str.getbyte(1) + b2 = zone_str.getbyte(2) + b4 = zone_str.getbyte(4) + b5 = zone_str.getbyte(5) + if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b4 >= 48 && b4 <= 57 && b5 >= 48 && b5 <= 57 + return sign * ((b1 - 48) * 36000 + (b2 - 48) * 3600 + (b4 - 48) * 600 + (b5 - 48) * 60) + end + end + if len == 5 # +HHMM + b1 = zone_str.getbyte(1) + b2 = zone_str.getbyte(2) + b3 = zone_str.getbyte(3) + b4 = zone_str.getbyte(4) + if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && b4 >= 48 && b4 <= 57 + return sign * ((b1 - 48) * 36000 + (b2 - 48) * 3600 + (b3 - 48) * 600 + (b4 - 48) * 60) + end end + end - return offset * HOUR_IN_SECONDS + # Short named zones: gmt, utc, est, etc. + if len <= 3 + off = ZONE_TABLE[zone_str.downcase] + return off if off end - # Normalize zone string for lookup - zone_upper = zone.gsub(/\s+/, ' ').upcase - zone_offsets[zone_upper] + # Fall back to full parser + _sp_zone_to_diff(zone_str) end - # JIS X 0301 format: H13.02.03 or H13.02.03T04:05:06 - def parse_jisx0301_fmt(str, hash) - # Pattern: [Era]YY.MM.DD[T]HH:MM:SS[.fraction][timezone] - # Era initials: M, T, S, H, R (or none for ISO 8601 fallback) - pattern = /\A\s* - ([#{JISX0301_ERA_INITIALS}])? # Era (optional) - (\d{2})\.(\d{2})\.(\d{2}) # YY.MM.DD - (?:t # Time separator (optional) - (?: - (\d{2}):(\d{2}) # HH:MM - (?::(\d{2}) # :SS (optional) - (?:[,.](\d*))? # .fraction (optional) - )? - (z|[-+]\d{2}(?::?\d{2})?)? # timezone (optional) - )? - )? - \s*\z/ix - - match = pattern.match(str) - return false unless match - - # Parse era and year - era_char = match[1] ? match[1].upcase : JISX0301_DEFAULT_ERA - era_year = match[2].to_i - - # Convert era year to gregorian year - era_start = gengo(era_char) - hash[:year] = era_start + era_year - - # Parse month and day - hash[:mon] = match[3].to_i - hash[:mday] = match[4].to_i - - # Parse time (if present) - if match[5] - hash[:hour] = match[5].to_i - hash[:min] = match[6].to_i if match[6] - hash[:sec] = match[7].to_i if match[7] - hash[:sec_fraction] = parse_fraction(match[8]) if match[8] - end - - # Parse timezone (if present) - if match[9] - hash[:zone] = match[9] - hash[:offset] = parse_zone_offset(match[9]) - end - - true - end + # ------------------------------------------------------------------ + # _iso8601 helpers + # ------------------------------------------------------------------ - # Convert era character to year offset - def gengo(era_char) - case era_char.upcase - when 'M' then 1867 # Meiji - when 'T' then 1911 # Taisho - when 'S' then 1925 # Showa - when 'H' then 1988 # Heisei - when 'R' then 2018 # Reiwa - else 0 - end + def comp_year69(y) + y >= 69 ? y + 1900 : y + 2000 end - # Post-processing: matches C's date__parse post-processing after ok: label. - # - # 1. _bc handling: negate year and cwyear (year = 1 - year) - # 2. _comp handling: complete 2-digit year/cwyear to 4-digit (69-99 → 1900s, 0-68 → 2000s) - # 3. zone → offset conversion - # 4. Clean up internal keys - def apply_comp(hash) - # _bc: del_hash("_bc") — read and delete - bc = hash.delete(:_bc) - if bc - if hash.key?(:cwyear) - hash[:cwyear] = 1 - hash[:cwyear] - end - if hash.key?(:year) - hash[:year] = 1 - hash[:year] + def iso8601_ext_datetime(m, h) + if m[1] + # year-mon-mday or truncated + unless m[1] == '-' + y = m[1].to_i + h[:year] = (m[1].length <= 2 && !m[1].start_with?('+') && !m[1].start_with?('-')) ? comp_year69(y) : y end - end - - # _comp: del_hash("_comp") — read and delete - comp = hash.delete(:_comp) - if comp - if hash.key?(:cwyear) - y = hash[:cwyear] - if y >= 0 && y <= 99 - hash[:cwyear] = y >= 69 ? y + 1900 : y + 2000 - end + h[:mon] = m[2].to_i if m[2] + h[:mday] = m[3].to_i if m[3] + elsif m[4] || m[5] + # year-yday + if m[4] + y = m[4].to_i + h[:year] = (m[4].length <= 2 && !m[4].start_with?('+') && !m[4].start_with?('-')) ? comp_year69(y) : y end - if hash.key?(:year) - y = hash[:year] - if y >= 0 && y <= 99 - hash[:year] = y >= 69 ? y + 1900 : y + 2000 - end + h[:yday] = m[5].to_i + elsif m[6] || m[7] + # cwyear-wNN-D + if m[6] + y = m[6].to_i + h[:cwyear] = m[6].length <= 2 ? comp_year69(y) : y end + h[:cweek] = m[7].to_i + h[:cwday] = m[8].to_i if m[8] + elsif m[9] + # -w-D + h[:cwday] = m[9].to_i end - - # zone → offset conversion - if hash.key?(:zone) && !hash.key?(:offset) - hash[:offset] = date_zone_to_diff(hash[:zone]) + # time part + if m[10] + h[:hour] = m[10].to_i + h[:min] = m[11].to_i if m[11] + h[:sec] = m[12].to_i if m[12] + h[:sec_fraction] = parse_sec_fraction(m[13]) if m[13] + parse_zone_and_offset(m[14], h) if m[14] end - - # Clean up internal keys - hash.delete(:_year_str) end - # s3e in date_parse.c. - # y, m, and d are Strings or nil. m can also be an Integer (convert with to_s). - # bc is a Boolean. - # - # This method normalizes the year, mon, and mday from the combination of y, m, and - # d and writes them to a hash. - # The sorting logic operates in the following order of priority: - # - # Phase 1: Argument rotation and promotion - # - y and m are available, but d is nil => Rotate because it is a pair (mon, mday) - # - y is nil and d is long (>2 digits) or starts with an apostrophe => Promote d to y - # - If y has a leading character other than a digit, extract only the numeric portion, and if there is a remainder, add it to d - # - # Phase 2: Sort m and d - # - m starts with an apostrophe or its length is >2 => US->BE sort (y,m,d)=(m,d,y) - # - d starts with an apostrophe or its length is >2 => Swap (y,d) - # - # Phase 3: Write to hash - # - Extract the sign and digits from y and set them to year - # If signed or the number of digits is >2, write _comp = false - # - Extract the number from m and set it to mon - # - Extract the number from d and set it to mday - # - If bc is true, write _bc = true - def s3e(hash, y, m, d, bc) - # Candidates for _comp. If nil, do not write. - c = nil - - # If m is not a string, use to_s (parse_eu/parse_us passes the Integer returned by mon_num) - m = m.to_s unless m.nil? || m.is_a?(String) - - # ---------------------------------------------------------- - # Phase 1: Argument reordering - # ---------------------------------------------------------- - - # If we have y and m, but d is nil, it's actually a (mon, mday) pair, so we rotate it. - # (y, m, d) = (nil, y, m) - if !y.nil? && !m.nil? && d.nil? - y, m, d = nil, y, m - end - - # If y is nil and d exists, if d is long or begins with an apostrophe, it is promoted to y - if y.nil? - if !d.nil? && d.length > 2 - y = d - d = nil - end - if !d.nil? && d.length > 0 && d[0] == "'" - y = d - d = nil - end + def iso8601_bas_datetime(m, h) + if m[1] + # yyyymmdd / --mmdd / ----dd + unless m[1] == '--' + y_s = m[1] + y = y_s.to_i + ylen = y_s.sub(/\A[-+]/, '').length + h[:year] = (ylen <= 2 && !y_s.start_with?('+') && !y_s.start_with?('-')) ? comp_year69(y) : y + end + h[:mon] = m[2].to_i unless m[2] == '-' + h[:mday] = m[3].to_i + elsif m[4] + # yyyyddd + y_s = m[4] + y = y_s.to_i + ylen = y_s.sub(/\A[-+]/, '').length + h[:year] = (ylen <= 2 && !y_s.start_with?('+') && !y_s.start_with?('-')) ? comp_year69(y) : y + h[:yday] = m[5].to_i + elsif m[6] + # -ddd + h[:yday] = m[6].to_i + elsif m[7] + # yyyywwwd + y = m[7].to_i + h[:cwyear] = m[7].length <= 2 ? comp_year69(y) : y + h[:cweek] = m[8].to_i + h[:cwday] = m[9].to_i + elsif m[10] + # -wNN-D + h[:cweek] = m[10].to_i + h[:cwday] = m[11].to_i + elsif m[12] + # -w-D + h[:cwday] = m[12].to_i end - - # If y has a leading character other than a sign or a number, skip it and - # extract only the numeric part. If there are any characters remaining after - # the extracted numeric string, swap y and d, and set the numeric part to d. - unless y.nil? - pos = 0 - pos += 1 while pos < y.length && !issign?(y[pos]) && !y[pos].match?(/\d/) - - unless pos >= y.length # no_date - bp = pos - pos += 1 if pos < y.length && issign?(y[pos]) - span = digit_span(y[pos..]) - ep = pos + span - - if ep < y.length - # There is a letter after the number string => exchange (y, d) - y, d = d, y[bp...ep] - end - end + # time part + if m[13] + h[:hour] = m[13].to_i + h[:min] = m[14].to_i if m[14] + h[:sec] = m[15].to_i if m[15] + h[:sec_fraction] = parse_sec_fraction(m[16]) if m[16] + parse_zone_and_offset(m[17], h) if m[17] end + end - # ---------------------------------------------------------- - # Phase 2: Rearrange m and d - # ---------------------------------------------------------- - - # m starts with an apostrophe or length > 2 => US => BE sort - # (y, m, d) = (m, d, y) - if !m.nil? && (m[0] == "'" || m.length > 2) - y, m, d = m, d, y - end + # ------------------------------------------------------------------ + # _parse sub-parsers (private) + # ------------------------------------------------------------------ - # d begins with an apostrophe or length > 2 => exchange (y, d) - if !d.nil? && (d[0] == "'" || d.length > 2) - y, d = d, y + def parse_day(str, h) + if (m = PARSE_DAYS_RE.match(str)) + h[:wday] = ABBR_DAY_NUM[m[1].downcase] + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) end + end - # ---------------------------------------------------------- - # Phase 3: Write to hash - # ---------------------------------------------------------- - - # year: Extract the sign and digit from y and set - unless y.nil? - pos = 0 - pos += 1 while pos < y.length && !issign?(y[pos]) && !y[pos].match?(/\d/) + def parse_time(str, h) + if (m = PARSE_TIME_RE.match(str)) + time_part = m[1] + zone_part = m[2] + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) - unless pos >= y.length # no_year - bp = pos - sign = false - if pos < y.length && issign?(y[pos]) - sign = true - pos += 1 + if (tm = PARSE_TIME_CB_RE.match(time_part)) + hour = tm[1].to_i + if tm[5] + ampm = tm[5].downcase + if ampm == 'p' + hour = (hour % 12) + 12 + else + hour = hour % 12 + end end - - c = false if sign # Signed => _comp = false - span = digit_span(y[pos..]) - c = false if span > 2 # Number of digits > 2 => _comp = false - - num_str = y[bp, (pos - bp) + span] # sign + number part - hash[:year] = num_str.to_i - end - end - - hash[:_bc] = true if bc - - # mon: Extract and set a number from m - unless m.nil? - pos = 0 - pos += 1 while pos < m.length && !m[pos].match?(/\d/) - - unless pos >= m.length # no_month - span = digit_span(m[pos..]) - hash[:mon] = m[pos, span].to_i + h[:hour] = hour + h[:min] = tm[2].to_i if tm[2] + h[:sec] = tm[3].to_i if tm[3] + h[:sec_fraction] = parse_sec_fraction(tm[4]) if tm[4] end - end - # mday: Extract and set numbers from d - unless d.nil? - pos = 0 - pos += 1 while pos < d.length && !d[pos].match?(/\d/) - - unless pos >= d.length # no_mday - span = digit_span(d[pos..]) - hash[:mday] = d[pos, span].to_i + if zone_part + h[:zone] = zone_part end end - - # _comp is written only if it is explicitly false - hash[:_comp] = false unless c.nil? - end - - # issign macro in date_parse.c. - def issign?(c) - c == '-' || c == '+' end - # digit_span in date_parse.c. - # Returns the length of the first consecutive digit in the string 's'. - def digit_span(s) - i = 0 - i += 1 while i < s.length && s[i].match?(/\d/) - - i - end - - # date_zone_to_diff in date_parse.c. - # Returns the number of seconds since UTC from a time zone name or offset string. - # Returns nil if no match occurs. - # - # Supported input types: - # 1. Zone names: "EST", "JST", "Eastern", "Central Pacific", ... - # 2. Suffixes: "Eastern standard time", "EST dst", ... - # "standard time" => As is - # "daylight time" / "dst" => Set offset to +3600 - # 3. Numeric offset: "+09:00", "-0530", "+9", "GMT+09:00", ... - # 4. Fractional time offset: "+9.5" (=+09:30), "+5.50" (=+05:30), ... - def date_zone_to_diff(str) - return nil if str.nil? || str.empty? - - s = str.dup - dst = false - - # Suffix removal: "time", "standard", "daylight", "dst" - w = str_end_with_word(s, "time") - if w > 0 - s = s[0, s.length - w] - - w2 = str_end_with_word(s, "standard") - if w2 > 0 - s = s[0, s.length - w2] - else - w2 = str_end_with_word(s, "daylight") - if w2 > 0 - s = s[0, s.length - w2] - dst = true - else - # "time" alone is not enough, so return - s = str.dup - end - end + def parse_eu(str, h) + if (m = PARSE_EU_RE.match(str)) + mon = ABBR_MONTH_NUM[m[2].downcase] + return false unless mon + bc = m[3] && m[3] =~ /\Ab/i ? true : false + s3e(h, m[4], mon, m[1], bc) + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + true else - w = str_end_with_word(s, "dst") - if w > 0 - s = s[0, s.length - w] - dst = true - end - end - - # --- zonetab search --- - # Normalize consecutive spaces into a single space before searching - zn = shrink_space(s) - z_offset = ZONE_TABLE[zn.downcase] - - if z_offset - z_offset += 3600 if dst - return z_offset - end - - # --- Parse numeric offsets --- - # Remove "GMT" and "UTC" prefixes - if zn.length > 3 && zn[0, 3].downcase =~ /\A(gmt|utc)\z/ - zn = zn[3..] - end - - # If there is no sign, it is not treated as a numeric offset - return nil if zn.empty? || (zn[0] != '+' && zn[0] != '-') - - sign = zn[0] == '-' ? -1 : 1 - zn = zn[1..] - return nil if zn.empty? - - # ':' separator: HH:MM or HH:MM:SS - if zn.include?(':') - return parse_colon_offset(zn, sign) - end - - # '.' or ',' separator: HH.fraction - if zn.include?('.') || zn.include?(',') - return parse_fractional_offset(zn, sign) + false end - - # Others: HH or HHMM or HHMMSS - parse_compact_offset(zn, sign) end - # str_end_with_word in date_parse.c. - # If the string 's' ends with "" (a word plus a space), - # Returns the length of that "" (including leading spaces). - # Otherwise, returns 0. - def str_end_with_word(s, word) - n = word.length - return 0 if s.length <= n - - # The last n characters match word (ignoring case) - return 0 unless s[-n..].casecmp?(word) - - # Is there a space just before it? - return 0 unless s[-(n + 1)].match?(/\s/) - - # Include consecutive spaces - count = n + 1 - count += 1 while count < s.length && s[-(count + 1)].match?(/\s/) - - count + def parse_us(str, h) + if (m = PARSE_US_RE.match(str)) + mon = ABBR_MONTH_NUM[m[1].downcase] + return false unless mon + bc = m[3] && m[3] =~ /\Ab/i ? true : false + s3e(h, m[4], mon, m[2], bc) + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + true + else + false + end end - # shrink_space in date_parse.c. - # Combines consecutive spaces into a single space. - # If the length is the same as the original (normalization unnecessary), - # return it as is. - def shrink_space(s) - result = [] - prev_space = false - s.each_char do |ch| - if ch.match?(/\s/) - result << ' ' unless prev_space - prev_space = true + def parse_iso(str, h) + if (m = PARSE_ISO_RE.match(str)) + y_s = m[1] + m_s = m[2] + d_s = m[3] + # Fast path: y is unambiguous year (3+ digits or signed), d is short + if y_s =~ /\A[-+]?\d{3,}\z/ && d_s =~ /\A\d{1,2}\z/ + h[:year] = y_s.to_i + h[:_comp] = false + h[:mon] = m_s.to_i + h[:mday] = d_s.to_i else - result << ch - prev_space = false + s3e(h, y_s, m_s, d_s, false) end + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + true + else + false end - result.join - end - - # parse_colon_offset - # Parse "+HH:MM" or "+HH:MM:SS" and return the number of seconds. - # Range checking: hour 0-23, min 0-59, sec 0-59 - def parse_colon_offset(zn, sign) - parts = zn.split(':') - hour = parts[0].to_i - return nil if hour < 0 || hour > 23 - - min = parts.length > 1 ? parts[1].to_i : 0 - return nil if min < 0 || min > 59 - - sec = parts.length > 2 ? parts[2].to_i : 0 - return nil if sec < 0 || sec > 59 - - sign * (sec + min * 60 + hour * 3600) end - # Parse "+HH.fraction" or "+HH,fraction" and return the number of seconds. - # - # C logic: - # Read the fraction string up to 7 digits. - # sec = (read value) * 36 - # If n <= 2: - # If n == 1, sec *= 10 (treat HH.n as HH.n0) - # Return value = sec + hour * 3600 (Integer) - # If n > 2: - # Return value = Rational(sec, 10**(n-2)) + hour * 3600 - # Convert to an Integer if the denominator is 1. - # - # Reason for the 36 factor: - # 1 hour = 3600 seconds. Each decimal point is 1/10. Time = 360 seconds. - # However, since the implementation handles it in two-digit units, multiply - # by 36 before dividing by 10^2. - # (3600 / 100 = 36) - def parse_fractional_offset(zn, sign) - sep = zn.include?('.') ? '.' : ',' - hh_str, frac_str = zn.split(sep, 2) - hour = hh_str.to_i - return nil if hour < 0 || hour > 23 - - # Up to 7 digits (C: "no over precision for offset") - max_digits = 7 - frac_str = frac_str[0, max_digits] - n = frac_str.length - return sign * (hour * 3600) if n == 0 - - sec = frac_str.to_i * 36 # Convert to seconds by factor 36 - - if sign == -1 - hour = -hour - sec = -sec - end - - if n <= 2 - sec *= 10 if n == 1 # HH.n => HH.n0 - sec + hour * 3600 + def parse_jis(str, h) + if (m = PARSE_JIS_RE.match(str)) + era_char = m[1].downcase + era_offset = JISX0301_ERA[era_char] + return false unless era_offset + h[:year] = m[2].to_i + era_offset + h[:mon] = m[3].to_i + h[:mday] = m[4].to_i + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + true else - # Rational for precise calculations - denom = 10 ** (n - 2) - offset = Rational(sec, denom) + (hour * 3600) - offset.denominator == 1 ? offset.to_i : offset + false + end + end + + def parse_vms(str, h) + if (m = PARSE_VMS11_RE.match(str)) + mon = ABBR_MONTH_NUM[m[2].downcase] + return false unless mon + s3e(h, m[3], mon, m[1], false) + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + true + elsif (m = PARSE_VMS12_RE.match(str)) + mon = ABBR_MONTH_NUM[m[1].downcase] + return false unless mon + s3e(h, m[3], mon, m[2], false) + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + true + else + false end end - # parse_compact_offset - # Parse consecutive numeric offsets without colons. - # HH (2 digits or less) - # HHM (3 digits: 1 digit for hour, 2 digits for min) - # HHMM (4 digits) - # HHMMM (5 digits: 2 digits for hour, 2 digits for min, 1 digit for sec) ... Rare in practical use - # HHMMSS (6 digits) - # - # C adjusts the leading padding width with "2 - l % 2". - # Ruby does the same calculation with length. - def parse_compact_offset(zn, sign) - l = zn.length - - # Only HH - return sign * zn.to_i * 3600 if l <= 2 - - # C: hour = scan_digits(&s[0], 2 - l % 2) - # min = scan_digits(&s[2 - l % 2], 2) - # sec = scan_digits(&s[4 - l % 2], 2) - # - # l=3 => hw=1 => hour=zn[0,1], min=zn[1,2] - # l=4 => hw=2 => hour=zn[0,2], min=zn[2,2] - # l=5 => hw=1 => hour=zn[0,1], min=zn[1,2], sec=zn[3,2] - # l=6 => hw=2 => hour=zn[0,2], min=zn[2,2], sec=zn[4,2] - hw = 2 - l % 2 # hour width: 2 for even, 1 for odd - hour = zn[0, hw].to_i - min = l >= 3 ? zn[hw, 2].to_i : 0 - sec = l >= 5 ? zn[hw + 2, 2].to_i : 0 - - sign * (sec + min * 60 + hour * 3600) - end - - # subx in date_parse.c. - # Matches pat against str. If it matches, replaces the matched - # portion of str (in-place) with rep (default: " ") and returns - # the MatchData. Returns nil on no match. - # - # This is the core mechanism C uses (via the SUBS macro) to - # prevent later parsers from re-matching already-consumed text. - def subx(str, pat, rep = " ") - m = pat.match(str) - return nil unless m - - str[m.begin(0), m.end(0) - m.begin(0)] = rep - m - end - - def check_class(str) - flags = 0 - flags |= HAVE_ALPHA if str.match?(/[a-zA-Z]/) - flags |= HAVE_DIGIT if str.match?(/\d/) - flags |= HAVE_DASH if str.include?('-') - flags |= HAVE_DOT if str.include?('.') - flags |= HAVE_SLASH if str.include?('/') - flags - end - - # C macro HAVE_ELEM_P(x) in date_parse.c. - # Note: C calls check_class(str) every time because str is - # modified by subx. We do the same here. - def have_elem_p?(str, required) - (check_class(str) & required) == required + def parse_sla(str, h) + if (m = PARSE_SLA_RE.match(str)) + s3e(h, m[1], m[2], m[3], false) + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + true + else + false + end end - # --- String type conversion (C's StringValue macro) --- - def string_value(str) - return str if str.is_a?(String) - if str.respond_to?(:to_str) - s = str.to_str - raise TypeError, "can't convert #{str.class} to String (#{str.class}#to_str gives #{s.class})" unless s.is_a?(String) - return s + def parse_dot(str, h) + if (m = PARSE_DOT_RE.match(str)) + s3e(h, m[1], m[2], m[3], false) + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + true + else + false end - raise TypeError, "no implicit conversion of #{str.class} into String" end - def check_string_limit(str, limit) - if limit && str.length > limit - raise ArgumentError, "string length (#{str.length}) exceeds the limit #{limit}" + def parse_iso2(str, h) + # iso21: week date + if (m = PARSE_ISO21_RE.match(str)) + if m[1] + y = m[1].to_i + h[:cwyear] = y + end + h[:cweek] = m[2].to_i + h[:cwday] = m[3].to_i if m[3] + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + return true end - end - # C: d_new_by_frags - # Date-only fragment-based constructor. - # Time fields in hash are ignored — use dt_new_by_frags (in datetime.rb) for DateTime. - def new_by_frags(hash, sg) - raise Error, "invalid date" if hash.nil? || hash.empty? + # iso22: -w-D + if (m = PARSE_ISO22_RE.match(str)) + h[:cwday] = m[1].to_i + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + return true + end - y = hash[:year] - m = hash[:mon] - d = hash[:mday] + # iso23: --MM-DD + if (m = PARSE_ISO23_RE.match(str)) + h[:mon] = m[1].to_i if m[1] + h[:mday] = m[2].to_i + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + return true + end - # Fast path: year+mon+mday present, no jd/yday - if !hash.key?(:jd) && !hash.key?(:yday) && y && m && d - raise Error, "invalid date" unless valid_civil?(y, m, d, sg) - obj = new(y, m, d, sg) - # Store parsed offset for deconstruct_keys([:zone]) without - # affecting JD calculations (don't use @of which triggers UTC conversion) - of = hash[:offset] - obj.instance_variable_set(:@parsed_offset, of) if of && of != 0 - return obj + # iso24: --MMDD + if (m = PARSE_ISO24_RE.match(str)) + h[:mon] = m[1].to_i + h[:mday] = m[2].to_i if m[2] + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + return true end - # Slow path — uses self (Date), so time-only patterns - # (e.g. '23:55') correctly fail: rt_complete_frags with Date class - # does not set :jd for :time pattern → rt__valid_date_frags_p returns nil. - hash = rt_rewrite_frags(hash) - hash = rt_complete_frags(self, hash) - jd = rt__valid_date_frags_p(hash, sg) + # iso25: YYYY-DDD (guard against fraction match) + unless str =~ /[,.]\d{2,4}-\d{3}\b/ + if (m = PARSE_ISO25_RE.match(str)) + h[:year] = m[1].to_i + h[:yday] = m[2].to_i + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + return true + end + end - raise Error, "invalid date" unless jd + # iso26: -DDD (guard against digit-DDD) + unless str =~ /\d-\d{3}\b/ + if (m = PARSE_ISO26_RE.match(str)) + h[:yday] = m[1].to_i + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + return true + end + end - self.jd(jd, sg) + false end - # C: rt_rewrite_frags - # Converts :seconds (from %s/%Q) into jd/hour/min/sec/sec_fraction fields. - # - # C implementation (date_core.c:4033): - # seconds = del_hash("seconds"); - # if (!NIL_P(seconds)) { - # if (!NIL_P(offset)) seconds = f_add(seconds, offset); - # d = f_idiv(seconds, DAY_IN_SECONDS); - # fr = f_mod(seconds, DAY_IN_SECONDS); - # h = f_idiv(fr, HOUR_IN_SECONDS); fr = f_mod(fr, HOUR_IN_SECONDS); - # min= f_idiv(fr, MINUTE_IN_SECONDS); fr = f_mod(fr, MINUTE_IN_SECONDS); - # s = f_idiv(fr, 1); fr = f_mod(fr, 1); - # set jd = UNIX_EPOCH_IN_CJD + d, hour, min, sec, sec_fraction - # } - # - # Ruby's .div() and % match C's f_idiv (rb_intern("div")) and f_mod ('%'). - # Both use floor semantics, correctly handling negative and Rational values. - def rt_rewrite_frags(hash) - seconds = hash.delete(:seconds) - return hash unless seconds - - offset = hash[:offset] - seconds = seconds + offset if offset - - # Day count from Unix epoch - # C: d = f_idiv(seconds, DAY_IN_SECONDS) - d = seconds.div(DAY_IN_SECONDS) - fr = seconds % DAY_IN_SECONDS - - # Decompose remainder into h:min:s.frac - h = fr.div(HOUR_IN_SECONDS) - fr = fr % HOUR_IN_SECONDS - - min = fr.div(MINUTE_IN_SECONDS) - fr = fr % MINUTE_IN_SECONDS - - s = fr.div(1) - fr = fr % 1 - - # C: UNIX_EPOCH_IN_CJD = 2440588 (1970-01-01 in Chronological JD) - hash[:jd] = 2440588 + d - hash[:hour] = h - hash[:min] = min - hash[:sec] = s - hash[:sec_fraction] = fr - hash + def parse_year(str, h) + if (m = PARSE_YEAR_RE.match(str)) + h[:year] = m[1].to_i + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + true + else + false + end end - # C: rt_complete_frags (date_core.c:4071) - # - # Algorithm: - # 1. Score each of 11 field-set patterns against hash, pick highest match count. - # 2. For the winning named pattern, fill leading missing date fields from Date.today - # and set defaults for trailing date fields. - # 3. Special case: "time" pattern + DateTime class → set :jd from today. - # 4. Default :hour/:min/:sec to 0; clamp :sec to 59. - # - # Pattern table (C's static tab): - # [name, [fields...]] - # ────────────────────────── - # [:time, [:hour, :min, :sec]] - # [nil, [:jd]] - # [:ordinal, [:year, :yday, :hour, :min, :sec]] - # [:civil, [:year, :mon, :mday, :hour, :min, :sec]] - # [:commercial, [:cwyear, :cweek, :cwday, :hour, :min, :sec]] - # [:wday, [:wday, :hour, :min, :sec]] - # [:wnum0, [:year, :wnum0, :wday, :hour, :min, :sec]] - # [:wnum1, [:year, :wnum1, :wday, :hour, :min, :sec]] - # [nil, [:cwyear, :cweek, :wday, :hour, :min, :sec]] - # [nil, [:year, :wnum0, :cwday, :hour, :min, :sec]] - # [nil, [:year, :wnum1, :cwday, :hour, :min, :sec]] - # - def rt_complete_frags(klass, hash) - # Step 1: Find best matching pattern - # C: for each tab entry, count how many fields exist in hash; pick max. - # First match wins on tie (strict >). - best_key = nil - best_fields = nil - best_count = 0 - - COMPLETE_FRAGS_TABLE.each do |key, fields| - count = fields.count { |f| hash.key?(f) } - if count > best_count - best_count = count - best_key = key - best_fields = fields + def parse_mon(str, h) + if (m = PARSE_MON_RE.match(str)) + mon = ABBR_MONTH_NUM[m[1].downcase] + if mon + h[:mon] = mon + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + return true end end + false + end - # Step 2: Complete missing fields for named patterns - # C: if (!NIL_P(k) && (RARRAY_LEN(a) > e)) - d = nil # lazy Date.today + def parse_mday(str, h) + if (m = PARSE_MDAY_RE.match(str)) + h[:mday] = m[1].to_i + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + true + else + false + end + end - if best_key && best_fields && best_fields.length > best_count - case best_key + def parse_ddd(str, h) + if (m = PARSE_DDD_RE.match(str)) + sign = m[1] + s2 = m[2] + s3 = m[3] + s4 = m[4] + s5 = m[5] - when :ordinal - # C: fill year from today if missing, default yday=1 - unless hash.key?(:year) - d ||= today - hash[:year] = d.year + l2 = s2.length + case l2 + when 2 + if s3.nil? && s4 + h[:sec] = s2.to_i + else + h[:mday] = s2.to_i + end + when 4 + if s3.nil? && s4 + h[:sec] = s2[2, 2].to_i + h[:min] = s2[0, 2].to_i + else + h[:mon] = s2[0, 2].to_i + h[:mday] = s2[2, 2].to_i + end + when 6 + if s3.nil? && s4 + h[:sec] = s2[4, 2].to_i + h[:min] = s2[2, 2].to_i + h[:hour] = s2[0, 2].to_i + else + h[:year] = (sign.to_s + s2[0, 2]).to_i + h[:mon] = s2[2, 2].to_i + h[:mday] = s2[4, 2].to_i end - hash[:yday] ||= 1 - - when :civil - # C: fill leading missing fields from today, stop at first present field. - # Then default mon=1, mday=1. - # - # The loop iterates [:year, :mon, :mday, :hour, :min, :sec]. - # For each field, if it's already in hash → break. - # Otherwise fill from today via d.send(field). - # In practice, the loop only reaches date fields (:year/:mon/:mday) - # because at least one date field must be present for civil to win. - best_fields.each do |f| - break if hash.key?(f) - d ||= today - hash[f] = d.send(f) + when 8, 10, 12, 14 + if s3.nil? && s4 + # read from end: sec,min,hour,mday,mon,year + pos = l2 + h[:sec] = s2[pos - 2, 2].to_i + pos -= 2 + h[:min] = s2[pos - 2, 2].to_i + pos -= 2 + h[:hour] = s2[pos - 2, 2].to_i + pos -= 2 + if pos >= 2 + h[:mday] = s2[pos - 2, 2].to_i + pos -= 2 + if pos >= 2 + h[:mon] = s2[pos - 2, 2].to_i + pos -= 2 + h[:year] = (sign.to_s + s2[0, pos]).to_i if pos > 0 + end + end + else + h[:year] = (sign.to_s + s2[0, 4]).to_i + h[:mon] = s2[4, 2].to_i if l2 >= 6 + h[:mday] = s2[6, 2].to_i if l2 >= 8 + h[:hour] = s2[8, 2].to_i if l2 >= 10 + h[:min] = s2[10, 2].to_i if l2 >= 12 + h[:sec] = s2[12, 2].to_i if l2 >= 14 + h[:_comp] = false end - hash[:mon] ||= 1 - hash[:mday] ||= 1 - - when :commercial - # C: same leading-fill pattern, then default cweek=1, cwday=1 - best_fields.each do |f| - break if hash.key?(f) - d ||= today - hash[f] = d.send(f) + when 3 + if s3.nil? && s4 + h[:sec] = s2[1, 2].to_i + h[:min] = s2[0, 1].to_i + else + h[:yday] = s2.to_i end - hash[:cweek] ||= 1 - hash[:cwday] ||= 1 - - when :wday - # C: set_hash("jd", d_lite_jd(f_add(f_sub(d, d_lite_wday(d)), ref_hash("wday")))) - # → jd of (today - today.wday + parsed_wday) - d ||= today - hash[:jd] = (d - d.wday + hash[:wday]).jd - - when :wnum0 - # C: leading-fill from today, then default wnum0=0, wday=0 - best_fields.each do |f| - break if hash.key?(f) - d ||= today - # :year is the only field that can be missing before :wnum0 in practice - hash[f] = d.send(f) if d.respond_to?(f) + when 5 + if s3.nil? && s4 + h[:sec] = s2[3, 2].to_i + h[:min] = s2[1, 2].to_i + h[:hour] = s2[0, 1].to_i + else + h[:year] = (sign.to_s + s2[0, 2]).to_i + h[:yday] = s2[2, 3].to_i end - hash[:wnum0] ||= 0 - hash[:wday] ||= 0 - - when :wnum1 - # C: leading-fill from today, then default wnum1=0, wday=1 - best_fields.each do |f| - break if hash.key?(f) - d ||= today - hash[f] = d.send(f) if d.respond_to?(f) + when 7 + if s3.nil? && s4 + h[:sec] = s2[5, 2].to_i + h[:min] = s2[3, 2].to_i + h[:hour] = s2[1, 2].to_i + h[:mday] = s2[0, 1].to_i + else + h[:year] = (sign.to_s + s2[0, 4]).to_i + h[:yday] = s2[4, 3].to_i + h[:_comp] = false end - hash[:wnum1] ||= 0 - hash[:wday] ||= 1 end - end - # Step 3: "time" pattern special case - # C: if (k == sym("time")) { if (f_le_p(klass, cDateTime)) { ... } } - # For DateTime (or subclass), time-only input gets :jd from today. - # For Date, time-only input will fail validation (no date fields). - if best_key == :time - if defined?(DateTime) && klass <= DateTime - d ||= today - hash[:jd] ||= d.jd + # s3 (time portion from continuous digits after separator) + if s3 && !s3.empty? + l3 = s3.length + if s4 + # read from end + case l3 + when 2 + h[:sec] = s3[0, 2].to_i + when 4 + h[:sec] = s3[2, 2].to_i + h[:min] = s3[0, 2].to_i + when 6 + h[:sec] = s3[4, 2].to_i + h[:min] = s3[2, 2].to_i + h[:hour] = s3[0, 2].to_i + end + else + # read from start + h[:hour] = s3[0, 2].to_i if l3 >= 2 + h[:min] = s3[2, 2].to_i if l3 >= 4 + h[:sec] = s3[4, 2].to_i if l3 >= 6 + end + end + + # s4: sec_fraction + if s4 && !s4.empty? + h[:sec_fraction] = parse_sec_fraction(s4) + end + + # s5: zone + if s5 && !s5.empty? + zone = s5 + if zone.start_with?('[') + zone = zone[1...-1] # strip brackets + # Format: [offset:zonename] or [offset zonename] or [offset] or [zonename] + if (zm = zone.match(/\A([-+]?\d+(?:[,.]\d+)?):(.+)/)) + # +9:JST, -5:EST, +12:XXX YYY ZZZ + h[:zone] = zm[2].strip + off_s = zm[1] + off_s = "+#{off_s}" unless off_s.start_with?('+') || off_s.start_with?('-') + h[:offset] = fast_zone_offset(off_s) + elsif (zm = zone.match(/\A([-+]?\d+(?:[,.]\d+)?)\s+(\S.+)/)) + # Number followed by space and non-empty name + h[:zone] = zm[2] + off_s = zm[1] + off_s = "+#{off_s}" unless off_s.start_with?('+') || off_s.start_with?('-') + h[:offset] = fast_zone_offset(off_s) + else + # Could be just a number with optional trailing space: [9], [-9], [9 ] + h[:zone] = zone + stripped = zone.strip + if stripped =~ /\A([-+]?\d+(?:[,.]\d+)?)\z/ + off_s = $1 + off_s = "+#{off_s}" unless off_s.start_with?('+') || off_s.start_with?('-') + h[:offset] = fast_zone_offset(off_s) + end + end + else + h[:zone] = zone + end end - end - # Step 4: Default time fields, clamp sec - # C: if (NIL_P(ref_hash("hour"))) set_hash("hour", 0); - # if (NIL_P(ref_hash("min"))) set_hash("min", 0); - # if (NIL_P(ref_hash("sec"))) set_hash("sec", 0); - # else if (ref_hash("sec") > 59) set_hash("sec", 59); - hash[:hour] ||= 0 - hash[:min] ||= 0 - if !hash.key?(:sec) - hash[:sec] = 0 - elsif hash[:sec] > 59 - hash[:sec] = 59 + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + true + else + false end + end - hash + def parse_bc_post(str, h) + if (m = PARSE_BC_RE.match(str)) + h[:_bc] = true + str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + end end - # C: rt__valid_date_frags_p (date_core.c:4379) - # Tries 6 strategies to produce a valid JD from hash fragments: - # jd → ordinal → civil → commercial → wnum0 → wnum1 - def rt__valid_date_frags_p(hash, sg) - # 1. Try jd (C: rt__valid_jd_p just returns jd) - if hash[:jd] - return hash[:jd] - end - - # 2. Try ordinal: year + yday - if hash[:yday] && hash[:year] - y = hash[:year] - yd = hash[:yday] - if valid_ordinal?(y, yd, sg) - return ordinal(y, yd, sg).jd + def parse_frag(str, h) + if (m = PARSE_FRAG_RE.match(str)) + v = m[1].to_i + if h.key?(:hour) && !h.key?(:mday) + h[:mday] = v if v >= 1 && v <= 31 + elsif h.key?(:mday) && !h.key?(:hour) + h[:hour] = v if v >= 0 && v <= 24 end end + end - # 3. Try civil: year + mon + mday - if hash[:mday] && hash[:mon] && hash[:year] - y = hash[:year] - m = hash[:mon] - d = hash[:mday] - if valid_civil?(y, m, d, sg) - return new(y, m, d, sg).jd - end + # s3e: 3-element (year, month, day) disambiguation + # Faithfully mirrors the C implementation's s3e() logic. + # Arguments: y, m, d are strings (or Integer for m when month name was parsed) + def s3e(h, y, m, d, bc) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + # Fast path: y is unambiguously a year (3+ digits or signed), m and d are simple digits. + # This covers ISO "2001-02-03" but not ambiguous cases like "23/5/1999". + if y && m && d && !bc && y.is_a?(String) && m.is_a?(String) && d.is_a?(String) && + !y.start_with?("'") && !d.start_with?("'") && + y =~ /\A([-+])?\d{3,}\z/ && m =~ /\A\d+\z/ && d =~ /\A\d{1,2}\z/ + h[:year] = y.to_i + h[:_comp] = false + h[:mon] = m.to_i + h[:mday] = d.to_i + return end - # 4. Try commercial: cwyear + cweek + cwday/wday - # C: wday = ref_hash("cwday"); - # if (NIL_P(wday)) { wday = ref_hash("wday"); if wday==0 → wday=7; } - begin - wday = hash[:cwday] - if wday.nil? - wday = hash[:wday] - wday = 7 if wday && wday == 0 # Sunday: wday 0 → cwday 7 - end + m = m.to_s if m.is_a?(Integer) - if wday && hash[:cweek] && hash[:cwyear] - jd = rt__valid_commercial_p(hash[:cwyear], hash[:cweek], wday, sg) - return jd if jd - end + # Step 1: If y && m are present but d is nil, rotate: d=m, m=y, y=nil + if y && m && d.nil? + d = m + m = y + y = nil end - # 5. Try wnum0: year + wnum0 + wday (Sunday-first week, %U) - # C: wday = ref_hash("wday"); - # if (NIL_P(wday)) { wday = ref_hash("cwday"); if cwday==7 → wday=0; } - begin - wday = hash[:wday] - if wday.nil? - wday = hash[:cwday] - wday = 0 if wday && wday == 7 # Sunday: cwday 7 → wday 0 - end - - if wday && hash[:wnum0] && hash[:year] - jd = rt__valid_weeknum_p(hash[:year], hash[:wnum0], wday, 0, sg) - return jd if jd + # Step 2: If y is nil but d is present, check if d looks like a year + if y.nil? && d + ds = d.to_s + digits = ds.sub(/\A'?-?/, '').sub(/(?:st|nd|rd|th)\z/i, '') + if digits.length > 2 || ds.start_with?("'") + y = d + d = nil end end - # 6. Try wnum1: year + wnum1 + wday (Monday-first week, %W) - # C: wday = ref_hash("wday"); if NIL → wday = ref_hash("cwday"); - # if wday → wday = (wday - 1) % 7 - begin - wday = hash[:wday] - wday = hash[:cwday] if wday.nil? - if wday - wday = (wday - 1) % 7 # Convert: 0(Sun)→6, 1(Mon)→0, ..., 7(Sun)→6 + # Step 3: Parse y - extract numeric value and determine _comp flag + year_val = nil + comp_flag = nil + if y + ys_raw = y.to_s + if ys_raw.start_with?("'") + year_val = ys_raw[1..].to_i + comp_flag = true + else + # Match digits (with optional leading sign), check for trailing non-digit + if ys_raw =~ /\A[^-+\d]*([-+]?\d+)/ + num_s = $1 + rest = ys_raw[$~.end(0)..] + if rest && !rest.empty? && rest =~ /[^\d]/ + # trailing non-digit (like "st" in "1st"): this y becomes d, old d becomes y + old_d = d + d = num_s + year_val = nil + comp_flag = nil + if old_d + s3eparse_year(old_d.to_s)&.then do |v, c| + year_val = v + comp_flag = c + end + end + else + year_val = num_s.to_i + if num_s.start_with?('-') || num_s.start_with?('+') || num_s.sub(/\A[-+]/, '').length > 2 + comp_flag = false + end + end + end end + end - if wday && hash[:wnum1] && hash[:year] - jd = rt__valid_weeknum_p(hash[:year], hash[:wnum1], wday, 1, sg) - return jd if jd + # Step 4: Check m - if it looks like a year (apostrophe or > 2 digits), swap US→BE + if m.is_a?(String) + ms_digits = m.sub(/\A'?-?/, '').sub(/(?:st|nd|rd|th)\z/i, '') + if m.start_with?("'") || ms_digits.length > 2 + # Rotate: old_y=y, y=m, m=d, d=old_y_string + old_y = y + y = m + m = d + d = old_y + + # Re-parse y + ys = y.to_s.sub(/(?:st|nd|rd|th)\z/i, '') + if ys.start_with?("'") + year_val = ys[1..].to_i + comp_flag = true + elsif ys =~ /([-+]?\d+)/ + num_s = $1 + year_val = num_s.to_i + comp_flag = (num_s.start_with?('-') || num_s.start_with?('+') || num_s.sub(/\A[-+]/, '').length > 2) ? false : nil + end end end - nil - end - - # C: rt__valid_commercial_p (date_core.c:4347) - # Validates commercial date and returns JD, or nil. - def rt__valid_commercial_p(y, w, d, sg) - if valid_commercial?(y, w, d, sg) - return commercial(y, w, d, sg).jd + # Step 5: Check d - if it looks like a year, swap with y + if d.is_a?(String) + ds_digits = d.sub(/\A'?-?/, '').sub(/(?:st|nd|rd|th)\z/i, '') + if d.start_with?("'") || ds_digits.length > 2 + old_y = y + # d becomes year + ys = d.sub(/(?:st|nd|rd|th)\z/i, '') + if ys.start_with?("'") + year_val = ys[1..].to_i + comp_flag = true + elsif ys =~ /([-+]?\d+)/ + num_s = $1 + year_val = num_s.to_i + comp_flag = (num_s.start_with?('-') || num_s.start_with?('+') || num_s.sub(/\A[-+]/, '').length > 2) ? false : nil + end + d = old_y + end end - nil - end - - # C: rt__valid_weeknum_p → valid_weeknum_p → c_valid_weeknum_p (date_core.c:1009) - # Validates weeknum-based date and returns JD, or nil. - # f=0 for Sunday-first (%U), f=1 for Monday-first (%W). - def rt__valid_weeknum_p(y, w, d, f, sg) - # C: if (d < 0) d += 7; - d += 7 if d < 0 - # C: if (w < 0) { ... normalize via next year ... } - if w < 0 - rjd2 = c_weeknum_to_jd(y + 1, 1, f, f, sg) - ry2, rw2, _ = c_jd_to_weeknum(rjd2 + w * 7, f, sg) - return nil if ry2 != y - w = rw2 - end - jd = c_weeknum_to_jd(y, w, d, f, sg) - ry, rw, rd = c_jd_to_weeknum(jd, f, sg) - return nil if y != ry || w != rw || d != rd - jd - end - - # C: c_weeknum_to_jd (date_core.c:663) - # Converts (year, week_number, day_in_week, first_day_flag, sg) → JD. - # - # C formula: - # c_find_fdoy(y, sg, &rjd2, &ns2); - # rjd2 += 6; - # *rjd = (rjd2 - MOD(((rjd2 - f) + 1), 7) - 7) + 7 * w + d; - def c_weeknum_to_jd(y, w, d, f, sg) - fdoy_jd, _ = c_find_fdoy(y, sg) - fdoy_jd += 6 - (fdoy_jd - ((fdoy_jd - f + 1) % 7) - 7) + 7 * w + d - end - - # C: c_jd_to_weeknum (date_core.c:674) - # Converts JD → [year, week_number, day_in_week]. - # Class-method version (the instance method in core.rb calls self.class.send). - # - # C formula: - # c_jd_to_civil(jd, sg, &ry, ...); - # c_find_fdoy(ry, sg, &rjd, ...); - # rjd += 6; - # j = jd - (rjd - MOD((rjd - f) + 1, 7)) + 7; - # rw = DIV(j, 7); - # rd = MOD(j, 7); - def c_jd_to_weeknum(jd, f, sg) - ry, _, _ = c_jd_to_civil(jd, sg) - fdoy_jd, _ = c_find_fdoy(ry, sg) - fdoy_jd += 6 - - j = jd - (fdoy_jd - ((fdoy_jd - f + 1) % 7)) + 7 - rw = j.div(7) - rd = j % 7 - - [ry, rw, rd] - end - - # --- comp_year helpers (C's comp_year69, comp_year50) --- - def comp_year69(y) - y >= 69 ? y + 1900 : y + 2000 - end - - def comp_year50(y) - y >= 50 ? y + 1900 : y + 2000 - end - - # --- sec_fraction helper --- - def sec_fraction(frac_str) - Rational(frac_str.to_i, 10 ** frac_str.length) - end - - # ================================================================ - # Format-specific parsers (date_parse.c) - # ================================================================ - - # --- ISO 8601 --- - def date__iso8601(str) - hash = {} - return hash if str.nil? || str.empty? + # Set year + h[:year] = year_val if year_val + h[:_comp] = comp_flag unless comp_flag.nil? + h[:_bc] = true if bc - if (m = ISO8601_EXT_DATETIME_PAT.match(str)) - iso8601_ext_datetime_cb(m, hash) - elsif (m = ISO8601_BAS_DATETIME_PAT.match(str)) - iso8601_bas_datetime_cb(m, hash) - elsif (m = ISO8601_EXT_TIME_PAT.match(str)) - iso8601_time_cb(m, hash) - elsif (m = ISO8601_BAS_TIME_PAT.match(str)) - iso8601_time_cb(m, hash) - end - hash - end - - def iso8601_ext_datetime_cb(m, hash) - if m[1] - hash[:mday] = m[3].to_i if m[3] - if m[1] != '-' - y = m[1].to_i - y = comp_year69(y) if m[1].length < 4 - hash[:year] = y - end - if m[2].nil? - return false if m[1] != '-' + # Set mon + if m + if m.is_a?(String) + ms = m.sub(/(?:st|nd|rd|th)\z/i, '') + h[:mon] = $1.to_i if ms =~ /(\d+)/ else - hash[:mon] = m[2].to_i - end - elsif m[5] - hash[:yday] = m[5].to_i - if m[4] - y = m[4].to_i - y = comp_year69(y) if m[4].length < 4 - hash[:year] = y - end - elsif m[8] - hash[:cweek] = m[7].to_i - hash[:cwday] = m[8].to_i - if m[6] - y = m[6].to_i - y = comp_year69(y) if m[6].length < 4 - hash[:cwyear] = y + h[:mon] = m.to_i end - elsif m[9] - hash[:cwday] = m[9].to_i - end - - if m[10] - hash[:hour] = m[10].to_i - hash[:min] = m[11].to_i - hash[:sec] = m[12].to_i if m[12] - end - hash[:sec_fraction] = sec_fraction(m[13]) if m[13] - if m[14] - hash[:zone] = m[14] - hash[:offset] = date_zone_to_diff(m[14]) end - true - end - def iso8601_bas_datetime_cb(m, hash) - if m[3] - hash[:mday] = m[3].to_i - if m[1] != '--' - y = m[1].to_i - y = comp_year69(y) if m[1].length < 4 - hash[:year] = y - end - if m[2][0] == '-' - return false if m[1] != '--' + # Set mday + if d + if d.is_a?(String) + ds = d.sub(/(?:st|nd|rd|th)\z/i, '') + h[:mday] = $1.to_i if ds =~ /(\d+)/ else - hash[:mon] = m[2].to_i + h[:mday] = d.to_i end - elsif m[5] - hash[:yday] = m[5].to_i - y = m[4].to_i - y = comp_year69(y) if m[4].length < 4 - hash[:year] = y - elsif m[6] - hash[:yday] = m[6].to_i - elsif m[9] - hash[:cweek] = m[8].to_i - hash[:cwday] = m[9].to_i - y = m[7].to_i - y = comp_year69(y) if m[7].length < 4 - hash[:cwyear] = y - elsif m[11] - hash[:cweek] = m[10].to_i - hash[:cwday] = m[11].to_i - elsif m[12] - hash[:cwday] = m[12].to_i - end - - if m[13] - hash[:hour] = m[13].to_i - hash[:min] = m[14].to_i - hash[:sec] = m[15].to_i if m[15] - end - hash[:sec_fraction] = sec_fraction(m[16]) if m[16] - if m[17] - hash[:zone] = m[17] - hash[:offset] = date_zone_to_diff(m[17]) - end - true - end - - def iso8601_time_cb(m, hash) - hash[:hour] = m[1].to_i - hash[:min] = m[2].to_i - hash[:sec] = m[3].to_i if m[3] - hash[:sec_fraction] = sec_fraction(m[4]) if m[4] - if m[5] - hash[:zone] = m[5] - hash[:offset] = date_zone_to_diff(m[5]) end - true - end - - # --- RFC 3339 --- - - def date__rfc3339(str) - hash = {} - return hash if str.nil? || str.empty? - - m = RFC3339_PAT.match(str) - return hash unless m - - hash[:year] = m[1].to_i - hash[:mon] = m[2].to_i - hash[:mday] = m[3].to_i - hash[:hour] = m[4].to_i - hash[:min] = m[5].to_i - hash[:sec] = m[6].to_i - hash[:zone] = m[8] - hash[:offset] = date_zone_to_diff(m[8]) - hash[:sec_fraction] = sec_fraction(m[7]) if m[7] - hash end - # --- XML Schema --- - - def date__xmlschema(str) - hash = {} - return hash if str.nil? || str.empty? - - if (m = XMLSCHEMA_DATETIME_PAT.match(str)) - hash[:year] = m[1].to_i - hash[:mon] = m[2].to_i if m[2] - hash[:mday] = m[3].to_i if m[3] - hash[:hour] = m[4].to_i if m[4] - hash[:min] = m[5].to_i if m[5] - hash[:sec] = m[6].to_i if m[6] - hash[:sec_fraction] = sec_fraction(m[7]) if m[7] - if m[8] - hash[:zone] = m[8] - hash[:offset] = date_zone_to_diff(m[8]) - end - elsif (m = XMLSCHEMA_TIME_PAT.match(str)) - hash[:hour] = m[1].to_i - hash[:min] = m[2].to_i - hash[:sec] = m[3].to_i if m[3] - hash[:sec_fraction] = sec_fraction(m[4]) if m[4] - if m[5] - hash[:zone] = m[5] - hash[:offset] = date_zone_to_diff(m[5]) - end - elsif (m = XMLSCHEMA_TRUNC_PAT.match(str)) - hash[:mon] = m[1].to_i if m[1] - hash[:mday] = m[2].to_i if m[2] - hash[:mday] = m[3].to_i if m[3] - if m[4] - hash[:zone] = m[4] - hash[:offset] = date_zone_to_diff(m[4]) - end + # Helper: parse a string as a year value, returning [year_val, comp_flag] or nil + def s3eparse_year(s) + if s.start_with?("'") + [s[1..].to_i, true] + elsif s =~ /\A[^-+\d]*([-+]?\d+)/ + num_s = $1 + cf = (num_s.start_with?('-') || num_s.start_with?('+') || num_s.sub(/\A[-+]/, '').length > 2) ? false : nil + [num_s.to_i, cf] end - hash - end - - # --- RFC 2822 --- - - def date__rfc2822(str) - hash = {} - return hash if str.nil? || str.empty? - - m = PARSE_RFC2822_PAT.match(str) - return hash unless m - - hash[:wday] = day_num(m[1]) if m[1] - hash[:mday] = m[2].to_i - hash[:mon] = mon_num(m[3]) - y = m[4].to_i - y = comp_year50(y) if m[4].length < 4 - hash[:year] = y - hash[:hour] = m[5].to_i - hash[:min] = m[6].to_i - hash[:sec] = m[7].to_i if m[7] - hash[:zone] = m[8] - hash[:offset] = date_zone_to_diff(m[8]) - hash - end - - # --- HTTP date --- - - def date__httpdate(str) - hash = {} - return hash if str.nil? || str.empty? - - if (m = PARSE_HTTPDATE_TYPE1_PAT.match(str)) - hash[:wday] = day_num(m[1]) - hash[:mday] = m[2].to_i - hash[:mon] = mon_num(m[3]) - hash[:year] = m[4].to_i - hash[:hour] = m[5].to_i - hash[:min] = m[6].to_i - hash[:sec] = m[7].to_i - hash[:zone] = m[8] - hash[:offset] = 0 - elsif (m = PARSE_HTTPDATE_TYPE2_PAT.match(str)) - hash[:wday] = day_num(m[1]) - hash[:mday] = m[2].to_i - hash[:mon] = mon_num(m[3]) - y = m[4].to_i - y = comp_year69(y) if y >= 0 && y <= 99 - hash[:year] = y - hash[:hour] = m[5].to_i - hash[:min] = m[6].to_i - hash[:sec] = m[7].to_i - hash[:zone] = m[8] - hash[:offset] = 0 - elsif (m = PARSE_HTTPDATE_TYPE3_PAT.match(str)) - hash[:wday] = day_num(m[1]) - hash[:mon] = mon_num(m[2]) - hash[:mday] = m[3].to_i - hash[:hour] = m[4].to_i - hash[:min] = m[5].to_i - hash[:sec] = m[6].to_i - hash[:year] = m[7].to_i - end - hash end - # --- JIS X 0301 --- + # ------------------------------------------------------------------ + # Fast Date construction + # ------------------------------------------------------------------ - def date__jisx0301(str) - hash = {} - return hash if str.nil? || str.empty? - - m = PARSE_JISX0301_PAT.match(str) - if m - era = m[1] || JISX0301_DEFAULT_ERA - ep = gengo(era) - hash[:year] = ep + m[2].to_i - hash[:mon] = m[3].to_i - hash[:mday] = m[4].to_i - if m[5] - hash[:hour] = m[5].to_i - hash[:min] = m[6].to_i if m[6] - hash[:sec] = m[7].to_i if m[7] - end - hash[:sec_fraction] = sec_fraction(m[8]) if m[8] && !m[8].empty? - if m[9] - hash[:zone] = m[9] - hash[:offset] = date_zone_to_diff(m[9]) + # Fast Date construction: when year/mon/mday are all present and no + # complex keys (jd, yday, cwyear, wday, wnum, seconds) exist, skip + # the full _sp_complete_frags pipeline and directly validate civil date. + def fast_new_date(hash, sg) + raise Error, 'invalid date' if hash.nil? || hash.empty? + y = hash[:year] + m = hash[:mon] + d = hash[:mday] + if y && m && d && + !hash.key?(:jd) && !hash.key?(:yday) && !hash.key?(:cwyear) && + !hash.key?(:wnum0) && !hash.key?(:wnum1) && !hash.key?(:seconds) + # Ultra-fast path: inline Gregorian JD for obviously valid dates + # (year > 1582 ensures JD > ITALY for any month/day; d <= 28 is always valid) + if y >= 1583 && m >= 1 && m <= 12 && d >= 1 && d <= 28 && sg <= 2299161 + gy = m <= 2 ? y - 1 : y + a = gy / 100 + _new_from_jd((1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[m] + d - 1524 + 2 - a + a / 4, sg) + else + jd = internal_valid_civil?(y, m, d, sg) + raise Error, 'invalid date' if jd.nil? + _new_from_jd(jd, sg) end else - # Fallback to iso8601 - hash = date__iso8601(str) + _new_by_frags(hash, sg) end - hash end + end end diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index b4e3f020..d86ad7a9 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -1,5 +1,7 @@ -# Implementation of ruby/date/ext/date/date_strftime.c +# frozen_string_literal: true + class Date + # call-seq: # strftime(format = '%F') -> string # @@ -10,746 +12,563 @@ class Date # # For other formats, see # {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]. - def strftime(format = STRFTIME_DEFAULT_FMT) - # If format is not a string, convert it to a string. - format = format.to_str unless format.is_a?(String) - - # Check for ASCII compatible encoding. - raise ArgumentError, "format should have ASCII compatible encoding" unless format.encoding.ascii_compatible? - - # Empty format returns empty string - return '' if format.empty? - - # Fast path: simple Date (no time/offset, @nth == 0) with civil fields cached. - # Covers the most common case for Date objects created via Date.new or Date.civil. - if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil && !format.include?("\0") - y = @year - case format - when '%Y-%m-%d', '%F' - str = if y >= 0 && y <= 9999 - "#{FOUR_DIGIT[y]}-#{TWO_DIGIT[@month]}-#{TWO_DIGIT[@day]}" - elsif y >= 0 - sprintf("%04d-%02d-%02d", y, @month, @day) - else - sprintf("%05d-%02d-%02d", y, @month, @day) - end - return str.force_encoding(format.encoding) - when '%Y-%m-%dT%H:%M:%S%z' - str = if y >= 0 && y <= 9999 - "#{FOUR_DIGIT[y]}-#{TWO_DIGIT[@month]}-#{TWO_DIGIT[@day]}T00:00:00+0000" - elsif y >= 0 - sprintf("%04d-%02d-%02dT00:00:00+0000", y, @month, @day) - else - sprintf("%05d-%02d-%02dT00:00:00+0000", y, @month, @day) - end - return str.force_encoding(format.encoding) - when '%x' - # %x = %m/%d/%y - str = "#{TWO_DIGIT[@month]}/#{TWO_DIGIT[@day]}/#{TWO_DIGIT[y % 100]}" - return str.force_encoding(format.encoding) - end - - # Formats that also require wday (needs @jd). - if @has_jd - wday = (@jd + 1) % 7 - case format - when '%c' - # %c = %a %b %e %H:%M:%S %Y (always 24 chars for 4-digit year) - ed = @day < 10 ? " #{@day}" : @day.to_s - y_str = (y >= 0 && y <= 9999) ? FOUR_DIGIT[y] : (y >= 0 ? sprintf("%04d", y) : sprintf("%05d", y)) - str = "#{ABBR_DAYNAMES[wday]} #{ABBR_MONTHNAMES[@month]} #{ed} 00:00:00 #{y_str}" - return str.force_encoding(format.encoding) - when '%A, %B %d, %Y' - y_str = (y >= 0 && y <= 9999) ? FOUR_DIGIT[y] : (y >= 0 ? sprintf("%04d", y) : sprintf("%05d", y)) - str = "#{DAYNAMES[wday]}, #{MONTHNAMES[@month]} #{TWO_DIGIT[@day]}, #{y_str}" - return str.force_encoding(format.encoding) - end - end + def strftime(format = DEFAULT_STRFTIME_FMT) + if format.equal?(DEFAULT_STRFTIME_FMT) + _civil unless @year + return _fast_ymd.force_encoding(Encoding::US_ASCII) end - - # What to do if format string contains a "\0". - if format.include?("\0") - result = String.new - parts = format.split("\0", -1) - - parts.each_with_index do |part, i| - result << strftime_format(part) unless part.empty? - result << "\0" if i < parts.length - 1 - end - - result.force_encoding(format.encoding) - - return result + fmt = format.to_str + if fmt == YMD_FMT + _civil unless @year + return _fast_ymd.force_encoding(Encoding::US_ASCII) end - - # Normal processing without "\0" in format string. - result = strftime_format(format) - result.force_encoding(format.encoding) - - result + internal_strftime(fmt).force_encoding(fmt.encoding) end private - def tmx_year - m_real_year - end - - def tmx_mon - mon - end - - def tmx_mday - mday - end - - def tmx_yday - yday - end - - def tmx_cwyear - m_real_cwyear - end - - def tmx_cweek - cweek - end - - def tmx_cwday - cwday - end - - def tmx_wday - wday - end - - def tmx_wnum0 - # Week number (Sunday start, 00-53) - m_wnumx(0) - end - - def tmx_wnum1 - # Week number (Monday start, 00-53) - m_wnumx(1) - end - - def tmx_hour - if simple_dat_p? - 0 - else - df = df_utc_to_local(m_df, m_of) - (df / 3600).floor - end - end - - def tmx_min - if simple_dat_p? - 0 - else - df = df_utc_to_local(m_df, m_of) - ((df % 3600) / 60).floor - end - end - - def tmx_sec - if simple_dat_p? - 0 - else - df = df_utc_to_local(m_df, m_of) - df % 60 - end - end - - def tmx_sec_fraction - if simple_dat_p? - Rational(0, 1) - else - # (Decimal part of df) + sf - df_frac = m_df - m_df.floor - sf_frac = m_sf == 0 ? 0 : Rational(m_sf, SECOND_IN_NANOSECONDS) - df_frac + sf_frac + def internal_strftime(fmt) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + # Fast path for common format strings (whole-string match) + case fmt + when '%Y-%m-%d', '%F' + _civil unless @year + return _fast_ymd + when '%H:%M:%S', '%T', '%X' + return instance_of?(Date) ? +'00:00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}" + when '%m/%d/%y', '%D', '%x' + _civil unless @year + return "#{PAD2[@month]}/#{PAD2[@day]}/#{PAD2[@year.abs % 100]}" + when '%Y-%m-%dT%H:%M:%S%z' + _civil unless @year + if instance_of?(Date) + return _fast_ymd << 'T00:00:00+0000' + else + of = _of_seconds + sign = of < 0 ? '-' : '+' + abs = of.abs + return "#{_fast_ymd}T#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}#{sign}#{PAD2[abs / 3600]}#{PAD2[(abs % 3600) / 60]}" + end + when '%a %b %e %H:%M:%S %Y', '%c' + _civil unless @year + return _fmt_asctime_str + when '%A, %B %d, %Y' + _civil unless @year + w = (@jd + 1) % 7 + y = @year + y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) + return "#{DAY_FULL_COMMA[w]}#{MONTH_FULL_SPACE[@month]}#{PAD2[@day]}, #{y_s}" end - end - def tmx_secs - # C: tmx_m_secs (date_core.c:7306) - # s = day_to_sec(m_real_jd - UNIX_EPOCH_IN_CJD) - # if complex: s += m_df - s = jd_to_unix_time(m_real_jd) - return s if simple_dat_p? - df = m_df - s += df if df != 0 - s - end - - def tmx_msecs - # C: tmx_m_msecs (date_core.c:7322) - # s = tmx_m_secs * 1000 - # if complex: s += m_sf / MILLISECOND_IN_NANOSECONDS - s = tmx_secs * SECOND_IN_MILLISECONDS - return s if simple_dat_p? - sf = m_sf - s += (sf / (SECOND_IN_NANOSECONDS / SECOND_IN_MILLISECONDS)).to_i if sf != 0 - s - end + result = +''.encode(fmt.encoding) + i = 0 + len = fmt.bytesize - def tmx_offset - simple_dat_p? ? 0 : m_of - end + while i < len + b = fmt.getbyte(i) - def tmx_zone - if simple_dat_p? || tmx_offset.zero? - "+00:00" - else - of2str(m_of) - end - end - - def of2str(of) - s, h, m = decode_offset(of) - sprintf('%c%02d:%02d', s, h, m) - end - - def decode_offset(of) - s = (of < 0) ? '-' : '+' - a = of.abs - h = a / HOUR_IN_SECONDS - m = (a % HOUR_IN_SECONDS) / MINUTE_IN_SECONDS - [s, h, m] - end - - # Processing format strings. - # Uses format.index('%') to scan literal sections in bulk, avoiding - # per-character String allocation from format[i] indexing. - def strftime_format(format) - result = String.new - pos = 0 - fmt_len = format.length - - # Detect simple Date (no time/offset) with both civil and JD fields cached. - # Precompute frequently accessed values to bypass the tmx_* method chain. - if @df.nil? && @sf.nil? && @of.nil? && @nth == 0 && @has_civil && @has_jd - f_year = @year - f_month = @month - f_day = @day - f_wday = (@jd + 1) % 7 - is_simple = true - else - is_simple = false - end - - while pos < fmt_len - # Find next '%' starting from current position. - pct = format.index('%', pos) - - if pct.nil? - # No more format specs — append remaining literal text as a block. - result << format[pos..] if pos < fmt_len - break + # Batch collect literal (non-%) characters + if b != 37 # '%' + lit_start = i + i += 1 + i += 1 while i < len && fmt.getbyte(i) != 37 + result << fmt.byteslice(lit_start, i - lit_start) + next end - # Append literal text before this '%' as a single block copy. - result << format[pos, pct - pos] if pct > pos - - i = pct + 1 - if i >= fmt_len - # Trailing '%' with nothing after — append as literal (matches C behavior). + i += 1 # skip '%' + if i >= len result << '%' break end - # Parse all modifiers in a flat loop (flags, width, colons, E/O). - # flags: integer bitmask (FLAG_MINUS | FLAG_SPACE | FLAG_UPPER | FLAG_CHCASE | FLAG_ZERO) - # width: integer (-1 = not specified) + # Quick dispatch: if next byte is a simple letter spec (A-Z or a-z, + # excluding E/O locale modifiers), skip flag/width/prec parsing entirely. + # Flag chars '-'(45) '_'(95) '0'(48) '^'(94) '#'(35) ':'(58) are all + # outside A-Z(65-90) and a-z(97-122) ranges. + b = fmt.getbyte(i) + if (b >= 65 && b <= 90 && b != 69 && b != 79) || (b >= 97 && b <= 122) + fast = _fast_spec(b) + if fast + result << fast + i += 1 + next + end + end + + # Parse flags (bitmask — no Hash allocation) flags = 0 - width = -1 - modifier = nil colons = 0 - - while i < fmt_len - c = format[i] - case c - when 'E', 'O' - modifier = c - i += 1 - when ':' + loop do + b = fmt.getbyte(i) + case b + when 45 then flags |= FL_LEFT # '-' + when 95 then flags |= FL_SPACE # '_' + when 48 then flags |= FL_ZERO # '0' + when 94 then flags |= FL_UPPER # '^' + when 35 then flags |= FL_CHCASE # '#' + when 58 # ':' colons += 1 i += 1 - when '-' - flags |= FLAG_MINUS - i += 1 - when '_' - flags |= FLAG_SPACE - i += 1 - when '^' - flags |= FLAG_UPPER - i += 1 - when '#' - flags |= FLAG_CHCASE - i += 1 - when '0' - # '0' is a flag only when width is not yet started - if width == -1 - flags |= FLAG_ZERO - else - width = width * 10 - end - i += 1 - when '1'..'9' - width = format[i].ord - 48 - i += 1 - # Continue reading remaining digits - while i < fmt_len - d = format[i] - break if d < '0' || d > '9' - width = width * 10 + (d.ord - 48) - i += 1 - end - else + redo if fmt.getbyte(i) == 58 break + else break end + i += 1 end - # Invalid if both E/O and colon modifiers are present. - if modifier && colons > 0 - if i < fmt_len - spec = format[i] - result << "%#{modifier}#{':' * colons}#{spec}" + # Parse width (byte range check — no Regexp) + width = nil + b = fmt.getbyte(i) + if b && b >= 48 && b <= 57 # '0'..'9' + width = b - 48 + i += 1 + b = fmt.getbyte(i) + while b && b >= 48 && b <= 57 + width = width * 10 + (b - 48) i += 1 + b = fmt.getbyte(i) end - pos = i - next - end - - # Width specifier overflow check - if width != -1 && width >= 1024 - raise Errno::ERANGE, "Result too large" + raise Errno::ERANGE, "strftime" if width > STRFTIME_MAX_WIDTH end - if i < fmt_len - spec = format[i] - - if modifier - # E/O modifier check must come first - valid = case modifier - when 'E' - %w[c C x X y Y].include?(spec) - when 'O' - %w[d e H k I l m M S u U V w W y].include?(spec) - else - false - end - - if valid - result << format_spec(spec, flags, width) - else - result << "%#{modifier}#{flags_to_s(flags)}#{width == -1 ? '' : width}#{spec}" - end - elsif spec == 'z' - if is_simple && flags == 0 && width == -1 && colons == 0 - # Simple Date: offset is always 0, result is always '+0000'. - result << '+0000' - else - result << format_z(tmx_offset, width, flags, colons) - end - elsif colons > 0 - # Colon modifier is only valid for 'z'. - result << "%#{':' * colons}#{flags_to_s(flags)}#{width == -1 ? '' : width}#{spec}" - elsif is_simple && flags == 0 && width == -1 - # Fast path: simple Date with no flags or width — bypass tmx_* method chain. - case spec - when 'Y' - raise Errno::ERANGE, "Result too large" if f_year.bit_length > 128 - if f_year >= 0 && f_year <= 9999 - result << FOUR_DIGIT[f_year] - else - result << sprintf("%0#{f_year < 0 ? 5 : 4}d", f_year) - end - when 'C' - c = f_year / 100 - result << (c >= 0 && c < 100 ? TWO_DIGIT[c] : sprintf('%02d', c)) - when 'y' - result << TWO_DIGIT[f_year % 100] - when 'm' - result << TWO_DIGIT[f_month] - when 'd' - result << TWO_DIGIT[f_day] - when 'e' - result << sprintf('%2d', f_day) - when 'A' - result << (DAYNAMES[f_wday] || '?') - when 'a' - result << (ABBR_DAYNAMES[f_wday] || '?')[0, 3] - when 'B' - result << (MONTHNAMES[f_month] || '?') - when 'b', 'h' - result << (ABBR_MONTHNAMES[f_month] || '?')[0, 3] - when 'H', 'M', 'S' - result << '00' - when 'I', 'l' - # hour=0 → h = 0%12 = 0 → h = 12 - result << '12' - when 'k' - # sprintf('%2d', 0) = ' 0' - result << ' 0' - when 'P' - result << 'am' # hour=0 < 12 - when 'p' - result << 'AM' - when 'w' - result << f_wday.to_s - when 'Z' - result << '+00:00' - when '%' - result << '%' - when 'n' - result << "\n" - when 't' - result << "\t" - else - result << format_spec(spec, flags, width) - end - else - result << format_spec(spec, flags, width) + # Parse precision (after '.') + prec = nil + if fmt.getbyte(i) == 46 # '.' + i += 1 + prec = 0 + b = fmt.getbyte(i) + while b && b >= 48 && b <= 57 + prec = prec * 10 + (b - 48) + i += 1 + b = fmt.getbyte(i) end + end + # Post-width colons (for %8:z, %11::z etc.) + while fmt.getbyte(i) == 58 # ':' + colons += 1 i += 1 end - pos = i - end - - result.force_encoding('US-ASCII') if result.ascii_only? + # Locale modifier (%E or %O) + locale_mod = nil + b = fmt.getbyte(i) + if b == 69 || b == 79 # 'E' or 'O' + locale_mod = b + i += 1 + end - result - end + spec = fmt.getbyte(i) + i += 1 - def flags_to_s(flags) - return '' if flags == 0 - s = ''.dup - s << '-' if flags & FLAG_MINUS != 0 - s << '_' if flags & FLAG_SPACE != 0 - s << '^' if flags & FLAG_UPPER != 0 - s << '#' if flags & FLAG_CHCASE != 0 - s << '0' if flags & FLAG_ZERO != 0 - s - end + # Inline fast path: no flags, no width, no prec, no locale mod, no colons + if flags == 0 && width.nil? && prec.nil? && locale_mod.nil? && colons == 0 + fast = _fast_spec(spec) + if fast + result << fast + next + end + end - def format_spec(spec, flags = 0, width = -1) - # N/L: width controls precision (number of fractional digits) - if spec == 'N' || spec == 'L' - precision = if width != -1 - width - elsif spec == 'L' - 3 - else - 9 - end - frac = tmx_sec_fraction - digits = (frac * (10 ** precision)).floor - return sprintf("%0#{precision}d", digits) + result << _format_spec_b(spec, flags, colons, width, prec, locale_mod) end - # Get basic formatting results. - base_result = get_base_format(spec, flags) - - # Apply case change flags (before width/precision) - base_result = apply_case_flags(base_result, spec, flags) - - # Apply width specifier. - if width != -1 - default_pad = if NUMERIC_SPECS.include?(spec) - '0' - elsif SPACE_PAD_SPECS.include?(spec) - ' ' - else - ' ' - end - apply_width(base_result, width, flags, default_pad) - else - base_result - end + result end - # C: Apply ^ (UPPER) and # (CHCASE) flags - def apply_case_flags(str, spec, flags) - if flags & FLAG_UPPER != 0 - str.upcase - elsif flags & FLAG_CHCASE != 0 - if CHCASE_UPPER_SPECS.include?(spec) - str.upcase - elsif CHCASE_LOWER_SPECS.include?(spec) - str.downcase - else - str.swapcase - end + # Format "%a %b %e %H:%M:%S %Y" directly (used by %c expansion and asctime) + def _fmt_asctime_str + w = (@jd + 1) % 7 + d = @day + d_s = d < 10 ? " #{d}" : d.to_s + y = @year + y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) + if instance_of?(Date) + "#{ASCTIME_PREFIX[w][@month]}#{d_s} 00:00:00 #{y_s}" else - str + "#{ASCTIME_PREFIX[w][@month]}#{d_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} #{y_s}" end end - # format specifiers - def get_base_format(spec, flags = 0) + # Inline fast path for common specs with default formatting (no flags/width/prec) + def _fast_spec(spec) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity case spec - when 'Y' # 4-digit year - y = tmx_year - raise Errno::ERANGE, "Result too large" if y.is_a?(Integer) && y.bit_length > 128 - # C: FMT('0', y >= 0 ? 4 : 5, "ld", y) - if flags & FLAG_MINUS != 0 - y.to_s - elsif flags & FLAG_SPACE != 0 - sprintf("%#{y < 0 ? 5 : 4}d", y) - elsif y >= 0 && y <= 9999 - FOUR_DIGIT[y] - else - sprintf("%0#{y < 0 ? 5 : 4}d", y) - end - when 'C' # Century - c = tmx_year / 100 - c >= 0 && c < 100 ? TWO_DIGIT[c] : sprintf('%02d', c) - when 'y' # Two-digit year - TWO_DIGIT[tmx_year % 100] - when 'm' # Month (01-12) - if flags & FLAG_MINUS != 0 - tmx_mon.to_s - elsif flags & FLAG_SPACE != 0 - sprintf('%2d', tmx_mon) + when 89 # 'Y' + _civil unless @year + y = @year + if y >= 1000 + s = y.to_s + raise Errno::ERANGE, "strftime" if s.length >= STRFTIME_MAX_COPY_LEN + s + elsif y >= 0 + format('%04d', y) else - TWO_DIGIT[tmx_mon] + format('-%04d', -y) end - when 'B' # Full month name - MONTHNAMES[tmx_mon] || '?' - when 'b', 'h' # Abbreviated month name - (ABBR_MONTHNAMES[tmx_mon] || '?')[0, 3] - when 'd' # Day (01-31) - if flags & FLAG_MINUS != 0 - tmx_mday.to_s - elsif flags & FLAG_SPACE != 0 - sprintf('%2d', tmx_mday) + when 109 # 'm' + _civil unless @year + PAD2[@month] + when 100 # 'd' + _civil unless @year + PAD2[@day] + when 101 # 'e' + _civil unless @year + d = @day + d < 10 ? " #{d}" : d.to_s + when 72 # 'H' + PAD2[internal_hour] + when 77 # 'M' + PAD2[internal_min] + when 83 # 'S' + PAD2[internal_sec] + when 97 # 'a' + STRFTIME_DAYS_ABBR[(@jd + 1) % 7] + when 65 # 'A' + STRFTIME_DAYS_FULL[(@jd + 1) % 7] + when 98, 104 # 'b', 'h' + _civil unless @year + STRFTIME_MONTHS_ABBR[@month] + when 66 # 'B' + _civil unless @year + STRFTIME_MONTHS_FULL[@month] + when 112 # 'p' + internal_hour < 12 ? 'AM' : 'PM' + when 80 # 'P' + internal_hour < 12 ? 'am' : 'pm' + when 37 # '%' + '%' + when 110 # 'n' + "\n" + when 116 # 't' + "\t" + when 106 # 'j' + yd = yday + if yd < 10 + "00#{yd}" + elsif yd < 100 + "0#{yd}" else - TWO_DIGIT[tmx_mday] + yd.to_s end - when 'e' # Day (1-31) blank filled - if flags & FLAG_MINUS != 0 - tmx_mday.to_s - elsif flags & FLAG_ZERO != 0 - TWO_DIGIT[tmx_mday] + when 119 # 'w' + ((@jd + 1) % 7).to_s + when 117 # 'u' + cwday.to_s + when 121 # 'y' + _civil unless @year + PAD2[@year.abs % 100] + when 90 # 'Z' + _zone_str + when 122 # 'z' + of = _of_seconds + sign = of < 0 ? '-' : '+' + abs = of.abs + "#{sign}#{PAD2[abs / 3600]}#{PAD2[(abs % 3600) / 60]}" + when 115 # 's' + ((@jd - 2440588) * 86400 - _of_seconds + internal_hour * 3600 + internal_min * 60 + internal_sec).to_s + # Composite specs — inline expansion + when 99 # 'c' + _civil unless @year + _fmt_asctime_str + when 70 # 'F' + _civil unless @year + _fast_ymd + when 84, 88 # 'T', 'X' + instance_of?(Date) ? '00:00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}" + when 68, 120 # 'D', 'x' + _civil unless @year + "#{PAD2[@month]}/#{PAD2[@day]}/#{PAD2[@year.abs % 100]}" + when 82 # 'R' + instance_of?(Date) ? '00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}" + when 114 # 'r' + if instance_of?(Date) + '12:00:00 AM' else - sprintf('%2d', tmx_mday) + h = internal_hour % 12 + h = 12 if h == 0 + "#{PAD2[h]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} #{internal_hour < 12 ? 'AM' : 'PM'}" end - when 'j' # Day of the year (001-366) - if flags & FLAG_MINUS != 0 - tmx_yday.to_s - else - sprintf('%03d', tmx_yday) + else + nil # fall through to _format_spec_b + end + end + + # Full spec handling with bitmask flags (called when _fast_spec returns nil or flags/width/prec present) + def _format_spec_b(spec, flags, colons, width, prec, locale_mod) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + # Handle %E/%O locale modifiers + if locale_mod + valid = locale_mod == 69 ? STRFTIME_E_VALID_BYTES : STRFTIME_O_VALID_BYTES # 69='E' + unless valid.include?(spec) + mod_chr = locale_mod == 69 ? 'E' : 'O' + return "%#{mod_chr}#{spec&.chr}" end - when 'H' # Hour (00-23) - if flags & FLAG_MINUS != 0 - tmx_hour.to_s - elsif flags & FLAG_SPACE != 0 - sprintf('%2d', tmx_hour) + end + + case spec + when 89, 71 # 'Y', 'G' + y = spec == 89 ? year : cwyear + _fmt_year(y, width, prec, flags) + when 67 # 'C' + cent = year.div(100) + _pad_num(cent, width || 2, flags) + when 121 # 'y' + _pad_num(year.abs % 100, width || 2, flags, zero: true) + when 103 # 'g' + _pad_num(cwyear.abs % 100, width || 2, flags, zero: true) + when 109 # 'm' + _pad_num(month, width || 2, flags, zero: true) + when 100 # 'd' + _pad_num(day, width || 2, flags, zero: true) + when 101 # 'e' + _pad_num(day, width || 2, flags, zero: false) + when 106 # 'j' + _pad_num(yday, width || 3, flags, zero: true) + when 72 # 'H' + _pad_num(internal_hour, width || 2, flags, zero: true) + when 107 # 'k' + _pad_num(internal_hour, width || 2, flags, zero: false) + when 73 # 'I' + h = internal_hour % 12 + h = 12 if h == 0 + _pad_num(h, width || 2, flags, zero: true) + when 108 # 'l' + h = internal_hour % 12 + h = 12 if h == 0 + _pad_num(h, width || 2, flags, zero: false) + when 77 # 'M' + _pad_num(internal_min, width || 2, flags, zero: true) + when 83 # 'S' + _pad_num(internal_sec, width || 2, flags, zero: true) + when 76 # 'L' + w = width || 3 + ms = (_sec_frac * (10**w)).floor + ms.to_s.rjust(w, '0') + when 78 # 'N' + w = width || prec || 9 + ns = (_sec_frac * (10**w)).floor + ns.to_s.rjust(w, '0') + when 115 # 's' + unix = (@jd - 2440588) * 86400 - _of_seconds + + internal_hour * 3600 + internal_min * 60 + internal_sec + _pad_num(unix, width || 1, flags) + when 81 # 'Q' + ms = ((@jd - 2440588) * 86400 - _of_seconds + + internal_hour * 3600 + internal_min * 60 + internal_sec) * 1000 + + (_sec_frac * 1000).floor + _pad_num(ms, width || 1, flags) + when 65 # 'A' + _fmt_str(STRFTIME_DAYS_FULL[wday], width, flags) + when 97 # 'a' + _fmt_str(STRFTIME_DAYS_ABBR[wday], width, flags) + when 66 # 'B' + _fmt_str(STRFTIME_MONTHS_FULL[month], width, flags) + when 98, 104 # 'b', 'h' + _fmt_str(STRFTIME_MONTHS_ABBR[month], width, flags) + when 112 # 'p' + _fmt_str(internal_hour < 12 ? 'AM' : 'PM', width, flags) + when 80 # 'P' + _fmt_str(internal_hour < 12 ? 'am' : 'pm', width, flags) + when 90 # 'Z' + _fmt_str(_zone_str, width, flags) + when 122 # 'z' + _fmt_z(colons, width, prec, flags) + when 117 # 'u' + _pad_num(cwday, width || 1, flags) + when 119 # 'w' + _pad_num(wday, width || 1, flags) + when 85 # 'U' + _pad_num(_week_number(0), width || 2, flags, zero: true) + when 87 # 'W' + _pad_num(_week_number(1), width || 2, flags, zero: true) + when 86 # 'V' + _pad_num(cweek, width || 2, flags, zero: true) + when 37 # '%' + '%' + when 43 # '+' + s = internal_strftime('%a %b %e %H:%M:%S %Z %Y') + _fmt_str(s, width, flags) + else + # Try composite + expansion = STRFTIME_COMPOSITE_BYTE[spec] + if expansion + s = internal_strftime(expansion) + _fmt_str(s, width, flags) else - TWO_DIGIT[tmx_hour] + "%#{spec&.chr}" end - when 'k' # Hour (0-23) blank-padded - sprintf('%2d', tmx_hour) - when 'I' # Hour (01-12) - h = tmx_hour % 12 - h = 12 if h.zero? - if flags & FLAG_MINUS != 0 - h.to_s - elsif flags & FLAG_SPACE != 0 - sprintf('%2d', h) + end + end + + # Format year (handles negative years, precision, and all flag variants) + def _fmt_year(y, width, prec, flags) + if prec + s = y.abs.to_s.rjust(prec, '0') + s = (y < 0 ? '-' : '') + s + elsif flags & FL_LEFT != 0 + s = (y < 0 ? '-' : '') + y.abs.to_s + else + default_w = y < 0 ? 5 : 4 + w = width || default_w + if flags & FL_SPACE != 0 + raw = (y < 0 ? '-' : '') + y.abs.to_s + s = raw.rjust(w, ' ') else - TWO_DIGIT[h] + s = y.abs.to_s.rjust(w - (y < 0 ? 1 : 0), '0') + s = (y < 0 ? '-' : '') + s end - when 'l' # Hour (1-12) blank filled - h = tmx_hour % 12 - h = 12 if h.zero? - sprintf('%2d', h) - when 'M' # Minutes (00-59) - if flags & FLAG_MINUS != 0 - tmx_min.to_s - elsif flags & FLAG_SPACE != 0 - sprintf('%2d', tmx_min) + end + raise Errno::ERANGE, "strftime" if s.length >= STRFTIME_MAX_COPY_LEN + if flags & (FL_UPPER | FL_CHCASE) != 0 + s.upcase + else + s + end + end + + def _pad_num(n, default_w, flags, zero: nil) + sign = n < 0 ? '-' : '' + abs = n.abs.to_s + w = default_w + + if flags & FL_LEFT != 0 + sign + abs + elsif flags & FL_SPACE != 0 || (flags & FL_ZERO == 0 && zero == false) + sign + abs.rjust(w - sign.length, ' ') + else + pad = (flags & FL_ZERO != 0 || zero) ? '0' : ' ' + sign + abs.rjust([w - sign.length, abs.length].max, pad) + end + end + + def _fmt_str(s, width, flags) + s = s.dup + if flags & FL_CHCASE != 0 + s = (s == s.upcase) ? s.downcase : s.upcase + elsif flags & FL_UPPER != 0 + s = s.upcase + end + if flags & FL_LEFT != 0 + s + elsif width + pad = flags & FL_ZERO != 0 ? '0' : ' ' + s.rjust(width, pad) + else + s + end + end + + # Week number (0=first partial week) + def _week_number(ws) + yd = yday + wd = wday # 0=Sun + if ws == 1 + # Monday-based + wd = wd == 0 ? 6 : wd - 1 + end + (yd - wd + 6).div(7) + end + + # Format %z with colons variant and GNU extension flag support + def _fmt_z(colons, width, _prec, flags) + of = _of_seconds + sign = of < 0 ? '-' : '+' + abs = of.abs + hh = abs / 3600 + mm = (abs % 3600) / 60 + ss = abs % 60 + + no_lead = flags & (FL_LEFT | FL_SPACE) != 0 + + if no_lead + case colons + when 0 + s = format('%s%d%02d', sign, hh, mm) + when 1 + s = format('%s%d:%02d', sign, hh, mm) + when 2 + s = format('%s%d:%02d:%02d', sign, hh, mm, ss) + when 3 + if ss != 0 + s = format('%s%d:%02d:%02d', sign, hh, mm, ss) + elsif mm != 0 + s = format('%s%d:%02d', sign, hh, mm) + else + s = format('%s%d', sign, hh) + end else - TWO_DIGIT[tmx_min] + s = format('%s%d:%02d', sign, hh, mm) end - when 'S' # Seconds (00-59) - if flags & FLAG_MINUS != 0 - tmx_sec.to_s - elsif flags & FLAG_SPACE != 0 - sprintf('%2d', tmx_sec) + else + case colons + when 0 + s = format('%s%02d%02d', sign, hh, mm) + when 1 + s = format('%s%02d:%02d', sign, hh, mm) + when 2 + s = format('%s%02d:%02d:%02d', sign, hh, mm, ss) + when 3 + if ss != 0 + s = format('%s%02d:%02d:%02d', sign, hh, mm, ss) + elsif mm != 0 + s = format('%s%02d:%02d', sign, hh, mm) + else + s = format('%s%02d', sign, hh) + end else - TWO_DIGIT[tmx_sec] + s = format('%s%02d:%02d', sign, hh, mm) end - when 'L' # Milliseconds (000-999) - sprintf('%09d', (tmx_sec_fraction * 1_000_000_000).floor) - when 'N' # Fractional seconds digits - # C: width controls precision (number of digits), default 9. - # %3N → 3 digits (milliseconds), %6N → 6 digits (microseconds), - # %9N → 9 digits (nanoseconds), %12N → 12 digits (picoseconds, zero-padded). - # The 'width' variable is handled specially in format_spec for 'N'. - sprintf('%09d', (tmx_sec_fraction * 1_000_000_000).floor) - when 'P' # am/pm - tmx_hour < 12 ? 'am' : 'pm' - when 'p' # AM/PM - tmx_hour < 12 ? 'AM' : 'PM' - when 'A' # Full name of the day of the week - DAYNAMES[tmx_wday] || '?' - when 'a' # Abbreviated day of the week - (ABBR_DAYNAMES[tmx_wday] || '?')[0, 3] - when 'w' # Day of the week (0-6, Sunday is 0) - tmx_wday.to_s - when 'u' # Day of the week (1-7, Monday is 1) - tmx_cwday.to_s - when 'U' # Week number (00-53, Sunday start) - TWO_DIGIT[tmx_wnum0] - when 'W' # Week number (00-53, Monday start) - TWO_DIGIT[tmx_wnum1] - when 'V' # ISO week number (01-53) - TWO_DIGIT[tmx_cweek] - when 'G' # ISO week year - y = tmx_cwyear - if flags & FLAG_MINUS != 0 - y.to_s - elsif flags & FLAG_SPACE != 0 - sprintf("%#{y < 0 ? 5 : 4}d", y) - elsif y >= 0 && y <= 9999 - FOUR_DIGIT[y] + end + + if width + if flags & FL_LEFT != 0 + s + elsif flags & FL_SPACE != 0 + s.rjust(width, ' ') else - sprintf("%0#{y < 0 ? 5 : 4}d", y) + digits = s[1..] + sign + digits.rjust(width - 1, '0') end - when 'g' # ISO week year (2 digits) - TWO_DIGIT[tmx_cwyear % 100] - when 'z' # Time Zone Offset (+0900) — handled by format_z in format_spec - format_z(tmx_offset, -1, 0, 0) - when 'Z' # Time Zone Name - tmx_zone || '' - when 's' # Number of seconds since the Unix epoch - tmx_secs.to_s - when 'Q' # Milliseconds since the Unix epoch - tmx_msecs.to_s - when 'n' # Line breaks - "\n" - when 't' # Tab - "\t" - when '%' # % symbol - '%' - when 'F' # %Y-%m-%d - strftime_format('%Y-%m-%d') - when 'D' # %m/%d/%y - strftime_format('%m/%d/%y') - when 'x' # %m/%d/%y - strftime_format('%m/%d/%y') - when 'T', 'X' # %H:%M:%S - strftime_format('%H:%M:%S') - when 'R' # %H:%M - strftime_format('%H:%M') - when 'r' # %I:%M:%S %p - strftime_format('%I:%M:%S %p') - when 'c' # %a %b %e %H:%M:%S %Y - strftime_format('%a %b %e %H:%M:%S %Y') - when 'v' # %e-%^b-%Y (3-FEB-2001 format) - day_str = sprintf('%2d', tmx_mday) - month_str = (ABBR_MONTHNAMES[tmx_mon] || '?')[0, 3].upcase - year_str = sprintf('%04d', tmx_year) - "#{day_str}-#{month_str}-#{year_str}" - when '+' # %a %b %e %H:%M:%S %Z %Y - strftime_format('%a %b %e %H:%M:%S %Z %Y') else - # Unknown specifiers are output as is. - "%#{spec}" + s end end - def apply_width(str, width, flags, default_pad = ' ') - # '-' flag means no padding at all - return str if flags & FLAG_MINUS != 0 - return str if str.length >= width - - # Determine a padding character. - padding = - if flags & FLAG_ZERO != 0 - '0' - elsif flags & FLAG_SPACE != 0 - ' ' - else - default_pad - end + # Fast path helper: format '%Y-%m-%d' without allocation overhead + def _fast_ymd + y = @year + suffix = MONTH_DAY_SUFFIX[@month][@day] + if y >= 1000 + y.to_s << suffix + elsif y >= 0 + format('%04d', y) << suffix + else + format('-%04d', -y) << suffix + end + end - str.rjust(width, padding) + # Helpers for DateTime override + def internal_hour + 0 end - # C: format %z with width/flags/colons support - # Matches date_strftime.c case 'z' logic exactly. - # width: integer (-1 = not specified), flags: integer bitmask - def format_z(offset, width, flags, colons) - sign = offset < 0 ? '-' : '+' - aoff = offset.abs - hours = aoff / 3600 - minutes = (aoff % 3600) / 60 - seconds = aoff % 60 - - hl = hours < 10 ? 1 : 2 # actual digits needed for hours - hw = 2 # default hour width - hw = 1 if flags & FLAG_MINUS != 0 && hl == 1 - - precision = width # -1 means not specified - - # Calculate fixed chars (everything except hour digits) per colons variant - fixed = case colons - when 0 then 3 # sign(1) + mm(2) - when 1 then 4 # sign(1) + :(1) + mm(2) - when 2 then 7 # sign(1) + :(1) + mm(2) + :(1) + ss(2) - when 3 - if (aoff % 3600).zero? - 1 # sign(1) only - elsif (aoff % 60).zero? - 4 # sign(1) + :(1) + mm(2) - else - 7 # sign(1) + :(1) + mm(2) + :(1) + ss(2) - end - else - 3 - end - - # C: hour_precision = precision <= (fixed + hw) ? hw : precision - fixed - hp = precision <= (fixed + hw) ? hw : precision - fixed - - result = String.new - - # C: space padding — print spaces before sign, reduce hour precision - if flags & FLAG_SPACE != 0 && hp > hl - result << ' ' * (hp - hl) - hp = hl - end + def internal_min + 0 + end - result << sign - result << sprintf("%0#{hp}d", hours) - - # Append minutes/seconds based on colons - case colons - when 0 - result << sprintf('%02d', minutes) - when 1 - result << sprintf(':%02d', minutes) - when 2 - result << sprintf(':%02d:%02d', minutes, seconds) - when 3 - unless (aoff % 3600).zero? - result << sprintf(':%02d', minutes) - unless (aoff % 60).zero? - result << sprintf(':%02d', seconds) - end - end - end + def internal_sec + 0 + end - result + def _sec_frac + Rational(0) end - def jd_to_unix_time(jd) - unix_epoch_jd = 2440588 - (jd - unix_epoch_jd) * DAY_IN_SECONDS + def _of_seconds + 0 end + + def _zone_str + '+00:00' + end + end diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index d4889ca6..d343ff52 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -1,7 +1,5 @@ # frozen_string_literal: true -require 'strscan' -# Implementation of ruby/date/ext/date/date_strptime.c class Date class << self # call-seq: @@ -20,167 +18,25 @@ class << self # # Related: Date.strptime (returns a \Date object). def _strptime(string, format = '%F') - # Fast paths for the most common format strings. - case format - when '%F', '%Y-%m-%d' - m = /\A([+-]?\d+)-(\d{1,2})-(\d{1,2})/.match(string) - return nil unless m - mon = m[2].to_i - mday = m[3].to_i - return nil if mon < 1 || mon > 12 || mday < 1 || mday > 31 - h = { year: m[1].to_i, mon: mon, mday: mday } - rest = m.post_match - h[:leftover] = rest unless rest.empty? - return h - - when '%Y-%m-%d %H:%M:%S' - m = /\A([+-]?\d+)-(\d{1,2})-(\d{1,2}) (\d{1,2}):(\d{1,2}):(\d{1,2})/.match(string) - return nil unless m - mon = m[2].to_i - mday = m[3].to_i - hour = m[4].to_i - min = m[5].to_i - sec = m[6].to_i - return nil if mon < 1 || mon > 12 || mday < 1 || mday > 31 - return nil if hour > 24 || min > 59 || sec > 60 - h = { year: m[1].to_i, mon: mon, mday: mday, hour: hour, min: min, sec: sec } - rest = m.post_match - h[:leftover] = rest unless rest.empty? - return h - - when '%Y-%m-%dT%H:%M:%S' - m = /\A([+-]?\d+)-(\d{1,2})-(\d{1,2})T(\d{1,2}):(\d{1,2}):(\d{1,2})/.match(string) - return nil unless m - mon = m[2].to_i - mday = m[3].to_i - hour = m[4].to_i - min = m[5].to_i - sec = m[6].to_i - return nil if mon < 1 || mon > 12 || mday < 1 || mday > 31 - return nil if hour > 24 || min > 59 || sec > 60 - h = { year: m[1].to_i, mon: mon, mday: mday, hour: hour, min: min, sec: sec } - rest = m.post_match - h[:leftover] = rest unless rest.empty? - return h - end - - ss = StringScanner.new(string) + string = String === string ? string : string.to_str + format = String === format ? format : format.to_str + if format == '%F' || format == '%Y-%m-%d' + return _strptime_ymd(string) + end + if format == '%a %b %d %Y' + return _strptime_abdy(string) + end hash = {} - - i = 0 - fmt_len = format.length - while i < fmt_len - fb = format.getbyte(i) - if fb == 37 && i + 1 < fmt_len # '%' - i += 1 - - # Parse modifier (E, O) - modifier = nil - fb2 = format.getbyte(i) - if i < fmt_len && (fb2 == 69 || fb2 == 79) # 'E' == 69, 'O' == 79 - modifier = fb2 == 69 ? 'E' : 'O' - i += 1 - end - - # Parse colons for %:z, %::z, %:::z - colons = 0 - while i < fmt_len && format.getbyte(i) == 58 # ':' - colons += 1 - i += 1 - end - - # Parse width as integer (avoids String allocation and regex digit check) - field_width = nil - while i < fmt_len - db = format.getbyte(i) - break if db < 48 || db > 57 # '0'..'9' - field_width = (field_width || 0) * 10 + db - 48 - i += 1 - end - - break if i >= fmt_len - - spec = format[i] - i += 1 - - # Handle E/O modifier validity - if modifier - valid = case modifier - when 'E' - %w[c C x X y Y].include?(spec) - when 'O' - %w[d e H I m M S u U V w W y].include?(spec) - else - false - end - unless valid - literal = "%#{modifier}#{':' * colons}#{field_width}#{spec}" - if ss.string[ss.pos, literal.length] == literal - ss.pos += literal.length - else - return nil - end - next - end - end - - # Handle colon+z - if colons > 0 && spec == 'z' - result = _strptime_zone_colon(ss.string, ss.pos, colons) - return nil unless result - ss.pos = result[:pos] - hash[:zone] = result[:zone] - hash[:offset] = result[:offset] - next - elsif colons > 0 - # Invalid colon usage - return nil - end - - # C: NUM_PATTERN_P() - check if next format element is a digit-consuming pattern. - next_is_num = num_pattern_p(format, i) - - return nil unless _strptime_spec(ss, spec, field_width, hash, next_is_num) - elsif fb == 37 && i + 1 == fmt_len # Trailing % - match literal - if ss.string.getbyte(ss.pos) == 37 # '%' - ss.pos += 1 - else - return nil - end - i += 1 - elsif fb == 32 || fb == 9 || fb == 10 || fb == 13 || fb == 11 || fb == 12 # whitespace - # Whitespace in format matches zero or more whitespace in input - i += 1 - skip_ws(ss) - else - # Literal match - if ss.string.getbyte(ss.pos) == fb - ss.pos += 1 - else - return nil - end - i += 1 - end + si = _sp_run(string, 0, format, hash) + return nil if hash.delete(:_fail) + hash[:leftover] = string[si..] if si < string.length + if (cent = hash.delete(:_cent)) + hash[:year] = hash[:year] + cent * 100 if hash.key?(:year) + hash[:cwyear] = hash[:cwyear] + cent * 100 if hash.key?(:cwyear) end - - # Store leftover if any - hash[:leftover] = ss.rest unless ss.eos? - - # --- Post-processing (C: date__strptime, date_strptime.c:524-546) --- - - # C: cent = del_hash("_cent"); - hash.delete(:_century) - hash.delete(:_century_set) - - # C: merid = del_hash("_merid"); - merid = hash.delete(:_merid) - if merid - hour = hash[:hour] - if hour - hash[:hour] = (hour % 12) + merid - end + if (merid = hash.delete(:_merid)) + hash[:hour] = hash[:hour] % 12 + merid if hash.key?(:hour) end - hash end @@ -208,621 +64,1429 @@ def _strptime(string, format = '%F') # # Related: Date._strptime (returns a hash). def strptime(string = JULIAN_EPOCH_DATE, format = '%F', start = DEFAULT_SG) + str = String === string ? string : string.to_str + if format == '%F' || format == '%Y-%m-%d' + result = _strptime_ymd_to_date(str, start) + return result if result + raise Error, 'invalid date' + end + if format == '%a %b %d %Y' + result = _strptime_abdy_to_date(str, start) + return result if result + raise Error, 'invalid date' + end hash = _strptime(string, format) - raise Error, "invalid strptime format - `#{format}'" unless hash - - # Apply comp for 2-digit year - if hash[:year] && !hash[:_century_set] - # If year came from %y (2-digit), comp_year69 was already applied + raise Error, 'invalid date' if hash.nil? + if !hash.key?(:seconds) && !hash.key?(:leftover) && + !hash.key?(:_cent) && !hash.key?(:_merid) && + (year = hash[:year]) && (mon = hash[:mon]) && (mday = hash[:mday]) + jd = internal_valid_civil?(year, mon, mday, start) + raise Error, 'invalid date' if jd.nil? + return _new_from_jd(jd, start) end - - new_by_frags(hash, start) + _new_by_frags(hash, start) end - private - # Advances StringScanner past zero or more ASCII whitespace bytes - # (space=32, tab=9, LF=10, CR=13, VT=11, FF=12). - # Avoids regex overhead compared to ss.skip(/[ \t\n\r\v\f]*/). - def skip_ws(ss) - str = ss.string - p = ss.pos - len = str.length - while p < len - b = str.getbyte(p) - break unless b == 32 || b == 9 || b == 10 || b == 13 || b == 11 || b == 12 - p += 1 - end - ss.pos = p - end + private - # Scans unsigned decimal integer from +str+ at +pos+, up to +max+ digits. - # Returns [value, new_pos] or nil if no digit found. - def scan_uint(str, pos, max) - val = 0 - count = 0 - len = str.length - while count < max && pos + count < len - b = str.getbyte(pos + count) - break unless b >= 48 && b <= 57 # '0'..'9' - val = val * 10 + b - 48 - count += 1 - end - count > 0 ? [val, pos + count] : nil + # Returns true if the format at position fi starts a numeric conversion spec. + # All byte-level comparison, no String allocation. + def _sp_num_p_b?(fmt, fi, flen) + return false if fi >= flen + c = fmt.getbyte(fi) + return true if c >= 48 && c <= 57 # '0'..'9' + if c == 37 # '%' + i = fi + 1 + return false if i >= flen + c2 = fmt.getbyte(i) + if c2 == 69 || c2 == 79 # 'E' or 'O' + i += 1 + return false if i >= flen + c2 = fmt.getbyte(i) + end + return STRPTIME_NUMERIC_SPEC_SET[c2] + end + false end - # Scans signed decimal integer (optional leading +/-) from +str+ at +pos+. - # Returns [value, new_pos] or nil if no digit found. - def scan_sint(str, pos, max) - b = str.getbyte(pos) - if b == 43 # '+' - result = scan_uint(str, pos + 1, max) - result - elsif b == 45 # '-' - result = scan_uint(str, pos + 1, max) - result ? [-result[0], result[1]] : nil - else - scan_uint(str, pos, max) + # Read up to max_w decimal digits from str starting at si. + # Returns [value, chars_consumed] or [nil, 0] if no digit found. + def _sp_digits(str, si, slen, max_w) + l = 0 + v = 0 + while si + l < slen + c = str.getbyte(si + l) + break unless c && c >= 48 && c <= 57 # '0'..'9' + break if l >= max_w + v = v * 10 + (c - 48) + l += 1 end + return nil, 0 if l == 0 + return v, l end - # C: num_pattern_p (date_strptime.c:48) - # Returns true if the format string at position `i` starts with a - # digit-consuming pattern (a literal digit or a %-specifier that reads digits). - # Uses byte-level operations to avoid String allocations. - def num_pattern_p(format, i) - return false if i >= format.length - b = format.getbyte(i) - return true if b >= 48 && b <= 57 # '0'..'9' - if b == 37 # '%' - i += 1 - return false if i >= format.length - b2 = format.getbyte(i) - # Skip E/O modifier (E=69, O=79) - if b2 == 69 || b2 == 79 - i += 1 - return false if i >= format.length - b2 = format.getbyte(i) - end - return true if (b2 >= 48 && b2 <= 57) || NUM_PATTERN_SPECS_TABLE[b2] - end - false + # Whitespace byte check (space, tab, newline, carriage return, vertical tab, form feed) + def _sp_ws?(b) + b == 32 || b == 9 || b == 10 || b == 13 || b == 11 || b == 12 end - # Modifies +hash+ in-place with parsed values for +spec+. - # Advances +ss+ position on success. Returns true on success, nil on failure. - def _strptime_spec(ss, spec, width, hash, next_is_num = false) - str = ss.string - pos = ss.pos - - case spec - when 'Y' # Full year (possibly negative) - year, new_pos = scan_sint(str, pos, width || (next_is_num ? 4 : 40)) - return nil unless year - hash[:year] = year - ss.pos = new_pos - true - - when 'C' # Century - century, new_pos = scan_sint(str, pos, width || (next_is_num ? 2 : 40)) - return nil unless century - hash[:_century] = century - if hash[:year] && !hash[:_century_set] - hash[:year] = century * 100 + (hash[:year] % 100) - hash[:_century_set] = true - end - ss.pos = new_pos - true - - when 'y' # 2-digit year - y, new_pos = scan_uint(str, pos, width || 2) - return nil unless y - if hash[:_century] - hash[:year] = hash[:_century] * 100 + y - hash[:_century_set] = true - else - hash[:year] = y >= 69 ? y + 1900 : y + 2000 - end - ss.pos = new_pos - true - - when 'm' # Month (01-12) - mon, new_pos = scan_uint(str, pos, width || 2) - return nil unless mon - return nil if mon < 1 || mon > 12 - hash[:mon] = mon - ss.pos = new_pos - true - - when 'd', 'e' # Day of month - if str.getbyte(pos) == 32 # ' ' - day, new_pos = scan_uint(str, pos + 1, 1) - return nil unless day - return nil if day < 1 || day > 31 - hash[:mday] = day - ss.pos = new_pos - else - day, new_pos = scan_uint(str, pos, width || 2) - return nil unless day - return nil if day < 1 || day > 31 - hash[:mday] = day - ss.pos = new_pos - end - true - - when 'j' # Day of year (001-366) - yday, new_pos = scan_uint(str, pos, width || 3) - return nil unless yday - return nil if yday < 1 || yday > 366 - hash[:yday] = yday - ss.pos = new_pos - true - - when 'H', 'k' # Hour (00-24) - if str.getbyte(pos) == 32 # ' ' - hour, new_pos = scan_uint(str, pos + 1, 1) - return nil unless hour - return nil if hour > 24 - hash[:hour] = hour - ss.pos = new_pos - else - hour, new_pos = scan_uint(str, pos, width || 2) - return nil unless hour - return nil if hour > 24 - hash[:hour] = hour - ss.pos = new_pos + # Core scanner: walks format string and string simultaneously. + # All comparisons use getbyte for zero-allocation byte-level operation. + # Returns new string index si on success. + # Sets hash[:_fail]=true and returns -1 on failure. + def _sp_run(str, si, fmt, hash) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + fi = 0 + flen = fmt.bytesize + slen = str.bytesize + + while fi < flen + ch = fmt.getbyte(fi) + + # Whitespace in format: skip any whitespace in both format and string + if _sp_ws?(ch) + while si < slen && _sp_ws?(str.getbyte(si)) + si += 1 + end + fi += 1 + while fi < flen && _sp_ws?(fmt.getbyte(fi)) + fi += 1 + end + next end - true - - when 'I', 'l' # Hour (01-12) - if str.getbyte(pos) == 32 # ' ' - hour, new_pos = scan_uint(str, pos + 1, 1) - return nil unless hour - return nil if hour < 1 || hour > 12 - hash[:hour] = hour - ss.pos = new_pos - else - hour, new_pos = scan_uint(str, pos, width || 2) - return nil unless hour - return nil if hour < 1 || hour > 12 - hash[:hour] = hour - ss.pos = new_pos + + if ch != 37 # '%' + if si >= slen + hash[:_fail] = true + return -1 + end + if str.getbyte(si) != ch + hash[:_fail] = true + return -1 + end + si += 1 + fi += 1 + next end - true - - when 'M' # Minute (00-59) - min, new_pos = scan_uint(str, pos, width || 2) - return nil unless min - return nil if min > 59 - hash[:min] = min - ss.pos = new_pos - true - - when 'S' # Second (00-60) - sec, new_pos = scan_uint(str, pos, width || 2) - return nil unless sec - return nil if sec > 60 - hash[:sec] = sec - ss.pos = new_pos - true - - when 'L' # Milliseconds — normalize digit string to 3-digit precision - w = width || (next_is_num ? 3 : 40) - val, count = 0, 0 - str_len = str.length - while count < w && pos + count < str_len - b = str.getbyte(pos + count) - break unless b >= 48 && b <= 57 - val = val * 10 + b - 48 - count += 1 + + fi += 1 # skip '%' + + # Handle colon modifiers: %:z, %::z, %:::z + colons = 0 + while fi < flen && fmt.getbyte(fi) == 58 # ':' + colons += 1 + fi += 1 end - return nil if count == 0 - val *= 10 ** (3 - count) if count < 3 - val /= 10 ** (count - 3) if count > 3 - hash[:sec_fraction] = Rational(val, 1000) - ss.pos = pos + count - true - - when 'N' # Nanoseconds — normalize digit string to 9-digit precision - w = width || (next_is_num ? 9 : 40) - val, count = 0, 0 - str_len = str.length - while count < w && pos + count < str_len - b = str.getbyte(pos + count) - break unless b >= 48 && b <= 57 - val = val * 10 + b - 48 - count += 1 + if colons > 0 + unless fi < flen && fmt.getbyte(fi) == 122 # 'z' + hash[:_fail] = true + return -1 + end + fi += 1 + new_si = _sp_zone(str, si, slen, hash) + if new_si < 0 + hash[:_fail] = true + return -1 + end + si = new_si + next end - return nil if count == 0 - val *= 10 ** (9 - count) if count < 9 - val /= 10 ** (count - 9) if count > 9 - hash[:sec_fraction] = Rational(val, 1_000_000_000) - ss.pos = pos + count - true - - when 'p', 'P' # AM/PM - m = ss.scan(/a\.?m\.?|p\.?m\.?/i) - return nil unless m - ampm = m.delete('.').upcase - hash[:_merid] = (ampm == 'PM') ? 12 : 0 - true - - when 'A', 'a' # Day name (full or abbreviated) - # Zero-alloc integer key from 3 bytes (lowercase via | 0x20). - # Check byte 4 to skip full-name string comparison in the common case. - b0 = str.getbyte(pos) - b1 = str.getbyte(pos + 1) - b2 = str.getbyte(pos + 2) - if b0 && b1 && b2 - k0 = b0 | 0x20; k1 = b1 | 0x20; k2 = b2 | 0x20 - if k0 >= 97 && k0 <= 122 && k1 >= 97 && k1 <= 122 && k2 >= 97 && k2 <= 122 - ikey = (k0 << 16) | (k1 << 8) | k2 - if (info = STRPTIME_DAYNAME_BY_INT_KEY[ikey]) - idx, full, full_len, abbr_len = info - b3 = str.getbyte(pos + abbr_len) - # If next byte is non-alpha, it's an abbreviated name. - if b3.nil? || (t = b3 | 0x20) < 97 || t > 122 - hash[:wday] = idx - ss.pos = pos + abbr_len - elsif str[pos, full_len]&.downcase == full - hash[:wday] = idx - ss.pos = pos + full_len - else - hash[:wday] = idx - ss.pos = pos + abbr_len - end - true + + # Handle E/O locale modifiers + fb = fi < flen ? fmt.getbyte(fi) : nil + if fb == 69 || fb == 79 # 'E' or 'O' + valid_set = fb == 69 ? STRPTIME_E_VALID_SET : STRPTIME_O_VALID_SET + fb2 = fi + 1 < flen ? fmt.getbyte(fi + 1) : nil + if fb2 && valid_set[fb2] + fi += 1 # skip E/O, fall through to handle spec + else + # Invalid combo: match '%' literally in string + if si >= slen || str.getbyte(si) != 37 # '%' + hash[:_fail] = true + return -1 end + si += 1 + next end end - when 'B', 'b', 'h' # Month name (full or abbreviated) - # Zero-alloc integer key from 3 bytes (lowercase via | 0x20). - b0 = str.getbyte(pos) - b1 = str.getbyte(pos + 1) - b2 = str.getbyte(pos + 2) - if b0 && b1 && b2 - k0 = b0 | 0x20; k1 = b1 | 0x20; k2 = b2 | 0x20 - if k0 >= 97 && k0 <= 122 && k1 >= 97 && k1 <= 122 && k2 >= 97 && k2 <= 122 - ikey = (k0 << 16) | (k1 << 8) | k2 - if (info = STRPTIME_MONNAME_BY_INT_KEY[ikey]) - idx, full, full_len, abbr_len = info - b3 = str.getbyte(pos + abbr_len) - if b3.nil? || (t = b3 | 0x20) < 97 || t > 122 - hash[:mon] = idx - ss.pos = pos + abbr_len - elsif str[pos, full_len]&.downcase == full - hash[:mon] = idx - ss.pos = pos + full_len - else - hash[:mon] = idx - ss.pos = pos + abbr_len - end - true + spec = fi < flen ? fmt.getbyte(fi) : nil + fi += 1 + + case spec + when 65, 97 # 'A', 'a' + # Weekday name: 3-byte key O(1) lookup + if si + 2 >= slen + hash[:_fail] = true + return -1 + end + key = ((str.getbyte(si) | 0x20) << 16) | ((str.getbyte(si + 1) | 0x20) << 8) | (str.getbyte(si + 2) | 0x20) + entry = ABBR_DAY_3KEY[key] + unless entry + hash[:_fail] = true + return -1 + end + wday_i = entry[0] + day_full_len = entry[1] + if si + day_full_len <= slen && _sp_head_match?(str, si, slen, DAY_LOWER_BYTES[wday_i], day_full_len) + si += day_full_len + else + si += 3 + end + hash[:wday] = wday_i + + when 66, 98, 104 # 'B', 'b', 'h' + # Month name: 3-byte key O(1) lookup + if si + 2 >= slen + hash[:_fail] = true + return -1 + end + key = ((str.getbyte(si) | 0x20) << 16) | ((str.getbyte(si + 1) | 0x20) << 8) | (str.getbyte(si + 2) | 0x20) + entry = ABBR_MONTH_3KEY[key] + unless entry + hash[:_fail] = true + return -1 + end + mon_i = entry[0] + mon_full_len = entry[1] + if si + mon_full_len <= slen && _sp_head_match?(str, si, slen, MONTH_LOWER_BYTES[mon_i], mon_full_len) + si += mon_full_len + else + si += 3 + end + hash[:mon] = mon_i + + when 67 # 'C' + # Century: greedy unless next spec is numeric + w = _sp_num_p_b?(fmt, fi, flen) ? 2 : 10000 + sb = si < slen ? str.getbyte(si) : nil + if sb == 43 || sb == 45 # '+' or '-' + sign = sb == 45 ? -1 : 1 + si += 1 + else + sign = 1 + end + n, l = _sp_digits(str, si, slen, w) + if l == 0 + hash[:_fail] = true + return -1 + end + si += l + hash[:_cent] = sign * n + + when 99 # 'c' + new_si = _sp_run(str, si, '%a %b %e %H:%M:%S %Y', hash) + return new_si if new_si < 0 + si = new_si + + when 68 # 'D' + new_si = _sp_run(str, si, '%m/%d/%y', hash) + return new_si if new_si < 0 + si = new_si + + when 100, 101 # 'd', 'e' + # Day of month (leading space allowed for single-digit) - inlined + if si < slen && str.getbyte(si) == 32 # ' ' + si += 1 + b = si < slen ? str.getbyte(si) : nil + unless b && b >= 48 && b <= 57 + hash[:_fail] = true + return -1 + end + n = b - 48 + si += 1 + else + b = si < slen ? str.getbyte(si) : nil + unless b && b >= 48 && b <= 57 + hash[:_fail] = true + return -1 + end + n = b - 48 + si += 1 + b = si < slen ? str.getbyte(si) : nil + if b && b >= 48 && b <= 57 + n = n * 10 + (b - 48) + si += 1 end end - end + if n < 1 || n > 31 + hash[:_fail] = true + return -1 + end + hash[:mday] = n + + when 70 # 'F' + new_si = _sp_run(str, si, '%Y-%m-%d', hash) + return new_si if new_si < 0 + si = new_si + + when 71 # 'G' + # ISO week-based year: greedy unless next spec is numeric + sb = si < slen ? str.getbyte(si) : nil + if sb == 43 || sb == 45 # '+' or '-' + sign = sb == 45 ? -1 : 1 + si += 1 + else + sign = 1 + end + w = _sp_num_p_b?(fmt, fi, flen) ? 4 : 10000 + n, l = _sp_digits(str, si, slen, w) + if l == 0 + hash[:_fail] = true + return -1 + end + si += l + hash[:cwyear] = sign * n + + when 103 # 'g' + # 2-digit ISO week year + n, l = _sp_digits(str, si, slen, 2) + if l == 0 || n > 99 + hash[:_fail] = true + return -1 + end + si += l + hash[:cwyear] = n + hash[:_cent] ||= n >= 69 ? 19 : 20 + + when 72, 107 # 'H', 'k' + # 24-hour clock (leading space allowed) - inlined + if si < slen && str.getbyte(si) == 32 # ' ' + si += 1 + b = si < slen ? str.getbyte(si) : nil + unless b && b >= 48 && b <= 57 + hash[:_fail] = true + return -1 + end + n = b - 48 + si += 1 + else + b = si < slen ? str.getbyte(si) : nil + unless b && b >= 48 && b <= 57 + hash[:_fail] = true + return -1 + end + n = b - 48 + si += 1 + b = si < slen ? str.getbyte(si) : nil + if b && b >= 48 && b <= 57 + n = n * 10 + (b - 48) + si += 1 + end + end + if n > 24 + hash[:_fail] = true + return -1 + end + hash[:hour] = n + + when 73, 108 # 'I', 'l' + # 12-hour clock (leading space allowed) - inlined + if si < slen && str.getbyte(si) == 32 # ' ' + si += 1 + b = si < slen ? str.getbyte(si) : nil + unless b && b >= 48 && b <= 57 + hash[:_fail] = true + return -1 + end + n = b - 48 + si += 1 + else + b = si < slen ? str.getbyte(si) : nil + unless b && b >= 48 && b <= 57 + hash[:_fail] = true + return -1 + end + n = b - 48 + si += 1 + b = si < slen ? str.getbyte(si) : nil + if b && b >= 48 && b <= 57 + n = n * 10 + (b - 48) + si += 1 + end + end + if n < 1 || n > 12 + hash[:_fail] = true + return -1 + end + hash[:hour] = n + + when 106 # 'j' + # Day of year (3-digit) + n, l = _sp_digits(str, si, slen, 3) + if l == 0 || n < 1 || n > 366 + hash[:_fail] = true + return -1 + end + si += l + hash[:yday] = n + + when 76 # 'L' + # Milliseconds: greedy unless next spec is numeric + sb = si < slen ? str.getbyte(si) : nil + if sb == 43 || sb == 45 # '+' or '-' + sign = sb == 45 ? -1 : 1 + si += 1 + else + sign = 1 + end + osi = si + w = _sp_num_p_b?(fmt, fi, flen) ? 3 : 10000 + n, l = _sp_digits(str, si, slen, w) + if l == 0 + hash[:_fail] = true + return -1 + end + si += l + n = -n if sign == -1 + hash[:sec_fraction] = Rational(n, 10**(si - osi)) + + when 77 # 'M' + # Minute - inlined + b = si < slen ? str.getbyte(si) : nil + unless b && b >= 48 && b <= 57 + hash[:_fail] = true + return -1 + end + n = b - 48 + si += 1 + b = si < slen ? str.getbyte(si) : nil + if b && b >= 48 && b <= 57 + n = n * 10 + (b - 48) + si += 1 + end + if n > 59 + hash[:_fail] = true + return -1 + end + hash[:min] = n + + when 109 # 'm' + # Month - inlined + b = si < slen ? str.getbyte(si) : nil + unless b && b >= 48 && b <= 57 + hash[:_fail] = true + return -1 + end + n = b - 48 + si += 1 + b = si < slen ? str.getbyte(si) : nil + if b && b >= 48 && b <= 57 + n = n * 10 + (b - 48) + si += 1 + end + if n < 1 || n > 12 + hash[:_fail] = true + return -1 + end + hash[:mon] = n + + when 78 # 'N' + # Nanoseconds (or sub-second fraction): greedy unless next spec is numeric + sb = si < slen ? str.getbyte(si) : nil + if sb == 43 || sb == 45 # '+' or '-' + sign = sb == 45 ? -1 : 1 + si += 1 + else + sign = 1 + end + osi = si + w = _sp_num_p_b?(fmt, fi, flen) ? 9 : 10000 + n, l = _sp_digits(str, si, slen, w) + if l == 0 + hash[:_fail] = true + return -1 + end + si += l + n = -n if sign == -1 + hash[:sec_fraction] = Rational(n, 10**(si - osi)) + + when 110, 116 # 'n', 't' + # Match any whitespace + new_si = _sp_run(str, si, ' ', hash) + return new_si if new_si < 0 + si = new_si + + when 80, 112 # 'P', 'p' + # AM/PM with optional dot notation (A.M./P.M.) + if si >= slen + hash[:_fail] = true + return -1 + end + c0 = str.getbyte(si) + if c0 == 80 || c0 == 112 # 'P' or 'p' + merid = 12 + elsif c0 == 65 || c0 == 97 # 'A' or 'a' + merid = 0 + else + hash[:_fail] = true + return -1 + end + if si + 1 < slen && str.getbyte(si + 1) == 46 # '.' + # Dot notation: X.M. + if si + 3 >= slen || str.getbyte(si + 3) != 46 # '.' + hash[:_fail] = true + return -1 + end + c_m = str.getbyte(si + 2) + unless c_m == 77 || c_m == 109 # 'M' or 'm' + hash[:_fail] = true + return -1 + end + si += 4 + else + if si + 1 >= slen + hash[:_fail] = true + return -1 + end + c_m = str.getbyte(si + 1) + unless c_m == 77 || c_m == 109 # 'M' or 'm' + hash[:_fail] = true + return -1 + end + si += 2 + end + hash[:_merid] = merid + + when 81 # 'Q' + # Milliseconds since Unix epoch + sign = 1 + if si < slen && str.getbyte(si) == 45 # '-' + sign = -1 + si += 1 + end + n, l = _sp_digits(str, si, slen, 10000) + if l == 0 + hash[:_fail] = true + return -1 + end + si += l + n = -n if sign == -1 + hash[:seconds] = Rational(n, 1000) + + when 82 # 'R' + new_si = _sp_run(str, si, '%H:%M', hash) + return new_si if new_si < 0 + si = new_si + + when 114 # 'r' + new_si = _sp_run(str, si, '%I:%M:%S %p', hash) + return new_si if new_si < 0 + si = new_si + + when 83 # 'S' + # Second (0-60 to allow leap second) - inlined + b = si < slen ? str.getbyte(si) : nil + unless b && b >= 48 && b <= 57 + hash[:_fail] = true + return -1 + end + n = b - 48 + si += 1 + b = si < slen ? str.getbyte(si) : nil + if b && b >= 48 && b <= 57 + n = n * 10 + (b - 48) + si += 1 + end + if n > 60 + hash[:_fail] = true + return -1 + end + hash[:sec] = n + + when 115 # 's' + # Seconds since Unix epoch + sign = 1 + if si < slen && str.getbyte(si) == 45 # '-' + sign = -1 + si += 1 + end + n, l = _sp_digits(str, si, slen, 10000) + if l == 0 + hash[:_fail] = true + return -1 + end + si += l + n = -n if sign == -1 + hash[:seconds] = n + + when 84 # 'T' + new_si = _sp_run(str, si, '%H:%M:%S', hash) + return new_si if new_si < 0 + si = new_si + + when 85 # 'U' + # Week number (Sunday-based) + n, l = _sp_digits(str, si, slen, 2) + if l == 0 || n > 53 + hash[:_fail] = true + return -1 + end + si += l + hash[:wnum0] = n + + when 117 # 'u' + # ISO weekday (1=Mon..7=Sun) + n, l = _sp_digits(str, si, slen, 1) + if l == 0 || n < 1 || n > 7 + hash[:_fail] = true + return -1 + end + si += l + hash[:cwday] = n + + when 86 # 'V' + # ISO week number + n, l = _sp_digits(str, si, slen, 2) + if l == 0 || n < 1 || n > 53 + hash[:_fail] = true + return -1 + end + si += l + hash[:cweek] = n + + when 118 # 'v' + new_si = _sp_run(str, si, '%e-%b-%Y', hash) + return new_si if new_si < 0 + si = new_si + + when 87 # 'W' + # Week number (Monday-based) + n, l = _sp_digits(str, si, slen, 2) + if l == 0 || n > 53 + hash[:_fail] = true + return -1 + end + si += l + hash[:wnum1] = n + + when 119 # 'w' + # Weekday (0=Sun..6=Sat) + n, l = _sp_digits(str, si, slen, 1) + if l == 0 || n > 6 + hash[:_fail] = true + return -1 + end + si += l + hash[:wday] = n + + when 88 # 'X' + new_si = _sp_run(str, si, '%H:%M:%S', hash) + return new_si if new_si < 0 + si = new_si + + when 120 # 'x' + new_si = _sp_run(str, si, '%m/%d/%y', hash) + return new_si if new_si < 0 + si = new_si + + when 89 # 'Y' + # Full year: greedy unless next spec is numeric - inlined + sb = si < slen ? str.getbyte(si) : nil + if sb == 43 || sb == 45 # '+' or '-' + sign = sb == 45 ? -1 : 1 + si += 1 + else + sign = 1 + end + w = _sp_num_p_b?(fmt, fi, flen) ? 4 : 10000 + b = si < slen ? str.getbyte(si) : nil + unless b && b >= 48 && b <= 57 + hash[:_fail] = true + return -1 + end + n = b - 48 + si += 1 + l = 1 + while l < w && si < slen + b = str.getbyte(si) + break unless b && b >= 48 && b <= 57 + n = n * 10 + (b - 48) + si += 1 + l += 1 + end + hash[:year] = sign * n + + when 121 # 'y' + # 2-digit year - inlined + b = si < slen ? str.getbyte(si) : nil + unless b && b >= 48 && b <= 57 + hash[:_fail] = true + return -1 + end + n = b - 48 + si += 1 + b = si < slen ? str.getbyte(si) : nil + if b && b >= 48 && b <= 57 + n = n * 10 + (b - 48) + si += 1 + end + if n > 99 + hash[:_fail] = true + return -1 + end + hash[:year] = n + hash[:_cent] ||= n >= 69 ? 19 : 20 + + when 90, 122 # 'Z', 'z' + new_si = _sp_zone(str, si, slen, hash) + if new_si < 0 + hash[:_fail] = true + return -1 + end + si = new_si - when 'w' # Weekday number (0-6, Sunday=0) - b = str.getbyte(pos) - return nil unless b && b >= 48 && b <= 54 # '0'..'6' - hash[:wday] = b - 48 - ss.pos = pos + 1 - true - - when 'u' # Weekday number (1-7, Monday=1) - b = str.getbyte(pos) - return nil unless b && b >= 49 && b <= 55 # '1'..'7' - hash[:cwday] = b - 48 - ss.pos = pos + 1 - true - - when 'U' # Week number (Sunday start, 00-53) - wnum, new_pos = scan_uint(str, pos, width || 2) - return nil unless wnum - return nil if wnum > 53 - hash[:wnum0] = wnum - ss.pos = new_pos - true - - when 'W' # Week number (Monday start, 00-53) - wnum, new_pos = scan_uint(str, pos, width || 2) - return nil unless wnum - return nil if wnum > 53 - hash[:wnum1] = wnum - ss.pos = new_pos - true - - when 'V' # ISO week number (01-53) - cweek, new_pos = scan_uint(str, pos, width || 2) - return nil unless cweek - return nil if cweek < 1 || cweek > 53 - hash[:cweek] = cweek - ss.pos = new_pos - true - - when 'G' # ISO week year - cwyear, new_pos = scan_sint(str, pos, width || (next_is_num ? 4 : 40)) - return nil unless cwyear - hash[:cwyear] = cwyear - ss.pos = new_pos - true - - when 'g' # ISO week year (2-digit) - y, new_pos = scan_uint(str, pos, width || 2) - return nil unless y - if hash[:_century] - hash[:cwyear] = hash[:_century] * 100 + y - hash[:_century_set] = true - else - hash[:cwyear] = y >= 69 ? y + 1900 : y + 2000 - end - ss.pos = new_pos - true - - when 'Z', 'z' # Timezone - result = _strptime_zone(str, pos) - return nil unless result - hash[:zone] = result[:zone] - hash[:offset] = result[:offset] unless result[:offset].nil? - ss.pos = result[:pos] - true - - when 's' # Seconds since epoch - secs, new_pos = scan_sint(str, pos, 40) - return nil unless secs - hash[:seconds] = secs - ss.pos = new_pos - true - - when 'Q' # Milliseconds since epoch - msecs, new_pos = scan_sint(str, pos, 40) - return nil unless msecs - hash[:seconds] = Rational(msecs, 1000) - ss.pos = new_pos - true - - when 'n', 't' # Newline / Tab — match any whitespace - skip_ws(ss) - true - - when '%' # Literal % - return nil unless str.getbyte(pos) == 37 # '%' - ss.pos = pos + 1 - true - - when 'F' # %Y-%m-%d - result = _strptime_composite(ss, '%Y-%m-%d', hash) - return nil unless result - hash.merge!(result) - true - - when 'D', 'x' # %m/%d/%y - result = _strptime_composite(ss, '%m/%d/%y', hash) - return nil unless result - hash.merge!(result) - true - - when 'T', 'X' # %H:%M:%S - result = _strptime_composite(ss, '%H:%M:%S', hash) - return nil unless result - hash.merge!(result) - true - - when 'R' # %H:%M - result = _strptime_composite(ss, '%H:%M', hash) - return nil unless result - hash.merge!(result) - true - - when 'r' # %I:%M:%S %p - result = _strptime_composite(ss, '%I:%M:%S %p', hash) - return nil unless result - hash.merge!(result) - true - - when 'c' # %a %b %e %H:%M:%S %Y - result = _strptime_composite(ss, '%a %b %e %H:%M:%S %Y', hash) - return nil unless result - hash.merge!(result) - true - - when 'v' # %e-%b-%Y - result = _strptime_composite(ss, '%e-%b-%Y', hash) - return nil unless result - hash.merge!(result) - true - - when '+' # %a %b %e %H:%M:%S %Z %Y - result = _strptime_composite(ss, '%a %b %e %H:%M:%S %Z %Y', hash) - return nil unless result - hash.merge!(result) - true + when 37 # '%' + if si >= slen || str.getbyte(si) != 37 + hash[:_fail] = true + return -1 + end + si += 1 + + when 43 # '+' + new_si = _sp_run(str, si, '%a %b %e %H:%M:%S %Z %Y', hash) + return new_si if new_si < 0 + si = new_si - else - # Unknown specifier - try to match literal - literal = "%#{spec}" - if str[pos, literal.length] == literal - ss.pos = pos + literal.length - true else - nil + # Unknown spec: match '%' then spec literally + if si >= slen || str.getbyte(si) != 37 # '%' + hash[:_fail] = true + return -1 + end + si += 1 + if spec + if si >= slen || str.getbyte(si) != spec + hash[:_fail] = true + return -1 + end + si += 1 + end end end + + si end - def _strptime_composite(ss, format, context_hash) - merged_hash = context_hash.dup + # Case-insensitive byte-level head match. + # Compares str[si..si+len-1] against pre-computed lowercase byte array. + # Uses | 0x20 for ASCII alpha downcase (works for A-Z only). + def _sp_head_match?(str, si, slen, lower_bytes, len) + return false if si + len > slen i = 0 - fmt_len = format.length - while i < fmt_len - fb = format.getbyte(i) - if fb == 37 && i + 1 < fmt_len # '%' - i += 1 - spec = format[i] - i += 1 - return nil unless _strptime_spec(ss, spec, nil, merged_hash) - elsif fb == 32 || fb == 9 || fb == 10 || fb == 13 || fb == 11 || fb == 12 # whitespace - i += 1 - skip_ws(ss) - else - if ss.string.getbyte(ss.pos) == fb - ss.pos += 1 - else - return nil - end - i += 1 + while i < len + return false if (str.getbyte(si + i) | 0x20) != lower_bytes[i] + i += 1 + end + true + end + + # Fast path for %Y-%m-%d / %F format. + # For common "YYYY-MM-DD" format, uses byteslice+to_i (fewer method calls). + # Falls back to getbyte loop for non-standard lengths or signed years. + def _strptime_ymd(str) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + slen = str.bytesize + + # Fast path for "YYYY-MM-DD" (exactly 10 chars) or "YYYY-MM-DD..." + if slen >= 10 && str.getbyte(4) == 45 && str.getbyte(7) == 45 + b0 = str.getbyte(0) + if b0 >= 48 && b0 <= 57 # first char is digit (positive 4-digit year) + year = str.byteslice(0, 4).to_i + mon = str.byteslice(5, 2).to_i + mday = str.byteslice(8, 2).to_i + return nil if mon < 1 || mon > 12 || mday < 1 || mday > 31 + hash = { year: year, mon: mon, mday: mday } + hash[:leftover] = str.byteslice(10, slen - 10) if slen > 10 + return hash end end - # Return only newly parsed or updated keys - new_hash = {} - merged_hash.each { |k, v| new_hash[k] = v unless context_hash.key?(k) && context_hash[k] == v } - merged_hash.each { |k, v| new_hash[k] = v if context_hash[k] != v } - new_hash + + # General path for signed years, short years, etc. + si = 0 + sign = 1 + b = str.getbyte(si) + if b == 43 # '+' + si += 1 + b = str.getbyte(si) + elsif b == 45 # '-' + sign = -1 + si += 1 + b = str.getbyte(si) + end + return nil unless b && b >= 48 && b <= 57 + year = b - 48 + si += 1 + while si < slen + b = str.getbyte(si) + break unless b && b >= 48 && b <= 57 + year = year * 10 + (b - 48) + si += 1 + end + year = -year if sign == -1 + + return nil unless si < slen && str.getbyte(si) == 45 + si += 1 + b = str.getbyte(si) + return nil unless b && b >= 48 && b <= 57 + mon = b - 48 + si += 1 + b = str.getbyte(si) + if b && b >= 48 && b <= 57 + mon = mon * 10 + (b - 48) + si += 1 + end + return nil if mon < 1 || mon > 12 + + return nil unless si < slen && str.getbyte(si) == 45 + si += 1 + b = str.getbyte(si) + return nil unless b && b >= 48 && b <= 57 + mday = b - 48 + si += 1 + b = str.getbyte(si) + if b && b >= 48 && b <= 57 + mday = mday * 10 + (b - 48) + si += 1 + end + return nil if mday < 1 || mday > 31 + + hash = { year: year, mon: mon, mday: mday } + hash[:leftover] = str.byteslice(si, slen - si) if si < slen + hash end - def _strptime_zone(str, pos) - remaining = str[pos..] - return nil if remaining.nil? || remaining.empty? - - # Try numeric timezone: +HH:MM, -HH:MM, +HH:MM:SS, -HH:MM:SS, +HHMM, -HHMM, +HH, -HH - # Also: GMT+HH, GMT-HH:MM, etc. and decimal offsets - # Colon-separated pattern (requires colon) tried first, then plain digits. - m = remaining.match(/\A( - (?:GMT|UTC)? - [+-] - (?:\d{1,2}:\d{2}(?::\d{2})? - | - \d+(?:[.,]\d+)?) - )/xi) - - if m - zone_str = m[1] - offset = _parse_zone_offset(zone_str) - return { pos: pos + zone_str.length, zone: zone_str, offset: offset } - end - - # Try named timezone (multi-word: "E. Australia Standard Time", "Mountain Daylight Time") - # Match alphabetic words with dots and spaces - m = remaining.match(/\A([A-Za-z][A-Za-z.]*(?:\s+[A-Za-z][A-Za-z.]*)*)/i) - if m - zone_candidate = m[1] - # Try progressively shorter matches (longest first) - words = zone_candidate.split(/\s+/) - (words.length).downto(1) do |n| - try_zone = words[0, n].join(' ') - offset = _zone_name_to_offset(try_zone) - if offset - # Compute actual consumed length preserving original spacing - if n == words.length - actual_zone = zone_candidate - else - # Find end of nth word in original string - end_pos = 0 - n.times do |wi| - end_pos = zone_candidate.index(words[wi], end_pos) - end_pos += words[wi].length + # Ultra-fast path: parse %Y-%m-%d and directly create Date object. + # Skips Hash creation, _sp_complete_frags, and _sp_valid_date_frags_p entirely. + # Returns Date object on success, nil on failure. + def _strptime_ymd_to_date(str, sg) # rubocop:disable Metrics/MethodLength + slen = str.bytesize + + # Ultra-fast path for exactly "YYYY-MM-DD" (10 chars, positive 4-digit year) + if slen == 10 && str.getbyte(4) == 45 && str.getbyte(7) == 45 + b0 = str.getbyte(0) + if b0 >= 48 && b0 <= 57 + year = str.byteslice(0, 4).to_i + mon = str.byteslice(5, 2).to_i + mday = str.byteslice(8, 2).to_i + if mon >= 1 && mon <= 12 && mday >= 1 && mday <= 31 + # Inline civil validation + JD + if sg != Float::INFINITY + dim = DAYS_IN_MONTH_GREGORIAN[mon] + if mon == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) + dim = 29 end - actual_zone = zone_candidate[0, end_pos] + return nil if mday > dim + gy = mon <= 2 ? year - 1 : year + gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[mon] + mday + a = gy / 100 + gjd = gjd_base - 1524 + 2 - a + a / 4 + jd = gjd >= sg ? gjd : gjd_base - 1524 + return _new_from_jd(jd, sg) + else + jd = internal_valid_civil?(year, mon, mday, sg) + return jd ? _new_from_jd(jd, sg) : nil end - return { pos: pos + actual_zone.length, zone: actual_zone, offset: offset } end + return nil end - # Unknown timezone - return full match with nil offset - # (Military single-letter zones like 'z' are already in ZONE_TABLE - # and handled by the loop above) - return { pos: pos + zone_candidate.length, zone: zone_candidate, offset: nil } end - nil + # General path for signed years, non-standard lengths + si = 0 + sign = 1 + b = str.getbyte(si) + if b == 43 # '+' + si += 1 + b = str.getbyte(si) + elsif b == 45 # '-' + sign = -1 + si += 1 + b = str.getbyte(si) + end + return nil unless b && b >= 48 && b <= 57 + year = b - 48 + si += 1 + while si < slen + b = str.getbyte(si) + break unless b && b >= 48 && b <= 57 + year = year * 10 + (b - 48) + si += 1 + end + year = -year if sign == -1 + return nil unless si < slen && str.getbyte(si) == 45 + si += 1 + b = str.getbyte(si) + return nil unless b && b >= 48 && b <= 57 + mon = b - 48 + si += 1 + b = str.getbyte(si) + if b && b >= 48 && b <= 57 + mon = mon * 10 + (b - 48) + si += 1 + end + return nil if mon < 1 || mon > 12 + return nil unless si < slen && str.getbyte(si) == 45 + si += 1 + b = str.getbyte(si) + return nil unless b && b >= 48 && b <= 57 + mday = b - 48 + si += 1 + b = str.getbyte(si) + if b && b >= 48 && b <= 57 + mday = mday * 10 + (b - 48) + si += 1 + end + return nil if mday < 1 || mday > 31 + return nil if si < slen + + # Inline civil validation + JD computation + # For common Gregorian dates with valid day-of-month, compute JD directly + if sg != Float::INFINITY # Gregorian path (most common) + dim = DAYS_IN_MONTH_GREGORIAN[mon] + if mon == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) + dim = 29 + end + return nil if mday > dim + # Inline civil_to_jd for Gregorian + gy = mon <= 2 ? year - 1 : year + offset = GJD_MONTH_OFFSET[mon] + gjd_base = (1461 * (gy + 4716)) / 4 + offset + mday + a = gy / 100 + gjd = gjd_base - 1524 + 2 - a + a / 4 + jd = gjd >= sg ? gjd : gjd_base - 1524 + else + jd = internal_valid_civil?(year, mon, mday, sg) + return nil unless jd + end + _new_from_jd(jd, sg) end - def _strptime_zone_colon(str, pos, colons) - remaining = str[pos..] - return nil if remaining.nil? || remaining.empty? - - case colons - when 1 # %:z -> +HH:MM - m = remaining.match(/\A([+-])(\d{2}):(\d{2})/) - return nil unless m - sign = m[1] == '-' ? -1 : 1 - offset = sign * (m[2].to_i * 3600 + m[3].to_i * 60) - zone = m[0] - { pos: pos + zone.length, zone: zone, offset: offset } - when 2 # %::z -> +HH:MM:SS - m = remaining.match(/\A([+-])(\d{2}):(\d{2}):(\d{2})/) - return nil unless m - sign = m[1] == '-' ? -1 : 1 - offset = sign * (m[2].to_i * 3600 + m[3].to_i * 60 + m[4].to_i) - zone = m[0] - { pos: pos + zone.length, zone: zone, offset: offset } - when 3 # %:::z -> +HH[:MM[:SS]] - m = remaining.match(/\A([+-])(\d{2})(?::(\d{2})(?::(\d{2}))?)?/) - return nil unless m - sign = m[1] == '-' ? -1 : 1 - offset = sign * (m[2].to_i * 3600 + (m[3] ? m[3].to_i * 60 : 0) + (m[4] ? m[4].to_i : 0)) - zone = m[0] - { pos: pos + zone.length, zone: zone, offset: offset } + # Fast path for "%a %b %d %Y" format (complex benchmark). + # Byte-level name matching + digit parsing. Zero String allocation. + def _strptime_abdy(str) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + slen = str.bytesize + si = 0 + + # Match weekday name using 3-byte key lookup + return nil if si + 2 >= slen + key = ((str.getbyte(si) | 0x20) << 16) | ((str.getbyte(si + 1) | 0x20) << 8) | (str.getbyte(si + 2) | 0x20) + entry = ABBR_DAY_3KEY[key] + return nil unless entry + wday = entry[0] + full_len = entry[1] + if si + full_len <= slen && _sp_head_match?(str, si, slen, DAY_LOWER_BYTES[wday], full_len) + si += full_len else - nil + si += 3 + end + + # Expect space(s) + return nil if si >= slen || str.getbyte(si) != 32 + si += 1 + si += 1 while si < slen && str.getbyte(si) == 32 + + # Match month name using 3-byte key lookup + return nil if si + 2 >= slen + key = ((str.getbyte(si) | 0x20) << 16) | ((str.getbyte(si + 1) | 0x20) << 8) | (str.getbyte(si + 2) | 0x20) + entry = ABBR_MONTH_3KEY[key] + return nil unless entry + mon = entry[0] + full_len = entry[1] + if si + full_len <= slen && _sp_head_match?(str, si, slen, MONTH_LOWER_BYTES[mon], full_len) + si += full_len + else + si += 3 + end + + # Expect space(s) + return nil if si >= slen || str.getbyte(si) != 32 + si += 1 + si += 1 while si < slen && str.getbyte(si) == 32 + + # Parse day (1-2 digits) + b = str.getbyte(si) + return nil unless b && b >= 48 && b <= 57 + mday = b - 48 + si += 1 + b = str.getbyte(si) + if b && b >= 48 && b <= 57 + mday = mday * 10 + (b - 48) + si += 1 + end + return nil if mday < 1 || mday > 31 + + # Expect space(s) + return nil if si >= slen || str.getbyte(si) != 32 + si += 1 + si += 1 while si < slen && str.getbyte(si) == 32 + + # Parse year: optional sign + greedy digits + sign = 1 + b = str.getbyte(si) + if b == 43 # '+' + si += 1 + b = str.getbyte(si) + elsif b == 45 # '-' + sign = -1 + si += 1 + b = str.getbyte(si) + end + + return nil unless b && b >= 48 && b <= 57 + year = b - 48 + si += 1 + while si < slen + b = str.getbyte(si) + break unless b && b >= 48 && b <= 57 + year = year * 10 + (b - 48) + si += 1 + end + year = -year if sign == -1 + + hash = { year: year, mon: mon, mday: mday, wday: wday } + hash[:leftover] = str.byteslice(si, slen - si) if si < slen + hash + end + + # Ultra-fast path: parse "%a %b %d %Y" and directly create Date object. + # Combines parsing + civil validation + JD computation without Hash. + def _strptime_abdy_to_date(str, sg) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + slen = str.bytesize + si = 0 + + # Match weekday name using 3-byte key lookup + return nil if si + 2 >= slen + key = ((str.getbyte(si) | 0x20) << 16) | ((str.getbyte(si + 1) | 0x20) << 8) | (str.getbyte(si + 2) | 0x20) + entry = ABBR_DAY_3KEY[key] + return nil unless entry + full_len = entry[1] + # Try full name first, then abbreviation + if si + full_len <= slen && _sp_head_match?(str, si, slen, DAY_LOWER_BYTES[entry[0]], full_len) + si += full_len + else + si += 3 + end + + # Expect space(s) + return nil if si >= slen || str.getbyte(si) != 32 + si += 1 + si += 1 while si < slen && str.getbyte(si) == 32 + + # Match month name using 3-byte key lookup + return nil if si + 2 >= slen + key = ((str.getbyte(si) | 0x20) << 16) | ((str.getbyte(si + 1) | 0x20) << 8) | (str.getbyte(si + 2) | 0x20) + entry = ABBR_MONTH_3KEY[key] + return nil unless entry + mon = entry[0] + full_len = entry[1] + if si + full_len <= slen && _sp_head_match?(str, si, slen, MONTH_LOWER_BYTES[mon], full_len) + si += full_len + else + si += 3 + end + + # Expect space(s) + return nil if si >= slen || str.getbyte(si) != 32 + si += 1 + si += 1 while si < slen && str.getbyte(si) == 32 + + # Parse day (1-2 digits) + b = str.getbyte(si) + return nil unless b && b >= 48 && b <= 57 + mday = b - 48 + si += 1 + b = str.getbyte(si) + if b && b >= 48 && b <= 57 + mday = mday * 10 + (b - 48) + si += 1 + end + return nil if mday < 1 || mday > 31 + + # Expect space(s) + return nil if si >= slen || str.getbyte(si) != 32 + si += 1 + si += 1 while si < slen && str.getbyte(si) == 32 + + # Parse year: optional sign + greedy digits + sign = 1 + b = str.getbyte(si) + if b == 43 # '+' + si += 1 + b = str.getbyte(si) + elsif b == 45 # '-' + sign = -1 + si += 1 + b = str.getbyte(si) + end + return nil unless b && b >= 48 && b <= 57 + year = b - 48 + si += 1 + while si < slen + b = str.getbyte(si) + break unless b && b >= 48 && b <= 57 + year = year * 10 + (b - 48) + si += 1 + end + year = -year if sign == -1 + + # Must consume entire string + return nil if si < slen + + # Inline civil validation + JD computation + if sg != Float::INFINITY + dim = DAYS_IN_MONTH_GREGORIAN[mon] + if mon == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) + dim = 29 + end + return nil if mday > dim + gy = mon <= 2 ? year - 1 : year + offset = GJD_MONTH_OFFSET[mon] + gjd_base = (1461 * (gy + 4716)) / 4 + offset + mday + a = gy / 100 + gjd = gjd_base - 1524 + 2 - a + a / 4 + jd = gjd >= sg ? gjd : gjd_base - 1524 + else + jd = internal_valid_civil?(year, mon, mday, sg) + return nil unless jd end + _new_from_jd(jd, sg) + end + + # Parse zone from string at position si; update hash[:zone] and hash[:offset]. + # Returns new si on success, -1 on failure. + def _sp_zone(str, si, slen, hash) + m = STRPTIME_ZONE_PAT.match(str[si..]) + return -1 unless m + zone_str = m[1] + hash[:zone] = zone_str + hash[:offset] = _sp_zone_to_diff(zone_str) + si + m[0].length end - def _parse_zone_offset(zone_str) - # Strip GMT/UTC prefix - s = zone_str.sub(/\A(?:GMT|UTC)/i, '') - return 0 if s.empty? - - m = s.match(/\A([+-])(\d+(?:[.,]\d+)?)$/) - if m - sign = m[1] == '-' ? -1 : 1 - num = m[2].tr(',', '.') - if num.include?('.') - # Decimal hours - hours = num.to_f - return nil if hours.abs >= 24 - return sign * (hours * 3600).to_i + # Convert a zone string to seconds offset from UTC. + # Returns Integer (seconds) or Rational, or nil if unparseable. + # Mirrors date_zone_to_diff() in ext/date/date_parse.c. + def _sp_zone_to_diff(zone_str) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + # Fast path for common numeric zones + len = zone_str.length + b0 = zone_str.getbyte(0) + if b0 == 43 || b0 == 45 # '+' or '-' + sign = b0 == 45 ? -1 : 1 + if len == 6 && zone_str.getbyte(3) == 58 # +HH:MM + b1 = zone_str.getbyte(1) + b2 = zone_str.getbyte(2) + b4 = zone_str.getbyte(4) + b5 = zone_str.getbyte(5) + if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b4 >= 48 && b4 <= 57 && b5 >= 48 && b5 <= 57 + h = (b1 - 48) * 10 + (b2 - 48) + m = (b4 - 48) * 10 + (b5 - 48) + return nil if h > 23 || m > 59 + return sign * (h * 3600 + m * 60) + end + elsif len == 5 # +HHMM + b1 = zone_str.getbyte(1) + b2 = zone_str.getbyte(2) + b3 = zone_str.getbyte(3) + b4 = zone_str.getbyte(4) + if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && b4 >= 48 && b4 <= 57 + return sign * ((b1 - 48) * 36000 + (b2 - 48) * 3600 + (b3 - 48) * 600 + (b4 - 48) * 60) + end + end + elsif len == 1 && (b0 == 90 || b0 == 122) # Z/z + return 0 + elsif len <= 3 + off = ZONE_TABLE[zone_str.downcase] + return off if off + end + + s = zone_str.dup + dst = false + + # Strip trailing " time" (optionally preceded by "standard" or "daylight") + strip_word = lambda do |str, len, word| + n = word.length + return nil unless len > n + return nil unless str[len - n - 1] =~ /[[:space:]]/ + return nil unless str[len - n, n].casecmp(word) == 0 + n += 1 + n += 1 while len > n && str[len - n - 1] =~ /[[:space:]]/ + n + end + + l = s.length + if (w = strip_word.call(s, l, 'time')) + l -= w + if (w2 = strip_word.call(s, l, 'standard')) + l -= w2 + elsif (w2 = strip_word.call(s, l, 'daylight')) + l -= w2 + dst = true else - # Could be HH, HHMM, or HHMMSS - digits = num - case digits.length - when 1, 2 - h = digits.to_i - return nil if h >= 24 - return sign * h * 3600 - when 3, 4 - h = digits[0, 2].to_i - min = digits[2, 2].to_i - return nil if h >= 24 || min >= 60 - return sign * (h * 3600 + min * 60) - when 5, 6 - h = digits[0, 2].to_i - min = digits[2, 2].to_i - sec = digits[4, 2].to_i - return nil if h >= 24 || min >= 60 || sec >= 60 - return sign * (h * 3600 + min * 60 + sec) - else - return nil + l += w # revert + end + elsif (w = strip_word.call(s, l, 'dst')) + l -= w + dst = true + end + + shrunk = s[0, l].gsub(/[[:space:]]+/, ' ').strip + if (offset = ZONE_TABLE[shrunk.downcase]) + return dst ? offset + 3600 : offset + end + + # Numeric parsing + t = s[0, l].strip + t = t[3..] if t =~ /\Agmt/i + t = t[$&.length..] if t =~ /\Autc?/i + return nil unless t && t.length > 0 && (t[0] == '+' || t[0] == '-') + + sign = t[0] == '-' ? -1 : 1 + t = t[1..] + + if (m = t.match(/\A(\d+):(\d+)(?::(\d+))?\z/)) + h = m[1].to_i + mn = m[2].to_i + sc = m[3] ? m[3].to_i : 0 + return nil if h > 23 || mn > 59 || sc > 59 + sign * (h * 3600 + mn * 60 + sc) + elsif (m = t.match(/\A(\d+)[,.](\d*)/)) + h = m[1].to_i + return nil if h > 23 + frac_s = m[2] + n = [frac_s.length, 7].min + digits = frac_s[0, n].to_i + digits += 1 if frac_s.length > n && frac_s[n].to_i >= 5 + sec = digits * 36 + os = if n == 0 + h * 3600 + elsif n == 1 + sec * 10 + h * 3600 + elsif n == 2 + sec + h * 3600 + else + denom = 10**(n - 2) + r = Rational(sec, denom) + h * 3600 + r.denominator == 1 ? r.numerator : r + end + sign == -1 ? -os : os + elsif t =~ /\A(\d+)\z/ + digits = $1 + dlen = digits.length + h = digits[0, 2 - dlen % 2].to_i + mn = dlen >= 3 ? digits[2 - dlen % 2, 2].to_i : 0 + sc = dlen >= 5 ? digits[4 - dlen % 2, 2].to_i : 0 + sign * (h * 3600 + mn * 60 + sc) + else + nil + end + end + + # Rewrite :seconds (from %s/%Q) into jd + time components. + # Offset is applied first (converts UTC epoch to local time). + def _sp_rewrite_frags(hash) + seconds = hash.delete(:seconds) + return hash unless seconds + + offset = hash[:offset] || 0 + seconds = seconds + offset if offset != 0 + + d, fr = seconds.divmod(86400) + h, fr = fr.divmod(3600) + m, fr = fr.divmod(60) + s, fr = fr.divmod(1) + + hash[:jd] = 2440588 + d + hash[:hour] = h + hash[:min] = m + hash[:sec] = s + hash[:sec_fraction] = fr + hash + end + + # Complete partial date fragments by filling defaults from today's date. + # Mirrors rt_complete_frags() in C. + def _sp_complete_frags(klass, hash) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + # Fast path: detect :civil case (most common) without iterating all entries + k = nil + a = nil + if hash.key?(:year) || hash.key?(:mon) || hash.key?(:mday) + civil_n = 0 + civil_n += 1 if hash.key?(:year) + civil_n += 1 if hash.key?(:mon) + civil_n += 1 if hash.key?(:mday) + civil_n += 1 if hash.key?(:hour) + civil_n += 1 if hash.key?(:min) + civil_n += 1 if hash.key?(:sec) + # Check if any other pattern matches better + best_n = civil_n + skip_civil = false + if hash.key?(:jd) # jd entry has 1 element + skip_civil = true if 1 > best_n + end + if hash.key?(:yday) # ordinal [:year, :yday, :hour, :min, :sec] + ord_n = (hash.key?(:year) ? 1 : 0) + 1 + (hash.key?(:hour) ? 1 : 0) + (hash.key?(:min) ? 1 : 0) + (hash.key?(:sec) ? 1 : 0) + skip_civil = true if ord_n > best_n + end + if hash.key?(:cwyear) || hash.key?(:cweek) || hash.key?(:cwday) + com_n = (hash.key?(:cwyear) ? 1 : 0) + (hash.key?(:cweek) ? 1 : 0) + (hash.key?(:cwday) ? 1 : 0) + (hash.key?(:hour) ? 1 : 0) + (hash.key?(:min) ? 1 : 0) + (hash.key?(:sec) ? 1 : 0) + skip_civil = true if com_n > best_n + end + if hash.key?(:wnum0) + wn0_n = (hash.key?(:year) ? 1 : 0) + 1 + (hash.key?(:wday) ? 1 : 0) + (hash.key?(:hour) ? 1 : 0) + (hash.key?(:min) ? 1 : 0) + (hash.key?(:sec) ? 1 : 0) + skip_civil = true if wn0_n > best_n + end + if hash.key?(:wnum1) + wn1_n = (hash.key?(:year) ? 1 : 0) + 1 + (hash.key?(:wday) ? 1 : 0) + (hash.key?(:hour) ? 1 : 0) + (hash.key?(:min) ? 1 : 0) + (hash.key?(:sec) ? 1 : 0) + skip_civil = true if wn1_n > best_n + end + unless skip_civil + k = :civil + a = [:year, :mon, :mday, :hour, :min, :sec] + end + end + + unless k + best_k = nil + best_a = nil + best_n = 0 + COMPLETE_FRAGS_TAB.each do |ek, ea| + n = ea.count { |sym| hash.key?(sym) } + if n > best_n + best_k = ek + best_a = ea + best_n = n + end + end + k = best_k + a = best_a + end + + if k && best_n < a.length + today = nil + case k + when :ordinal + hash[:year] ||= (today ||= Date.today).year + hash[:yday] ||= 1 + when :civil + a.each do |sym| + break unless hash[sym].nil? + hash[sym] = (today ||= Date.today).__send__(sym) + end + hash[:mon] ||= 1 + hash[:mday] ||= 1 + when :commercial + a.each do |sym| + break unless hash[sym].nil? + hash[sym] = (today ||= Date.today).__send__(sym) + end + hash[:cweek] ||= 1 + hash[:cwday] ||= 1 + when :wday + today ||= Date.today + hash[:jd] = (today - today.wday + hash[:wday]).jd + when :wnum0 + a.each do |sym| + break unless hash[sym].nil? + hash[sym] = (today ||= Date.today).year end + hash[:wnum0] ||= 0 + hash[:wday] ||= 0 + when :wnum1 + a.each do |sym| + break unless hash[sym].nil? + hash[sym] = (today ||= Date.today).year + end + hash[:wnum1] ||= 0 + hash[:wday] ||= 1 end end - # +HH:MM or +HH:MM:SS - m = s.match(/\A([+-])(\d{1,2}):(\d{2})(?::(\d{2}))?$/) - if m - sign = m[1] == '-' ? -1 : 1 - h = m[2].to_i - min = m[3].to_i - sec = m[4] ? m[4].to_i : 0 - return nil if h >= 24 || min >= 60 || sec >= 60 - return sign * (h * 3600 + min * 60 + sec) + if k == :time && klass <= DateTime + hash[:jd] ||= Date.today.jd + end + + hash[:hour] ||= 0 + hash[:min] ||= 0 + hash[:sec] = if hash[:sec].nil? + 0 + elsif hash[:sec] > 59 + 59 + else + hash[:sec] + end + hash + end + + # Convert year/week/wday to Julian Day number. + # f=0: Sunday-based (%U), d=0=Sun..6=Sat + # f=1: Monday-based (%W), d=0=Mon..6=Sun (Mon-based) + # Mirrors c_weeknum_to_jd() in ext/date/date_core.c: + # rjd2 = JD(Jan 1) + 6 (= JD of Jan 7) + # return (rjd2 - MOD((rjd2 - f + 1), 7) - 7) + 7*w + d + def _sp_weeknum_to_jd(y, w, d, f, sg) + jd_jan7 = civil_to_jd(y, 1, 1, sg) + 6 + (jd_jan7 - (jd_jan7 - f + 1) % 7 - 7) + 7 * w + d + end + + # Find the Julian Day number from the fragment hash. + # Tries jd, ordinal, civil, commercial, wnum0, wnum1 in order. + # Returns jd integer or nil. + def _sp_valid_date_frags_p(hash, sg) # rubocop:disable Metrics/CyclomaticComplexity + return hash[:jd] if hash[:jd] + + if (yday = hash[:yday]) && (year = hash[:year]) + jd = internal_valid_ordinal?(year, yday, sg) + return jd if jd + end + + if (mday = hash[:mday]) && (mon = hash[:mon]) && (year = hash[:year]) + jd = internal_valid_civil?(year, mon, mday, sg) + return jd if jd + end + + # Commercial (ISO week): prefer cwday, else wday (treating 0 as 7) + wday = hash[:cwday] + if wday.nil? + wday = hash[:wday] + wday = 7 if !wday.nil? && wday == 0 + end + if wday && (week = hash[:cweek]) && (year = hash[:cwyear]) + jd = internal_valid_commercial?(year, week, wday, sg) + return jd if jd + end + + # wnum0 (Sunday-start): prefer wday (0=Sun), else cwday (converting 7→0) + wday = hash[:wday] + if wday.nil? + wday = hash[:cwday] + wday = 0 if !wday.nil? && wday == 7 + end + if wday && (week = hash[:wnum0]) && (year = hash[:year]) + jd = _sp_weeknum_to_jd(year, week, wday, 0, sg) + return jd if jd + end + + # wnum1 (Monday-start): convert to Mon-based 0=Mon using (wday-1)%7 + # Uses original wday (0=Sun) or cwday (1=Mon..7=Sun) — no 7→0 conversion here + wday = hash[:wday] + wday = hash[:cwday] if wday.nil? + wday = (wday - 1) % 7 if wday + if wday && (week = hash[:wnum1]) && (year = hash[:year]) + jd = _sp_weeknum_to_jd(year, week, wday, 1, sg) + return jd if jd end nil end - def _zone_name_to_offset(name) - ZONE_TABLE[name.downcase.gsub(/\s+/, ' ')] + # Create a Date object from parsed fragment hash. + def _new_by_frags(hash, sg) + raise Error, 'invalid date' if hash.nil? + hash = _sp_rewrite_frags(hash) + hash = _sp_complete_frags(Date, hash) + jd = _sp_valid_date_frags_p(hash, sg) + raise Error, 'invalid date' if jd.nil? + _new_from_jd(jd, sg) end end end diff --git a/lib/date/time.rb b/lib/date/time.rb index 3b73236b..ee8ef7c3 100644 --- a/lib/date/time.rb +++ b/lib/date/time.rb @@ -1,59 +1,31 @@ # frozen_string_literal: true class Time + # call-seq: + # t.to_time -> time + # + # Returns self. def to_time self end unless method_defined?(:to_time) + # call-seq: + # t.to_date -> date + # + # Returns a Date object which denotes self. def to_date - y = year - m = month - d = day - - nth, ry = Date.send(:decode_year, y, -1) - - # First, create it in GREGORIAN (dates during the reform period are also valid). - obj = Date.send(:d_simple_new_internal, - nth, 0, - Date::GREGORIAN, - ry, m, d, - 0x04) # Date::HAVE_CIVIL - - # Then change to DEFAULT_SG. - obj.send(:set_sg, Date::ITALY) - - obj + jd = Date.__send__(:gregorian_to_jd, year, mon, mday) + Date.__send__(:_new_from_jd, jd, Date::ITALY) end unless method_defined?(:to_date) + # call-seq: + # t.to_datetime -> datetime + # + # Returns a DateTime object which denotes self. def to_datetime - y = year - m = month - d = day - h = hour - mi = min - s = sec - of_sec = utc_offset - sf = nsec - - nth, ry = Date.send(:decode_year, y, -1) - rjd, _ = Date.send(:c_civil_to_jd, ry, m, d, Date::GREGORIAN) - - df = h * 3600 + mi * 60 + s - - # Convert local to UTC - df_utc = df - of_sec - jd_utc = rjd - if df_utc < 0 - jd_utc -= 1 - df_utc += 86400 - elsif df_utc >= 86400 - jd_utc += 1 - df_utc -= 86400 - end - - obj = DateTime.send(:new_with_jd_and_time, nth, jd_utc, df_utc, sf, of_sec, Date::GREGORIAN) - obj.send(:set_sg, Date::ITALY) - - obj + jd = Date.__send__(:gregorian_to_jd, year, mon, mday) + dt = DateTime.allocate + dt.__send__(:_init_datetime, jd, hour, min, sec, subsec, utc_offset, Date::ITALY) + dt end unless method_defined?(:to_datetime) end From d276c804d635db5bf707e6c5c0df4534e562361d Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 2 Mar 2026 01:32:06 +0900 Subject: [PATCH 006/144] Auto-generate lib/date/zonetab.rb from ext/date/zonetab.list Add ext/date/generate-zonetab-rb script that reads zonetab.list and produces lib/date/zonetab.rb, ensuring the Ruby hash table stays in sync with the C gperf header (zonetab.h) from the same sources. - Update ext/date/prereq.mk to run generate-zonetab-rb after update-abbr - Update .github/workflows/update.yml to include lib/date/zonetab.rb in the weekly auto-commit - Remove 75 "xxx standard time" entries from zonetab.rb that did not exist in zonetab.list or the C extension (316 entries, matching zonetab.list exactly) --- .github/workflows/update.yml | 2 +- ext/date/generate-zonetab-rb | 59 +++ ext/date/prereq.mk | 1 + lib/date/zonetab.rb | 718 ++++++++++++++++------------------- 4 files changed, 380 insertions(+), 400 deletions(-) create mode 100755 ext/date/generate-zonetab-rb diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index 9e0d465e..540a9967 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -31,7 +31,7 @@ jobs: echo "diff=true" >> $GITHUB_OUTPUT - name: Commit run: | - git commit --message="Update zonetab.h at $(date +%F)" ext/date + git commit --message="Update zonetab at $(date +%F)" ext/date lib/date/zonetab.rb git pull --ff-only origin ${GITHUB_REF#refs/heads/} git push origin ${GITHUB_REF#refs/heads/} env: diff --git a/ext/date/generate-zonetab-rb b/ext/date/generate-zonetab-rb new file mode 100755 index 00000000..64b72c7e --- /dev/null +++ b/ext/date/generate-zonetab-rb @@ -0,0 +1,59 @@ +# -*- mode: ruby -*- +# Generate lib/date/zonetab.rb from ext/date/zonetab.list +# +# Usage: ruby -C ext/date generate-zonetab-rb +# +# This script reads zonetab.list (the same source used to generate zonetab.h +# via gperf) and produces the equivalent Ruby hash table. + +list_path = File.join(__dir__, 'zonetab.list') +output_path = File.join(__dir__, '..', '..', 'lib', 'date', 'zonetab.rb') + +entries = {} +in_entries = false + +File.foreach(list_path) do |line| + line.chomp! + if line == '%%' + if in_entries + break + else + in_entries = true + next + end + end + next unless in_entries + + abbr, offset_expr = line.split(',', 2) + next unless offset_expr + + abbr.strip! + offset_expr.strip! + + # Evaluate offset expression (e.g., "0*3600", "-5*3600", "-(1*3600+1800)", "16200") + offset = eval(offset_expr) + + entries[abbr] = offset +end + +sorted = entries.sort_by { |k, _| k } + +max_key_len = sorted.map { |k, _| k.length }.max + +File.open(output_path, 'w') do |f| + f.puts '# frozen_string_literal: true' + f.puts + f.puts '# Timezone name => UTC offset (seconds) mapping table.' + f.puts '# Auto-generated from ext/date/zonetab.list by ext/date/generate-zonetab-rb.' + f.puts '# Do not edit manually.' + f.puts 'class Date' + f.puts ' ZONE_TABLE = {' + sorted.each do |abbr, offset| + key = abbr.include?(' ') ? %Q("#{abbr}") : %Q("#{abbr}") + f.puts " %-#{max_key_len + 3}s => %d," % [key, offset] + end + f.puts ' }.freeze' + f.puts 'end' +end + +puts "Generated #{output_path} with #{entries.size} entries." diff --git a/ext/date/prereq.mk b/ext/date/prereq.mk index b5d271a3..7f8e0bbf 100644 --- a/ext/date/prereq.mk +++ b/ext/date/prereq.mk @@ -10,6 +10,7 @@ zonetab.h: zonetab.list .PHONY: update-zonetab update-zonetab: $(RUBY) -C $(srcdir) update-abbr + $(RUBY) -C $(srcdir) generate-zonetab-rb .PHONY: update-nothing update-nothing: diff --git a/lib/date/zonetab.rb b/lib/date/zonetab.rb index c26262f0..b7e22c37 100644 --- a/lib/date/zonetab.rb +++ b/lib/date/zonetab.rb @@ -1,405 +1,325 @@ # frozen_string_literal: true -# Timezone name => UTC offset (seconds) mapping table -# Converted C's zonetab.h (gperf-generated hash table) to a Ruby hash. -# 316 zones in total. -# Search ignores case (.downcase on the caller before searching). -# -# Original data source: zonetab.h #included in date_parse.c -# gperf --ignore-case -L ANSI-C -C -c -P -p -j1 -i 1 -g -o -t \ -# -N zonetab zonetab.list -# The complete static hash table generated by was converted equivalently to a Ruby hash. +# Timezone name => UTC offset (seconds) mapping table. +# Auto-generated from ext/date/zonetab.list by ext/date/generate-zonetab-rb. +# Do not edit manually. class Date ZONE_TABLE = { - "a" => 3600, - "acdt" => 37800, - "acst" => 34200, - "act" => -18000, - "acwst" => 31500, - "adt" => -10800, - "aedt" => 39600, - "aest" => 36000, - "afghanistan" => 16200, - "aft" => 16200, - "ahst" => -36000, - "akdt" => -28800, - "akst" => -32400, - "alaskan" => -32400, - "almt" => 21600, - "anast" => 43200, - "anat" => 43200, - "aoe" => -43200, - "aqtt" => 18000, - "arab" => 10800, - "arabian" => 14400, - "arabic" => 10800, - "art" => -10800, - "ast" => -14400, - "at" => -7200, - "atlantic" => -14400, - "aus central" => 34200, - "aus eastern" => 36000, - "awdt" => 32400, - "awst" => 28800, - "azores" => -3600, - "azost" => 0, - "azot" => -3600, - "azst" => 18000, - "azt" => 14400, - "b" => 7200, - "bnt" => 28800, - "bot" => -14400, - "brst" => -7200, - "brt" => -10800, - "bst" => 3600, - "bt" => 10800, - "btt" => 21600, - "c" => 10800, - "canada central" => -21600, - "cape verde" => -3600, - "cast" => 28800, - "cat" => 7200, - "caucasus" => 14400, - "cct" => 23400, - "cdt" => -18000, - "cen. australia" => 34200, - "central" => -21600, - "central america" => -21600, - "central asia" => 21600, - "central europe" => 3600, - "central european" => 3600, - "central pacific" => 39600, - "cest" => 7200, - "cet" => 3600, - "chadt" => 49500, - "chast" => 45900, - "china" => 28800, - "chost" => 32400, - "chot" => 28800, - "chst" => 36000, - "chut" => 36000, - "cidst" => -14400, - "cist" => -18000, - "ckt" => -36000, - "clst" => -10800, - "clt" => -14400, - "cot" => -18000, - "cst" => -21600, - "cvt" => -3600, - "cxt" => 25200, - "d" => 14400, - "dateline" => -43200, - "davt" => 25200, - "ddut" => 36000, - "e" => 18000, - "e. africa" => 10800, - "e. australia" => 36000, - "e. europe" => 7200, - "e. south america" => -10800, - "eadt" => 39600, - "easst" => -18000, - "east" => -21600, - "eastern" => -18000, - "eat" => 10800, - "ect" => -18000, - "edt" => -14400, - "eest" => 10800, - "eet" => 7200, - "egst" => 0, - "egt" => -3600, - "egypt" => 7200, - "ekaterinburg" => 18000, - "est" => -18000, - "f" => 21600, - "fet" => 10800, - "fiji" => 43200, - "fjst" => 46800, - "fjt" => 43200, - "fkst" => -10800, - "fkt" => -14400, - "fle" => 7200, - "fnt" => -7200, - "fst" => 7200, - "fwt" => 3600, - "g" => 25200, - "galt" => -21600, - "gamt" => -32400, - "get" => 14400, - "gft" => -10800, - "gilt" => 43200, - "gmt" => 0, - "greenland" => -10800, - "greenwich" => 0, - "gst" => 36000, - "gtb" => 7200, - "gyt" => -14400, - "h" => 28800, - "hadt" => -32400, - "hast" => -36000, - "hawaiian" => -36000, - "hdt" => -32400, - "hkt" => 28800, - "hovst" => 28800, - "hovt" => 25200, - "hst" => -36000, - "i" => 32400, - "ict" => 25200, - "idle" => 43200, - "idlw" => -43200, - "idt" => 10800, - "india" => 19800, - "iot" => 21600, - "iran" => 12600, - "irdt" => 16200, - "irkst" => 32400, - "irkt" => 28800, - "irst" => 12600, - "ist" => 19800, - "jerusalem" => 7200, - "jst" => 32400, - "k" => 36000, - "kgt" => 21600, - "korea" => 32400, - "kost" => 39600, - "krast" => 28800, - "krat" => 25200, - "kst" => 32400, - "kuyt" => 14400, - "l" => 39600, - "lhdt" => 39600, - "lhst" => 37800, - "lint" => 50400, - "m" => 43200, - "magst" => 43200, - "magt" => 39600, - "malay peninsula" => 28800, - "mart" => -30600, - "mawt" => 18000, - "mdt" => -21600, - "mest" => 7200, - "mesz" => 7200, - "met" => 3600, - "mewt" => 3600, - "mexico" => -21600, - "mez" => 3600, - "mht" => 43200, - "mid-atlantic" => -7200, - "mmt" => 23400, - "mountain" => -25200, - "msd" => 14400, - "msk" => 10800, - "mst" => -25200, - "mut" => 14400, - "mvt" => 18000, - "myanmar" => 23400, - "myt" => 28800, - "n" => -3600, - "n. central asia" => 21600, - "nct" => 39600, - "ndt" => -5400, - "nepal" => 20700, - "new zealand" => 43200, - "newfoundland" => -12600, - "nfdt" => 43200, - "nft" => 39600, - "north asia" => 25200, - "north asia east" => 28800, - "novst" => 25200, - "novt" => 25200, - "npt" => 20700, - "nrt" => 43200, - "nst" => -9000, - "nt" => -39600, - "nut" => -39600, - "nzdt" => 46800, - "nzst" => 43200, - "nzt" => 43200, - "o" => -7200, - "omsst" => 25200, - "omst" => 21600, - "orat" => 18000, - "p" => -10800, - "pacific" => -28800, - "pacific sa" => -14400, - "pdt" => -25200, - "pet" => -18000, - "petst" => 43200, - "pett" => 43200, - "pgt" => 36000, - "phot" => 46800, - "pht" => 28800, - "pkt" => 18000, - "pmdt" => -7200, - "pmst" => -10800, - "pont" => 39600, - "pst" => -28800, - "pwt" => 32400, - "pyst" => -10800, - "q" => -14400, - "qyzt" => 21600, - "r" => -18000, - "ret" => 14400, - "romance" => 3600, - "rott" => -10800, - "russian" => 10800, - "s" => -21600, - "sa eastern" => -10800, - "sa pacific" => -18000, - "sa western" => -14400, - "sakt" => 39600, - "samoa" => -39600, - "samt" => 14400, - "sast" => 7200, - "sbt" => 39600, - "sct" => 14400, - "se asia" => 25200, - "sgt" => 28800, - "south africa" => 7200, - "sret" => 39600, - "sri lanka" => 21600, - "srt" => -10800, - "sst" => -39600, - "swt" => 3600, - "syot" => 10800, - "t" => -25200, - "taht" => -36000, - "taipei" => 28800, - "tasmania" => 36000, - "tft" => 18000, - "tjt" => 18000, - "tkt" => 46800, - "tlt" => 32400, - "tmt" => 18000, - "tokyo" => 32400, - "tonga" => 46800, - "tost" => 50400, - "tot" => 46800, - "trt" => 10800, - "tvt" => 43200, - "u" => -28800, - "ulast" => 32400, - "ulat" => 28800, - "us eastern" => -18000, - "us mountain" => -25200, - "ut" => 0, - "utc" => 0, - "uyst" => -7200, - "uyt" => -10800, - "uzt" => 18000, - "v" => -32400, - "vet" => -14400, - "vladivostok" => 36000, - "vlast" => 39600, - "vlat" => 36000, - "vost" => 21600, - "vut" => 39600, - "w" => -36000, - "w. australia" => 28800, - "w. central africa" => 3600, - "w. europe" => 3600, - "wadt" => 28800, - "wakt" => 43200, - "warst" => -10800, - "wast" => 7200, - "wat" => 3600, - "west" => 3600, - "west asia" => 18000, - "west pacific" => 36000, - "wet" => 0, - "wft" => 43200, - "wgst" => -3600, - "wgt" => -7200, - "wib" => 25200, - "wit" => 32400, - "wita" => 28800, - "wt" => 0, - "x" => -39600, - "y" => -43200, - "yakst" => 36000, - "yakt" => 32400, - "yakutsk" => 32400, - "yapt" => 36000, - "ydt" => -28800, - "yekst" => 21600, - "yekt" => 18000, - "yst" => -32400, - "z" => 0, - "zp4" => 14400, - "zp5" => 18000, - "zp6" => 21600, - # Multi-word timezone names from C's zonetab.list - "met dst" => 7200, - "mountain standard time" => -25200, - "mountain daylight time" => -21600, - "pacific standard time" => -28800, - "pacific daylight time" => -25200, - "eastern standard time" => -18000, - "eastern daylight time" => -14400, - "central standard time" => -21600, - "central daylight time" => -18000, - "atlantic standard time" => -14400, - "atlantic daylight time" => -10800, - "e. australia standard time" => 36000, - "cen. australia standard time" => 34200, - "w. australia standard time" => 28800, - "dateline standard time" => -43200, - "fiji standard time" => 43200, - "samoa standard time" => -39600, - "new zealand standard time" => 43200, - "taipei standard time" => 28800, - "tokyo standard time" => 32400, - "china standard time" => 28800, - "india standard time" => 19800, - "korea standard time" => 32400, - "singapore standard time" => 28800, - "north asia standard time" => 25200, - "north asia east standard time" => 28800, - "se asia standard time" => 25200, - "west asia standard time" => 18000, - "romance standard time" => 3600, - "russian standard time" => 10800, - "us eastern standard time" => -18000, - "us mountain standard time" => -25200, - "sa western standard time" => -14400, - "sa pacific standard time" => -18000, - "sa eastern standard time" => -10800, - "e. south america standard time" => -10800, - "greenland standard time" => -10800, - "mid-atlantic standard time" => -7200, - "azores standard time" => -3600, - "cape verde standard time" => -3600, - "gmt standard time" => 0, - "greenwich standard time" => 0, - "w. europe standard time" => 3600, - "central europe standard time" => 3600, - "central european standard time" => 3600, - "gtb standard time" => 7200, - "e. europe standard time" => 7200, - "egypt standard time" => 7200, - "south africa standard time" => 7200, - "fle standard time" => 7200, - "israel standard time" => 7200, - "arabian standard time" => 14400, - "arab standard time" => 10800, - "e. africa standard time" => 10800, - "iran standard time" => 12600, - "west pacific standard time" => 36000, - "aus central standard time" => 34200, - "aus eastern standard time" => 36000, - "central pacific standard time" => 39600, - "tasmania standard time" => 36000, - "canada central standard time" => -21600, - "mexico standard time" => -21600, - "mexico standard time 2" => -25200, - "central america standard time" => -21600, - "nepal standard time" => 20700, - "sri lanka standard time" => 21600, - "n. central asia standard time" => 21600, - "central asia standard time" => 21600, - "afghanistan standard time" => 16200, - "ekaterinburg standard time" => 18000, - "alaska standard time" => -32400, - "alaska daylight time" => -28800, - "hawaii standard time" => -36000, + "a" => 3600, + "acdt" => 37800, + "acst" => 34200, + "act" => -18000, + "acwst" => 31500, + "adt" => -10800, + "aedt" => 39600, + "aest" => 36000, + "afghanistan" => 16200, + "aft" => 16200, + "ahst" => -36000, + "akdt" => -28800, + "akst" => -32400, + "alaskan" => -32400, + "almt" => 21600, + "anast" => 43200, + "anat" => 43200, + "aoe" => -43200, + "aqtt" => 18000, + "arab" => 10800, + "arabian" => 14400, + "arabic" => 10800, + "art" => -10800, + "ast" => -14400, + "at" => -7200, + "atlantic" => -14400, + "aus central" => 34200, + "aus eastern" => 36000, + "awdt" => 32400, + "awst" => 28800, + "azores" => -3600, + "azost" => 0, + "azot" => -3600, + "azst" => 18000, + "azt" => 14400, + "b" => 7200, + "bnt" => 28800, + "bot" => -14400, + "brst" => -7200, + "brt" => -10800, + "bst" => 3600, + "bt" => 10800, + "btt" => 21600, + "c" => 10800, + "canada central" => -21600, + "cape verde" => -3600, + "cast" => 28800, + "cat" => 7200, + "caucasus" => 14400, + "cct" => 23400, + "cdt" => -18000, + "cen. australia" => 34200, + "central" => -21600, + "central america" => -21600, + "central asia" => 21600, + "central europe" => 3600, + "central european" => 3600, + "central pacific" => 39600, + "cest" => 7200, + "cet" => 3600, + "chadt" => 49500, + "chast" => 45900, + "china" => 28800, + "chost" => 32400, + "chot" => 28800, + "chst" => 36000, + "chut" => 36000, + "cidst" => -14400, + "cist" => -18000, + "ckt" => -36000, + "clst" => -10800, + "clt" => -14400, + "cot" => -18000, + "cst" => -21600, + "cvt" => -3600, + "cxt" => 25200, + "d" => 14400, + "dateline" => -43200, + "davt" => 25200, + "ddut" => 36000, + "e" => 18000, + "e. africa" => 10800, + "e. australia" => 36000, + "e. europe" => 7200, + "e. south america" => -10800, + "eadt" => 39600, + "easst" => -18000, + "east" => -21600, + "eastern" => -18000, + "eat" => 10800, + "ect" => -18000, + "edt" => -14400, + "eest" => 10800, + "eet" => 7200, + "egst" => 0, + "egt" => -3600, + "egypt" => 7200, + "ekaterinburg" => 18000, + "est" => -18000, + "f" => 21600, + "fet" => 10800, + "fiji" => 43200, + "fjst" => 46800, + "fjt" => 43200, + "fkst" => -10800, + "fkt" => -14400, + "fle" => 7200, + "fnt" => -7200, + "fst" => 7200, + "fwt" => 3600, + "g" => 25200, + "galt" => -21600, + "gamt" => -32400, + "get" => 14400, + "gft" => -10800, + "gilt" => 43200, + "gmt" => 0, + "greenland" => -10800, + "greenwich" => 0, + "gst" => 36000, + "gtb" => 7200, + "gyt" => -14400, + "h" => 28800, + "hadt" => -32400, + "hast" => -36000, + "hawaiian" => -36000, + "hdt" => -32400, + "hkt" => 28800, + "hovst" => 28800, + "hovt" => 25200, + "hst" => -36000, + "i" => 32400, + "ict" => 25200, + "idle" => 43200, + "idlw" => -43200, + "idt" => 10800, + "india" => 19800, + "iot" => 21600, + "iran" => 12600, + "irdt" => 16200, + "irkst" => 32400, + "irkt" => 28800, + "irst" => 12600, + "ist" => 19800, + "jerusalem" => 7200, + "jst" => 32400, + "k" => 36000, + "kgt" => 21600, + "korea" => 32400, + "kost" => 39600, + "krast" => 28800, + "krat" => 25200, + "kst" => 32400, + "kuyt" => 14400, + "l" => 39600, + "lhdt" => 39600, + "lhst" => 37800, + "lint" => 50400, + "m" => 43200, + "magst" => 43200, + "magt" => 39600, + "malay peninsula" => 28800, + "mart" => -30600, + "mawt" => 18000, + "mdt" => -21600, + "mest" => 7200, + "mesz" => 7200, + "met" => 3600, + "mewt" => 3600, + "mexico" => -21600, + "mez" => 3600, + "mht" => 43200, + "mid-atlantic" => -7200, + "mmt" => 23400, + "mountain" => -25200, + "msd" => 14400, + "msk" => 10800, + "mst" => -25200, + "mut" => 14400, + "mvt" => 18000, + "myanmar" => 23400, + "myt" => 28800, + "n" => -3600, + "n. central asia" => 21600, + "nct" => 39600, + "ndt" => -5400, + "nepal" => 20700, + "new zealand" => 43200, + "newfoundland" => -12600, + "nfdt" => 43200, + "nft" => 39600, + "north asia" => 25200, + "north asia east" => 28800, + "novst" => 25200, + "novt" => 25200, + "npt" => 20700, + "nrt" => 43200, + "nst" => -9000, + "nt" => -39600, + "nut" => -39600, + "nzdt" => 46800, + "nzst" => 43200, + "nzt" => 43200, + "o" => -7200, + "omsst" => 25200, + "omst" => 21600, + "orat" => 18000, + "p" => -10800, + "pacific" => -28800, + "pacific sa" => -14400, + "pdt" => -25200, + "pet" => -18000, + "petst" => 43200, + "pett" => 43200, + "pgt" => 36000, + "phot" => 46800, + "pht" => 28800, + "pkt" => 18000, + "pmdt" => -7200, + "pmst" => -10800, + "pont" => 39600, + "pst" => -28800, + "pwt" => 32400, + "pyst" => -10800, + "q" => -14400, + "qyzt" => 21600, + "r" => -18000, + "ret" => 14400, + "romance" => 3600, + "rott" => -10800, + "russian" => 10800, + "s" => -21600, + "sa eastern" => -10800, + "sa pacific" => -18000, + "sa western" => -14400, + "sakt" => 39600, + "samoa" => -39600, + "samt" => 14400, + "sast" => 7200, + "sbt" => 39600, + "sct" => 14400, + "se asia" => 25200, + "sgt" => 28800, + "south africa" => 7200, + "sret" => 39600, + "sri lanka" => 21600, + "srt" => -10800, + "sst" => -39600, + "swt" => 3600, + "syot" => 10800, + "t" => -25200, + "taht" => -36000, + "taipei" => 28800, + "tasmania" => 36000, + "tft" => 18000, + "tjt" => 18000, + "tkt" => 46800, + "tlt" => 32400, + "tmt" => 18000, + "tokyo" => 32400, + "tonga" => 46800, + "tost" => 50400, + "tot" => 46800, + "trt" => 10800, + "tvt" => 43200, + "u" => -28800, + "ulast" => 32400, + "ulat" => 28800, + "us eastern" => -18000, + "us mountain" => -25200, + "ut" => 0, + "utc" => 0, + "uyst" => -7200, + "uyt" => -10800, + "uzt" => 18000, + "v" => -32400, + "vet" => -14400, + "vladivostok" => 36000, + "vlast" => 39600, + "vlat" => 36000, + "vost" => 21600, + "vut" => 39600, + "w" => -36000, + "w. australia" => 28800, + "w. central africa" => 3600, + "w. europe" => 3600, + "wadt" => 28800, + "wakt" => 43200, + "warst" => -10800, + "wast" => 7200, + "wat" => 3600, + "west" => 3600, + "west asia" => 18000, + "west pacific" => 36000, + "wet" => 0, + "wft" => 43200, + "wgst" => -3600, + "wgt" => -7200, + "wib" => 25200, + "wit" => 32400, + "wita" => 28800, + "wt" => 0, + "x" => -39600, + "y" => -43200, + "yakst" => 36000, + "yakt" => 32400, + "yakutsk" => 32400, + "yapt" => 36000, + "ydt" => -28800, + "yekst" => 21600, + "yekt" => 18000, + "yst" => -32400, + "z" => 0, + "zp4" => 14400, + "zp5" => 18000, + "zp6" => 21600, }.freeze end From 2b938aa228d14cde20c90a6cf03bb29f3a863442 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 2 Mar 2026 02:20:56 +0900 Subject: [PATCH 007/144] Remove redundant .encode(Encoding::US_ASCII).freeze from constants.rb The file already has `# encoding: US-ASCII` magic comment, which makes string literals US-ASCII by default. Additionally, `# frozen_string_literal: true` makes .freeze unnecessary for string literals. - Remove .encode(Encoding::US_ASCII).freeze from MONTH_DAY_SUFFIX (keep .freeze since format() returns a new mutable string) - Remove .encode(Encoding::US_ASCII).freeze from DEFAULT_STRFTIME_FMT - Remove .encode(Encoding::US_ASCII).freeze from YMD_FMT --- lib/date/constants.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index c9333b6a..c2b9313a 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -101,17 +101,17 @@ class Date MONTH_DAY_SUFFIX = Array.new(13) { |m| Array.new(32) { |d| next nil if m == 0 || d == 0 - format('-%02d-%02d', m, d).encode(Encoding::US_ASCII).freeze + format('-%02d-%02d', m, d).freeze }.freeze }.freeze private_constant :MONTH_DAY_SUFFIX # === String formatting (from strftime.rb) === - DEFAULT_STRFTIME_FMT = '%F'.encode(Encoding::US_ASCII).freeze + DEFAULT_STRFTIME_FMT = '%F' private_constant :DEFAULT_STRFTIME_FMT - YMD_FMT = '%Y-%m-%d'.encode(Encoding::US_ASCII).freeze + YMD_FMT = '%Y-%m-%d' private_constant :YMD_FMT # Locale-independent month/day name tables (same as C ext) From fb3743926ed83bef4cc928f6d64989721e5327a1 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 2 Mar 2026 10:39:04 +0900 Subject: [PATCH 008/144] Optimize Date.new by delegating to Date.civil directly Skip Class#new -> allocate -> initialize overhead by defining Date.new as a class method that delegates to Date.civil. Also replace rescue-based type guard with direct Integer === checks to eliminate rescue frame cost. Add DateTime.new override to prevent infinite recursion from inheritance. Performance comparison (Date.new): | Method | C ext (i/s) | Pure Ruby Before (i/s) | Pure Ruby After (i/s) | vs C ext | |------------|---------------|------------------------|-----------------------|----------| | Date.new | 4,648,499 | 1,531,119 (32.9%) | 2,011,298 (43.3%) | 43.3% | | Date.civil | 4,648,499 | 2,137,457 (46.0%) | 2,118,545 (45.6%) | 45.6% | --- lib/date/core.rb | 155 +++++++++++++++++++++++-------------------- lib/date/datetime.rb | 19 ++++-- lib/date/parse.rb | 4 +- lib/date/strftime.rb | 34 +++++----- lib/date/strptime.rb | 12 ++-- lib/date/time.rb | 2 +- 6 files changed, 122 insertions(+), 104 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index e625ddd2..886a7c02 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -12,42 +12,46 @@ class Date class << self # Same as Date.new. def civil(year = -4712, month = 1, day = 1, start = DEFAULT_SG) - unless (Integer === (year + month + day) rescue false) && month >= 1 && month <= 12 - return new(year, month, day, start) - end - if day >= 1 && day <= 28 - gy = month > 2 ? year : year - 1 - gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[month] + day - a = gy / 100 - jd_julian = gjd_base - 1524 - gjd = jd_julian + 2 - a + a / 4 - obj = allocate - obj.__send__(:_init_from_jd, gjd >= start ? gjd : jd_julian, start) - return obj - elsif day >= -31 - dim = if month == 2 - if start == Float::INFINITY - year % 4 == 0 ? 29 : 28 - else - (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 29 : 28 - end - else - DAYS_IN_MONTH_GREGORIAN[month] - end - d = day < 0 ? day + dim + 1 : day - if d >= 1 && d <= dim + if Integer === year && Integer === month && Integer === day && month >= 1 && month <= 12 + if day >= 1 && day <= 28 gy = month > 2 ? year : year - 1 - gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[month] + d + gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[month] + day a = gy / 100 jd_julian = gjd_base - 1524 gjd = jd_julian + 2 - a + a / 4 obj = allocate - obj.__send__(:_init_from_jd, gjd >= start ? gjd : jd_julian, start) + obj.__send__(:init_from_jd, gjd >= start ? gjd : jd_julian, start) return obj + elsif day >= -31 + dim = if month == 2 + if start == Float::INFINITY + year % 4 == 0 ? 29 : 28 + else + (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 29 : 28 + end + else + DAYS_IN_MONTH_GREGORIAN[month] + end + d = day < 0 ? day + dim + 1 : day + if d >= 1 && d <= dim + gy = month > 2 ? year : year - 1 + gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[month] + d + a = gy / 100 + jd_julian = gjd_base - 1524 + gjd = jd_julian + 2 - a + a / 4 + obj = allocate + obj.__send__(:init_from_jd, gjd >= start ? gjd : jd_julian, start) + return obj + end end end - new(year, month, day, start) + civil_fallback(year, month, day, start) + end + + def new(year = -4712, month = 1, day = 1, start = DEFAULT_SG) + civil(year, month, day, start) end + # call-seq: # Date.valid_civil?(year, month, mday, start = Date::ITALY) -> true or false # @@ -94,7 +98,7 @@ def valid_civil?(year, month, day, start = DEFAULT_SG) def jd(jd = 0, start = DEFAULT_SG) jd = Integer(jd) obj = allocate - obj.__send__(:_init_from_jd, jd, start) + obj.__send__(:init_from_jd, jd, start) obj end @@ -180,14 +184,14 @@ def ordinal(year = -4712, yday = 1, start = DEFAULT_SG) gjd = gjd_base - 1524 + 2 - a + a / 4 jd1 = gjd >= start ? gjd : gjd_base - 1524 obj = allocate - obj.__send__(:_init_from_jd, jd1 + yday - 1, start) + obj.__send__(:init_from_jd, jd1 + yday - 1, start) return obj end year = Integer(year) yday = Integer(yday) jd = internal_valid_ordinal?(year, yday, start) raise Date::Error, "invalid date" unless jd - _new_from_jd(jd, start) + new_from_jd(jd, start) end # call-seq: @@ -263,7 +267,7 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = DEFAULT_SG) mon_wk1 = jd_jan4 - (wday_jan4 == 0 ? 6 : wday_jan4 - 1) jd = mon_wk1 + (cweek - 1) * 7 + (cwday - 1) obj = allocate - obj.__send__(:_init_from_jd, jd, start) + obj.__send__(:init_from_jd, jd, start) return obj end cwyear = Integer(cwyear) @@ -271,7 +275,7 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = DEFAULT_SG) cwday = Integer(cwday) jd = internal_valid_commercial?(cwyear, cweek, cwday, start) raise Date::Error, "invalid date" unless jd - _new_from_jd(jd, start) + new_from_jd(jd, start) end # call-seq: @@ -307,7 +311,7 @@ def weeknum(year = -4712, week = 0, wday = 1, wstart = 0, start = DEFAULT_SG) # Verify the resulting date is in the same year (week must be valid) y2, = jd_to_civil(jd, start) raise Date::Error, "invalid date" if y2 != year - _new_from_jd(jd, start) + new_from_jd(jd, start) end # call-seq: @@ -324,7 +328,7 @@ def nth_kday(year = -4712, month = 1, n = 1, k = 1, start = DEFAULT_SG) # Verify the result is in the same month y2, m2, = jd_to_civil(jd, start) raise Date::Error, "invalid date" if y2 != year || m2 != month - _new_from_jd(jd, start) + new_from_jd(jd, start) end # call-seq: @@ -339,7 +343,7 @@ def nth_kday(year = -4712, month = 1, n = 1, k = 1, start = DEFAULT_SG) def today(start = DEFAULT_SG) t = Time.now jd = civil_to_jd(t.year, t.mon, t.mday, start) - _new_from_jd(jd, start) + new_from_jd(jd, start) end # :nodoc: @@ -358,12 +362,21 @@ def new!(ajd = 0, of = 0, sg = DEFAULT_SG) jd = raw_jd.floor df = raw_jd - jd obj = allocate - obj.__send__(:_init_from_jd, jd, sg, df == 0 ? nil : df) + obj.__send__(:init_from_jd, jd, sg, df == 0 ? nil : df) obj end private + def civil_fallback(year, month, day, start) + year = Integer(year) + month = Integer(month) + day = Integer(day) + jd = internal_valid_civil?(year, month, day, start) + raise Date::Error, "invalid date" unless jd + new_from_jd(jd, start) + end + # --------------------------------------------------------------------------- # Internal calendar arithmetic (pure Ruby, no C dependency) # --------------------------------------------------------------------------- @@ -602,14 +615,14 @@ def internal_valid_commercial?(y, w, d, sg) # --------------------------------------------------------------------------- # Build a Date from a Julian Day Number (integer part), start, and optional day fraction. - def _new_from_jd(jd, sg, df = nil) + def new_from_jd(jd, sg, df = nil) obj = allocate - obj.__send__(:_init_from_jd, jd, sg, df) + obj.__send__(:init_from_jd, jd, sg, df) obj end # Parse offset string like "+09:00", "-07:30", "Z" to seconds. - def _offset_str_to_sec(str) + def offset_str_to_sec(str) case str when 'Z', 'z', 'UTC', 'GMT' 0 @@ -696,7 +709,7 @@ def initialize(year = -4712, month = 1, day = 1, start = DEFAULT_SG) day = Integer(day) jd = self.class.__send__(:internal_valid_civil?, year, month, day, start) raise Date::Error, "invalid date" unless jd - _init_from_jd(jd, start) + init_from_jd(jd, start) end # --------------------------------------------------------------------------- @@ -712,7 +725,7 @@ def initialize(year = -4712, month = 1, day = 1, start = DEFAULT_SG) # (Date.new(1, 1, 1) - 1).year # => 0 # def year - _civil unless @year + internal_civil unless @year @year end @@ -724,7 +737,7 @@ def year # Date.new(2001, 2, 3).mon # => 2 # def month - _civil unless @year + internal_civil unless @year @month end alias mon month @@ -737,7 +750,7 @@ def month # Date.new(2001, 2, 3).mday # => 3 # def day - _civil unless @year + internal_civil unless @year @day end alias mday day @@ -838,7 +851,7 @@ def ld # def yday return @yday if @yday - _civil unless @year + internal_civil unless @year # inline civil_to_jd(@year, 1, 1, @sg): month=1 (<= 2 so y-=1), day=1 yy = @year - 1 gjd_base = (1461 * (yy + 4716)) / 4 + 429 # GJD_MONTH_OFFSET[1](=428) + 1 @@ -884,7 +897,7 @@ def cwday # Date.new(2001, 2, 3).cweek # => 5 # def cweek - @cweek || _compute_commercial[1] + @cweek || compute_commercial[1] end # call-seq: @@ -897,7 +910,7 @@ def cweek # Date.new(2000, 1, 1).cwyear # => 1999 # def cwyear - @cwyear || _compute_commercial[0] + @cwyear || compute_commercial[0] end # call-seq: @@ -920,7 +933,7 @@ def day_fraction # Date.new(2001).leap? # => false # def leap? - _civil unless @year + internal_civil unless @year if @jd < @sg # julian? @year % 4 == 0 else @@ -1236,7 +1249,7 @@ def +(other) obj.instance_variable_set(:@sg, @sg) obj else - self.class.__send__(:_new_from_jd, @jd + other, @sg, @df) + self.class.__send__(:new_from_jd, @jd + other, @sg, @df) end when Numeric r = other.to_r @@ -1244,7 +1257,7 @@ def +(other) total = r + (@df || 0) days = total.floor frac = total - days - self.class.__send__(:_new_from_jd, @jd + days, @sg, frac == 0 ? nil : frac) + self.class.__send__(:new_from_jd, @jd + days, @sg, frac == 0 ? nil : frac) else raise TypeError, "expected numeric" end @@ -1278,7 +1291,7 @@ def -(other) obj.instance_variable_set(:@sg, @sg) obj else - self.class.__send__(:_new_from_jd, @jd - other, @sg, @df) + self.class.__send__(:new_from_jd, @jd - other, @sg, @df) end when Numeric r = other.to_r @@ -1286,7 +1299,7 @@ def -(other) total = (@df || 0) - r days = total.floor frac = total - days - self.class.__send__(:_new_from_jd, @jd + days, @sg, frac == 0 ? nil : frac) + self.class.__send__(:new_from_jd, @jd + days, @sg, frac == 0 ? nil : frac) else raise TypeError, "expected numeric" end @@ -1318,7 +1331,7 @@ def -(other) # d2 = d1 >> -1 # => # # def >>(n) - _civil unless @year + internal_civil unless @year m2 = @month + n.to_i y2 = @year + (m2 - 1).div(12) m2 = (m2 - 1) % 12 + 1 @@ -1340,7 +1353,7 @@ def >>(n) a = yy / 100 gjd = gjd_base - 1524 + 2 - a + a / 4 jd2 = gjd >= @sg ? gjd : gjd_base - 1524 - # inline _new_from_jd + # inline new_from_jd obj = self.class.allocate obj.instance_variable_set(:@jd, jd2) obj.instance_variable_set(:@sg, @sg) @@ -1638,22 +1651,22 @@ def marshal_load(array) # Format 1.4/1.6: [jd_like, sg_or_bool] jd_like, sg_or_bool = array sg = sg_or_bool == true ? GREGORIAN : (sg_or_bool == false ? JULIAN : sg_or_bool.to_f) - _init_from_jd(jd_like.to_i, sg) + init_from_jd(jd_like.to_i, sg) when 3 # Format 1.8: [ajd, of, sg] ajd, _of, sg = array raw_jd = ajd + Rational(1, 2) jd = raw_jd.floor df = raw_jd - jd - _init_from_jd(jd, sg, df == 0 ? nil : df) + init_from_jd(jd, sg, df == 0 ? nil : df) when 6 # Current format: [nth, jd, df, sf, of, sg] _nth, jd, df, sf, _of, sg = array if df != 0 || sf != 0 day_frac = (Rational(df) + sf) / 86400 - _init_from_jd(jd, sg, day_frac) + init_from_jd(jd, sg, day_frac) else - _init_from_jd(jd, sg) + init_from_jd(jd, sg) end else raise TypeError, "invalid marshal data" @@ -1697,20 +1710,20 @@ def deconstruct_keys(keys) if keys.size == 1 case keys[0] when :year - _civil unless @year + internal_civil unless @year { year: @year } when :month - _civil unless @year + internal_civil unless @year { month: @month } when :day - _civil unless @year + internal_civil unless @year { day: @day } when :wday then { wday: (@jd + 1) % 7 } when :yday then { yday: yday } else {} end else - _civil unless @year + internal_civil unless @year h = {} keys.each do |k| case k @@ -1724,7 +1737,7 @@ def deconstruct_keys(keys) h end else - _civil unless @year + internal_civil unless @year { year: @year, month: @month, day: @day, wday: (@jd + 1) % 7, yday: yday } end end @@ -1745,7 +1758,7 @@ def deconstruct_keys(keys) # See {asctime}[https://linux.die.net/man/3/asctime]. # def asctime - _civil unless @year + internal_civil unless @year d = @day d_s = d < 10 ? " #{d}" : d.to_s y = @year @@ -1794,7 +1807,7 @@ def rfc3339 # Date.new(2001, 2, 3).rfc2822 # => "Sat, 3 Feb 2001 00:00:00 +0000" # def rfc2822 - _civil unless @year + internal_civil unless @year w = (@jd + 1) % 7 y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) @@ -1815,7 +1828,7 @@ def rfc2822 # Date.new(2001, 2, 3).httpdate # => "Sat, 03 Feb 2001 00:00:00 GMT" # def httpdate - _civil unless @year + internal_civil unless @year w = (@jd + 1) % 7 y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) @@ -1835,7 +1848,7 @@ def httpdate # Date.new(2001, 2, 3).jisx0301 # => "H13.02.03" # def jisx0301 - _civil unless @year + internal_civil unless @year jd = @jd m = @month d = @day @@ -1865,7 +1878,7 @@ def jisx0301 # Date.new(2001, 2, 3).to_s # => "2001-02-03" # def to_s - _civil + internal_civil suffix = MONTH_DAY_SUFFIX[@month][@day] y = @year if y >= 1000 @@ -1893,7 +1906,7 @@ def inspect # override def freeze - _civil # compute and cache civil date before freezing + internal_civil # compute and cache civil date before freezing super end @@ -1903,13 +1916,13 @@ def freeze private - def _init_from_jd(jd, sg, df = nil) + def init_from_jd(jd, sg, df = nil) @jd = jd @sg = sg @df = df end - def _civil + def internal_civil return if @year jd = @jd if @sg == Float::INFINITY # always Julian @@ -1932,7 +1945,7 @@ def _civil end # Inline jd_to_commercial: compute and cache cwyear/cweek - def _compute_commercial + def compute_commercial jd = @jd wday_val = (jd + 1) % 7 cwday_val = wday_val == 0 ? 7 : wday_val diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index aa68c08c..3bf636d7 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -356,13 +356,13 @@ def deconstruct_keys(keys) if keys.size == 1 case keys[0] when :year - _civil unless @year + internal_civil unless @year { year: @year } when :month - _civil unless @year + internal_civil unless @year { month: @month } when :day - _civil unless @year + internal_civil unless @year { day: @day } when :wday then { wday: (@jd + 1) % 7 } when :yday then { yday: yday } @@ -374,7 +374,7 @@ def deconstruct_keys(keys) else {} end else - _civil unless @year + internal_civil unless @year h = {} keys.each do |k| case k @@ -393,7 +393,7 @@ def deconstruct_keys(keys) h end else - _civil unless @year + internal_civil unless @year { year: @year, month: @month, day: @day, wday: (@jd + 1) % 7, yday: yday, hour: @hour, min: @min, sec: @sec_i, sec_fraction: @sec_frac, zone: _of2str(@of) } end @@ -476,7 +476,7 @@ def marshal_load(array) # # Returns a Date object which denotes self. def to_date - Date.__send__(:_new_from_jd, @jd, @sg) + Date.__send__(:new_from_jd, @jd, @sg) end # call-seq: @@ -505,6 +505,11 @@ def to_time # --------------------------------------------------------------------------- class << self + def new(year = -4712, month = 1, day = 1, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) + instance = allocate + instance.__send__(:initialize, year, month, day, hour, minute, second, offset, start) + instance + end alias_method :civil, :new undef_method :today @@ -859,7 +864,7 @@ def _dt_new_by_frags(hash, sg) # rubocop:disable Metrics/MethodLength def _parse_of(offset) case offset when String - Date.__send__(:_offset_str_to_sec, offset) + Date.__send__(:offset_str_to_sec, offset) when Rational (offset * 86400).to_i when Numeric diff --git a/lib/date/parse.rb b/lib/date/parse.rb index 682f6b40..0f05cd75 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -1688,11 +1688,11 @@ def fast_new_date(hash, sg) if y >= 1583 && m >= 1 && m <= 12 && d >= 1 && d <= 28 && sg <= 2299161 gy = m <= 2 ? y - 1 : y a = gy / 100 - _new_from_jd((1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[m] + d - 1524 + 2 - a + a / 4, sg) + new_from_jd((1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[m] + d - 1524 + 2 - a + a / 4, sg) else jd = internal_valid_civil?(y, m, d, sg) raise Error, 'invalid date' if jd.nil? - _new_from_jd(jd, sg) + new_from_jd(jd, sg) end else _new_by_frags(hash, sg) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index d86ad7a9..681854c2 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -14,12 +14,12 @@ class Date # {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]. def strftime(format = DEFAULT_STRFTIME_FMT) if format.equal?(DEFAULT_STRFTIME_FMT) - _civil unless @year + internal_civil unless @year return _fast_ymd.force_encoding(Encoding::US_ASCII) end fmt = format.to_str if fmt == YMD_FMT - _civil unless @year + internal_civil unless @year return _fast_ymd.force_encoding(Encoding::US_ASCII) end internal_strftime(fmt).force_encoding(fmt.encoding) @@ -31,15 +31,15 @@ def internal_strftime(fmt) # rubocop:disable Metrics/MethodLength,Metrics/Cyclom # Fast path for common format strings (whole-string match) case fmt when '%Y-%m-%d', '%F' - _civil unless @year + internal_civil unless @year return _fast_ymd when '%H:%M:%S', '%T', '%X' return instance_of?(Date) ? +'00:00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}" when '%m/%d/%y', '%D', '%x' - _civil unless @year + internal_civil unless @year return "#{PAD2[@month]}/#{PAD2[@day]}/#{PAD2[@year.abs % 100]}" when '%Y-%m-%dT%H:%M:%S%z' - _civil unless @year + internal_civil unless @year if instance_of?(Date) return _fast_ymd << 'T00:00:00+0000' else @@ -49,10 +49,10 @@ def internal_strftime(fmt) # rubocop:disable Metrics/MethodLength,Metrics/Cyclom return "#{_fast_ymd}T#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}#{sign}#{PAD2[abs / 3600]}#{PAD2[(abs % 3600) / 60]}" end when '%a %b %e %H:%M:%S %Y', '%c' - _civil unless @year + internal_civil unless @year return _fmt_asctime_str when '%A, %B %d, %Y' - _civil unless @year + internal_civil unless @year w = (@jd + 1) % 7 y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) @@ -194,7 +194,7 @@ def _fmt_asctime_str def _fast_spec(spec) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity case spec when 89 # 'Y' - _civil unless @year + internal_civil unless @year y = @year if y >= 1000 s = y.to_s @@ -206,13 +206,13 @@ def _fast_spec(spec) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticCo format('-%04d', -y) end when 109 # 'm' - _civil unless @year + internal_civil unless @year PAD2[@month] when 100 # 'd' - _civil unless @year + internal_civil unless @year PAD2[@day] when 101 # 'e' - _civil unless @year + internal_civil unless @year d = @day d < 10 ? " #{d}" : d.to_s when 72 # 'H' @@ -226,10 +226,10 @@ def _fast_spec(spec) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticCo when 65 # 'A' STRFTIME_DAYS_FULL[(@jd + 1) % 7] when 98, 104 # 'b', 'h' - _civil unless @year + internal_civil unless @year STRFTIME_MONTHS_ABBR[@month] when 66 # 'B' - _civil unless @year + internal_civil unless @year STRFTIME_MONTHS_FULL[@month] when 112 # 'p' internal_hour < 12 ? 'AM' : 'PM' @@ -255,7 +255,7 @@ def _fast_spec(spec) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticCo when 117 # 'u' cwday.to_s when 121 # 'y' - _civil unless @year + internal_civil unless @year PAD2[@year.abs % 100] when 90 # 'Z' _zone_str @@ -268,15 +268,15 @@ def _fast_spec(spec) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticCo ((@jd - 2440588) * 86400 - _of_seconds + internal_hour * 3600 + internal_min * 60 + internal_sec).to_s # Composite specs — inline expansion when 99 # 'c' - _civil unless @year + internal_civil unless @year _fmt_asctime_str when 70 # 'F' - _civil unless @year + internal_civil unless @year _fast_ymd when 84, 88 # 'T', 'X' instance_of?(Date) ? '00:00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}" when 68, 120 # 'D', 'x' - _civil unless @year + internal_civil unless @year "#{PAD2[@month]}/#{PAD2[@day]}/#{PAD2[@year.abs % 100]}" when 82 # 'R' instance_of?(Date) ? '00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}" diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index d343ff52..3a482be0 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -82,7 +82,7 @@ def strptime(string = JULIAN_EPOCH_DATE, format = '%F', start = DEFAULT_SG) (year = hash[:year]) && (mon = hash[:mon]) && (mday = hash[:mday]) jd = internal_valid_civil?(year, mon, mday, start) raise Error, 'invalid date' if jd.nil? - return _new_from_jd(jd, start) + return new_from_jd(jd, start) end _new_by_frags(hash, start) end @@ -881,10 +881,10 @@ def _strptime_ymd_to_date(str, sg) # rubocop:disable Metrics/MethodLength a = gy / 100 gjd = gjd_base - 1524 + 2 - a + a / 4 jd = gjd >= sg ? gjd : gjd_base - 1524 - return _new_from_jd(jd, sg) + return new_from_jd(jd, sg) else jd = internal_valid_civil?(year, mon, mday, sg) - return jd ? _new_from_jd(jd, sg) : nil + return jd ? new_from_jd(jd, sg) : nil end end return nil @@ -958,7 +958,7 @@ def _strptime_ymd_to_date(str, sg) # rubocop:disable Metrics/MethodLength jd = internal_valid_civil?(year, mon, mday, sg) return nil unless jd end - _new_from_jd(jd, sg) + new_from_jd(jd, sg) end # Fast path for "%a %b %d %Y" format (complex benchmark). @@ -1149,7 +1149,7 @@ def _strptime_abdy_to_date(str, sg) # rubocop:disable Metrics/MethodLength,Metri jd = internal_valid_civil?(year, mon, mday, sg) return nil unless jd end - _new_from_jd(jd, sg) + new_from_jd(jd, sg) end # Parse zone from string at position si; update hash[:zone] and hash[:offset]. @@ -1486,7 +1486,7 @@ def _new_by_frags(hash, sg) hash = _sp_complete_frags(Date, hash) jd = _sp_valid_date_frags_p(hash, sg) raise Error, 'invalid date' if jd.nil? - _new_from_jd(jd, sg) + new_from_jd(jd, sg) end end end diff --git a/lib/date/time.rb b/lib/date/time.rb index ee8ef7c3..cc463b5c 100644 --- a/lib/date/time.rb +++ b/lib/date/time.rb @@ -15,7 +15,7 @@ def to_time # Returns a Date object which denotes self. def to_date jd = Date.__send__(:gregorian_to_jd, year, mon, mday) - Date.__send__(:_new_from_jd, jd, Date::ITALY) + Date.__send__(:new_from_jd, jd, Date::ITALY) end unless method_defined?(:to_date) # call-seq: From a65aca656dfbef94af8ed97ec05a17c5183fda82 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 3 Mar 2026 16:21:31 +0900 Subject: [PATCH 009/144] Refactor getbyte to StringScanner, and optimize strptime Replace all getbyte-based byte manipulation with StringScanner and regex patterns across parse.rb, strftime.rb, and strptime.rb for improved readability and maintainability. Key changes: - Replace getbyte loops with StringScanner#scan/skip and regex patterns - Optimize strptime fast paths using match? + byteslice instead of StringScanner allocation - Add 17 pre-compiled regex constants for YJIT inline cache efficiency - Inline sp_digits_sc and sp_num_p? helper methods - Replace hash[:_fail] error propagation with throw/catch(:sp_fail) - Extract compute_3key into lib/date/shared.rb Performance (iterations/s, pure Ruby + YJIT vs C ext + YJIT): | Benchmark | C ext+YJIT | pure Ruby+YJIT | Ratio | |------------------------|-------------|-----------------|-------| | Date._strptime | 2,263,815 | 1,284,553 | 57% | | Date.strptime | 1,156,519 | 1,189,801 | 103% | | Date.strptime(complex) | 905,983 | 424,281 | 47% | --- lib/date.rb | 2 + lib/date/constants.rb | 42 +- lib/date/datetime.rb | 14 +- lib/date/parse.rb | 358 ++++--------- lib/date/shared.rb | 13 + lib/date/strftime.rb | 239 ++++----- lib/date/strptime.rb | 1189 ++++++++++++----------------------------- 7 files changed, 555 insertions(+), 1302 deletions(-) create mode 100644 lib/date/shared.rb diff --git a/lib/date.rb b/lib/date.rb index 1bb5da3f..d5869a61 100644 --- a/lib/date.rb +++ b/lib/date.rb @@ -2,10 +2,12 @@ # date.rb: Written by Tadayoshi Funaba 1998-2011 require 'timeout' +require 'strscan' if RUBY_VERSION >= "3.3" require_relative "date/version" require_relative "date/constants" + require_relative "date/shared" require_relative "date/core" require_relative "date/strftime" require_relative "date/parse" diff --git a/lib/date/constants.rb b/lib/date/constants.rb index c2b9313a..707018ed 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -18,18 +18,6 @@ class Date DEFAULT_SG = ITALY private_constant :DEFAULT_SG - # Pre-computed lowercase byte arrays for fast case-insensitive name matching in strptime - ABBR_DAY_LOWER_BYTES = ABBR_DAYNAMES.map { |n| n.downcase.bytes.freeze }.freeze - DAY_LOWER_BYTES = DAYNAMES.map { |n| n.downcase.bytes.freeze }.freeze - ABBR_MONTH_LOWER_BYTES = ABBR_MONTHNAMES.each_with_object([]) { |n, a| - a << (n ? n.downcase.bytes.freeze : nil) - }.freeze - MONTH_LOWER_BYTES = MONTHNAMES.each_with_object([]) { |n, a| - a << (n ? n.downcase.bytes.freeze : nil) - }.freeze - private_constant :ABBR_DAY_LOWER_BYTES, :DAY_LOWER_BYTES, - :ABBR_MONTH_LOWER_BYTES, :MONTH_LOWER_BYTES - # 3-byte integer key lookup tables for O(1) abbreviated name matching. # Key = (byte0_lower << 16) | (byte1_lower << 8) | byte2_lower # Value = [index, full_name_length] @@ -54,6 +42,12 @@ class Date ABBR_DAY_NUM = ABBR_DAYNAMES.each_with_index.to_h { |n, i| [n.downcase, i] }.freeze private_constant :ABBR_MONTH_NUM, :ABBR_DAY_NUM + # Lowercase full name strings for StringScanner-based head matching + DAY_LOWER_STRS = DAYNAMES.map { |n| n.downcase.freeze }.freeze + MONTH_LOWER_STRS = MONTHNAMES.map { |n| n&.downcase&.freeze }.freeze + private_constant :DAY_LOWER_STRS, :MONTH_LOWER_STRS + + JULIAN_EPOCH_DATE = '-4712-01-01'.freeze JULIAN_EPOCH_DATETIME = '-4712-01-01T00:00:00+00:00'.freeze JULIAN_EPOCH_DATETIME_RFC2822 = 'Mon, 1 Jan -4712 00:00:00 +0000'.freeze @@ -340,10 +334,6 @@ class Date # === Strptime constants (from strptime.rb) === - # Specs that produce numeric output (used by NUM_PATTERN_P lookahead) - STRPTIME_NUMERIC_SPECS = 'CDdeFGgHIjkLlMmNQRrSsTUuVvWwXxYy'.freeze - private_constant :STRPTIME_NUMERIC_SPECS - # Zone pattern matching: numeric offsets and named zones # Matches (case-insensitive): # - Numeric: +/-HHMM, +/-HH:MM, +/-HH:MM:SS, +/-HH,frac, +/-HH.frac @@ -371,24 +361,4 @@ class Date [nil, [:year, :wnum1, :cwday, :hour, :min, :sec]], ].freeze private_constant :COMPLETE_FRAGS_TAB - - # O(1) boolean lookup table for numeric specs (used by _sp_num_p_b?) - # Includes both STRPTIME_NUMERIC_SPECS chars and digits '0'..'9' - STRPTIME_NUMERIC_SPEC_SET = Array.new(256, false).tap { |a| - STRPTIME_NUMERIC_SPECS.each_byte { |b| a[b] = true } - 48.upto(57) { |b| a[b] = true } # '0'..'9' - }.freeze - private_constant :STRPTIME_NUMERIC_SPEC_SET - - # O(1) boolean lookup table for E-modifier valid specs - STRPTIME_E_VALID_SET = Array.new(256, false).tap { |a| - 'cCxXyY'.each_byte { |b| a[b] = true } - }.freeze - private_constant :STRPTIME_E_VALID_SET - - # O(1) boolean lookup table for O-modifier valid specs - STRPTIME_O_VALID_SET = Array.new(256, false).tap { |a| - 'deHImMSuUVwWy'.each_byte { |b| a[b] = true } - }.freeze - private_constant :STRPTIME_O_VALID_SET end diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 3bf636d7..fe990943 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -839,12 +839,12 @@ def jisx0301(string = '-4712-01-01T00:00:00+00:00', start = Date::ITALY, limit: # Create a DateTime object from parsed fragment hash. # Uses the same fragment rewrite/complete/validate logic as Date._new_by_frags # but additionally extracts time components (hour, min, sec, offset, sec_fraction). - def _dt_new_by_frags(hash, sg) # rubocop:disable Metrics/MethodLength + def _dt_new_by_frags(hash, sg) raise Date::Error, 'invalid date' if hash.nil? - hash = _sp_rewrite_frags(hash) + hash = sp_rewrite_frags(hash) orig_sec = hash[:sec] - hash = _sp_complete_frags(DateTime, hash) - jd = _sp_valid_date_frags_p(hash, sg) + hash = sp_complete_frags(DateTime, hash) + jd = sp_valid_date_frags_p(hash, sg) raise Date::Error, 'invalid date' if jd.nil? h = hash[:hour] || 0 @@ -904,15 +904,15 @@ def internal_sec @sec_i end - def _sec_frac + def sec_frac @sec_frac end - def _of_seconds + def of_seconds @of end - def _zone_str + def zone_str _of2str(@of) end diff --git a/lib/date/parse.rb b/lib/date/parse.rb index 0f05cd75..72f55646 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -35,56 +35,21 @@ def _rfc3339(string, limit: 128) # Fast path: YYYY-MM-DDTHH:MM:SS+HH:MM (25 bytes) or YYYY-MM-DDTHH:MM:SSZ (20 bytes) len = string.length if len == 25 || len == 20 - b0 = string.getbyte(0) - if b0 >= 48 && b0 <= 57 && - string.getbyte(4) == 45 && string.getbyte(7) == 45 && - (string.getbyte(10) | 32) == 116 && # T or t - string.getbyte(13) == 58 && string.getbyte(16) == 58 - b1 = string.getbyte(1) - b2 = string.getbyte(2) - b3 = string.getbyte(3) - b5 = string.getbyte(5) - b6 = string.getbyte(6) - b8 = string.getbyte(8) - b9 = string.getbyte(9) - b11 = string.getbyte(11) - b12 = string.getbyte(12) - b14 = string.getbyte(14) - b15 = string.getbyte(15) - b17 = string.getbyte(17) - b18 = string.getbyte(18) - if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && - b5 >= 48 && b5 <= 57 && b6 >= 48 && b6 <= 57 && - b8 >= 48 && b8 <= 57 && b9 >= 48 && b9 <= 57 && - b11 >= 48 && b11 <= 57 && b12 >= 48 && b12 <= 57 && - b14 >= 48 && b14 <= 57 && b15 >= 48 && b15 <= 57 && - b17 >= 48 && b17 <= 57 && b18 >= 48 && b18 <= 57 - h = { - year: (b0 - 48) * 1000 + (b1 - 48) * 100 + (b2 - 48) * 10 + (b3 - 48), - mon: (b5 - 48) * 10 + (b6 - 48), - mday: (b8 - 48) * 10 + (b9 - 48), - hour: (b11 - 48) * 10 + (b12 - 48), - min: (b14 - 48) * 10 + (b15 - 48), - sec: (b17 - 48) * 10 + (b18 - 48) - } - b19 = string.getbyte(19) - if (b19 == 90 || b19 == 122) && len == 20 # Z or z - h[:zone] = string[19, 1] - h[:offset] = 0 - elsif (b19 == 43 || b19 == 45) && len == 25 && string.getbyte(22) == 58 - zone = string[19, 6] - h[:zone] = zone - b20 = string.getbyte(20) - b21 = string.getbyte(21) - b23 = string.getbyte(23) - b24 = string.getbyte(24) - if b20 >= 48 && b20 <= 57 && b21 >= 48 && b21 <= 57 && - b23 >= 48 && b23 <= 57 && b24 >= 48 && b24 <= 57 - h[:offset] = (b19 == 45 ? -1 : 1) * ((b20 - 48) * 36000 + (b21 - 48) * 3600 + (b23 - 48) * 600 + (b24 - 48) * 60) - return h - end - end - return h if h.key?(:zone) + sc = StringScanner.new(string) + if sc.scan(/(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})/) + h = { + year: sc[1].to_i, mon: sc[2].to_i, mday: sc[3].to_i, + hour: sc[4].to_i, min: sc[5].to_i, sec: sc[6].to_i + } + if sc.scan(/[Zz]\z/) + h[:zone] = sc.matched + h[:offset] = 0 + return h + elsif sc.scan(/([+-])(\d{2}):(\d{2})\z/) + zone = sc.matched + h[:zone] = zone + h[:offset] = (sc[1] == '-' ? -1 : 1) * (sc[2].to_i * 3600 + sc[3].to_i * 60) + return h end end end @@ -92,24 +57,18 @@ def _rfc3339(string, limit: 128) h = {} if (m = RFC3339_RE.match(string)) h[:year] = m[1].to_i - s = m[2] - h[:mon] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) - s = m[3] - h[:mday] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) - s = m[4] - h[:hour] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) - s = m[5] - h[:min] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) - s = m[6] - h[:sec] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + h[:mon] = m[2].to_i + h[:mday] = m[3].to_i + h[:hour] = m[4].to_i + h[:min] = m[5].to_i + h[:sec] = m[6].to_i h[:sec_fraction] = Rational(m[7].to_i, 10 ** m[7].length) if m[7] zone = m[8] h[:zone] = zone - b0 = zone.getbyte(0) - if b0 == 90 || b0 == 122 # Z or z + if zone[0] == 'Z' || zone[0] == 'z' h[:offset] = 0 else - h[:offset] = (b0 == 45 ? -1 : 1) * ((zone.getbyte(1) - 48) * 36000 + (zone.getbyte(2) - 48) * 3600 + (zone.getbyte(4) - 48) * 600 + (zone.getbyte(5) - 48) * 60) + h[:offset] = (zone[0] == '-' ? -1 : 1) * (zone[1, 2].to_i * 3600 + zone[4, 2].to_i * 60) end end h @@ -140,30 +99,20 @@ def _httpdate(string, limit: 128) return {} if string.empty? raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit - # Byte-level fast path for Type 1: "Dow, DD Mon YYYY HH:MM:SS GMT" (29 bytes) - # Avoids all regex and string allocation overhead + # Fast path for Type 1: "Dow, DD Mon YYYY HH:MM:SS GMT" (29 bytes) len = string.length if len == 29 - b0 = string.getbyte(0) - if b0 >= 65 && string.getbyte(3) == 44 && string.getbyte(4) == 32 && # alpha, ',', ' ' - string.getbyte(7) == 32 && string.getbyte(11) == 32 && - string.getbyte(16) == 32 && string.getbyte(19) == 58 && - string.getbyte(22) == 58 && string.getbyte(25) == 32 && - string.getbyte(26) == 71 && string.getbyte(27) == 77 && string.getbyte(28) == 84 # 'G','M','T' - wkey = ((b0 | 32) << 16) | ((string.getbyte(1) | 32) << 8) | (string.getbyte(2) | 32) + sc = StringScanner.new(string) + if sc.scan(/([A-Za-z]{3}), (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) (GMT)\z/i) + wkey = compute_3key(sc[1]) wday_info = ABBR_DAY_3KEY[wkey] if wday_info - mkey = ((string.getbyte(8) | 32) << 16) | ((string.getbyte(9) | 32) << 8) | (string.getbyte(10) | 32) + mkey = compute_3key(sc[3]) mon_info = ABBR_MONTH_3KEY[mkey] if mon_info return { - wday: wday_info[0], - mday: (string.getbyte(5) - 48) * 10 + (string.getbyte(6) - 48), - mon: mon_info[0], - year: (string.getbyte(12) - 48) * 1000 + (string.getbyte(13) - 48) * 100 + (string.getbyte(14) - 48) * 10 + (string.getbyte(15) - 48), - hour: (string.getbyte(17) - 48) * 10 + (string.getbyte(18) - 48), - min: (string.getbyte(20) - 48) * 10 + (string.getbyte(21) - 48), - sec: (string.getbyte(23) - 48) * 10 + (string.getbyte(24) - 48), + wday: wday_info[0], mday: sc[2].to_i, mon: mon_info[0], + year: sc[4].to_i, hour: sc[5].to_i, min: sc[6].to_i, sec: sc[7].to_i, zone: 'GMT', offset: 0 } end @@ -174,43 +123,32 @@ def _httpdate(string, limit: 128) h = {} if (m = HTTPDATE_TYPE1_RE.match(string)) h[:wday] = HTTPDATE_WDAY[m[1].downcase] - s = m[2] - h[:mday] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + h[:mday] = m[2].to_i h[:mon] = ABBR_MONTH_NUM[m[3].downcase] h[:year] = m[4].to_i - s = m[5] - h[:hour] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) - s = m[6] - h[:min] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) - s = m[7] - h[:sec] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + h[:hour] = m[5].to_i + h[:min] = m[6].to_i + h[:sec] = m[7].to_i h[:zone] = m[8] h[:offset] = 0 elsif (m = HTTPDATE_TYPE2_RE.match(string)) h[:wday] = HTTPDATE_FULL_WDAY[m[1].downcase] - s = m[2] - h[:mday] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + h[:mday] = m[2].to_i h[:mon] = ABBR_MONTH_NUM[m[3].downcase] y = m[4].to_i h[:year] = y >= 69 ? y + 1900 : y + 2000 - s = m[5] - h[:hour] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) - s = m[6] - h[:min] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) - s = m[7] - h[:sec] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + h[:hour] = m[5].to_i + h[:min] = m[6].to_i + h[:sec] = m[7].to_i h[:zone] = m[8] h[:offset] = 0 elsif (m = HTTPDATE_TYPE3_RE.match(string)) h[:wday] = HTTPDATE_WDAY[m[1].downcase] h[:mon] = ABBR_MONTH_NUM[m[2].downcase] h[:mday] = m[3].to_i - s = m[4] - h[:hour] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) - s = m[5] - h[:min] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) - s = m[6] - h[:sec] = (s.getbyte(0) - 48) * 10 + (s.getbyte(1) - 48) + h[:hour] = m[4].to_i + h[:min] = m[5].to_i + h[:sec] = m[6].to_i h[:year] = m[7].to_i end h @@ -243,41 +181,26 @@ def _rfc2822(string, limit: 128) return {} if string.empty? raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit - # Byte-level fast path: "Dow, DD Mon YYYY HH:MM:SS +ZZZZ" (31 bytes, 2-digit day) - # Avoids all regex and string allocation overhead + # Fast path: "Dow, DD Mon YYYY HH:MM:SS +ZZZZ" (31 bytes, 2-digit day) len = string.length if len == 31 - b0 = string.getbyte(0) - if b0 >= 65 && string.getbyte(3) == 44 && string.getbyte(4) == 32 && # alpha, ',', ' ' - string.getbyte(7) == 32 && string.getbyte(11) == 32 && - string.getbyte(16) == 32 && string.getbyte(19) == 58 && - string.getbyte(22) == 58 && string.getbyte(25) == 32 - bz0 = string.getbyte(26) - if bz0 == 43 || bz0 == 45 # '+' or '-' - wkey = ((b0 | 32) << 16) | ((string.getbyte(1) | 32) << 8) | (string.getbyte(2) | 32) - wday_info = ABBR_DAY_3KEY[wkey] - if wday_info - mkey = ((string.getbyte(8) | 32) << 16) | ((string.getbyte(9) | 32) << 8) | (string.getbyte(10) | 32) - mon_info = ABBR_MONTH_3KEY[mkey] - if mon_info - bz1 = string.getbyte(27) - bz2 = string.getbyte(28) - bz3 = string.getbyte(29) - bz4 = string.getbyte(30) - sign = bz0 == 45 ? -1 : 1 - offset_val = sign * ((bz1 - 48) * 36000 + (bz2 - 48) * 3600 + (bz3 - 48) * 600 + (bz4 - 48) * 60) - zone = (bz0 == 43 && bz1 == 48 && bz2 == 48 && bz3 == 48 && bz4 == 48) ? '+0000' : string.byteslice(26, 5) - return { - wday: wday_info[0], - mday: (string.getbyte(5) - 48) * 10 + (string.getbyte(6) - 48), - mon: mon_info[0], - year: (string.getbyte(12) - 48) * 1000 + (string.getbyte(13) - 48) * 100 + (string.getbyte(14) - 48) * 10 + (string.getbyte(15) - 48), - hour: (string.getbyte(17) - 48) * 10 + (string.getbyte(18) - 48), - min: (string.getbyte(20) - 48) * 10 + (string.getbyte(21) - 48), - sec: (string.getbyte(23) - 48) * 10 + (string.getbyte(24) - 48), - zone: zone, offset: offset_val - } - end + sc = StringScanner.new(string) + if sc.scan(/([A-Za-z]{3}), (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) ([+-]\d{4})\z/) + wkey = compute_3key(sc[1]) + wday_info = ABBR_DAY_3KEY[wkey] + if wday_info + mkey = compute_3key(sc[3]) + mon_info = ABBR_MONTH_3KEY[mkey] + if mon_info + zone = sc[8] + sign = zone[0] == '-' ? -1 : 1 + offset_val = sign * (zone[1, 2].to_i * 3600 + zone[3, 2].to_i * 60) + zone = '+0000' if zone == '+0000' + return { + wday: wday_info[0], mday: sc[2].to_i, mon: mon_info[0], + year: sc[4].to_i, hour: sc[5].to_i, min: sc[6].to_i, sec: sc[7].to_i, + zone: zone, offset: offset_val + } end end end @@ -293,7 +216,7 @@ def _rfc2822(string, limit: 128) h[:mon] = ABBR_MONTH_NUM[m[3].downcase] y_s = m[4] y = y_s.to_i - ylen = y_s.getbyte(0) == 45 ? y_s.length - 1 : y_s.length + ylen = y_s[0] == '-' ? y_s.length - 1 : y_s.length if ylen < 4 if ylen == 3 h[:year] = y + 1900 @@ -303,14 +226,9 @@ def _rfc2822(string, limit: 128) else h[:year] = y end - s5 = m[5] - h[:hour] = (s5.getbyte(0) - 48) * 10 + (s5.getbyte(1) - 48) - s6 = m[6] - h[:min] = (s6.getbyte(0) - 48) * 10 + (s6.getbyte(1) - 48) - if m[7] - s7 = m[7] - h[:sec] = (s7.getbyte(0) - 48) * 10 + (s7.getbyte(1) - 48) - end + h[:hour] = m[5].to_i + h[:min] = m[6].to_i + h[:sec] = m[7].to_i if m[7] h[:zone] = m[8] h[:offset] = fast_zone_offset(m[8]) end @@ -346,26 +264,9 @@ def _xmlschema(string, limit: 128) # Fast path: YYYY-MM-DD (exactly 10 bytes, all ASCII) if string.length == 10 - b0 = string.getbyte(0) - if b0 >= 48 && b0 <= 57 - b1 = string.getbyte(1) - b2 = string.getbyte(2) - b3 = string.getbyte(3) - if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && - string.getbyte(4) == 45 && string.getbyte(7) == 45 - b5 = string.getbyte(5) - b6 = string.getbyte(6) - b8 = string.getbyte(8) - b9 = string.getbyte(9) - if b5 >= 48 && b5 <= 57 && b6 >= 48 && b6 <= 57 && - b8 >= 48 && b8 <= 57 && b9 >= 48 && b9 <= 57 - return { - year: (b0 - 48) * 1000 + (b1 - 48) * 100 + (b2 - 48) * 10 + (b3 - 48), - mon: (b5 - 48) * 10 + (b6 - 48), - mday: (b8 - 48) * 10 + (b9 - 48) - } - end - end + sc = StringScanner.new(string) + if sc.scan(/(\d{4})-(\d{2})-(\d{2})\z/) + return { year: sc[1].to_i, mon: sc[2].to_i, mday: sc[3].to_i } end end @@ -425,26 +326,9 @@ def _iso8601(string, limit: 128) # Fast path: YYYY-MM-DD (exactly 10 bytes, all ASCII) if string.length == 10 - b0 = string.getbyte(0) - if b0 >= 48 && b0 <= 57 - b1 = string.getbyte(1) - b2 = string.getbyte(2) - b3 = string.getbyte(3) - if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && - string.getbyte(4) == 45 && string.getbyte(7) == 45 - b5 = string.getbyte(5) - b6 = string.getbyte(6) - b8 = string.getbyte(8) - b9 = string.getbyte(9) - if b5 >= 48 && b5 <= 57 && b6 >= 48 && b6 <= 57 && - b8 >= 48 && b8 <= 57 && b9 >= 48 && b9 <= 57 - return { - mday: (b8 - 48) * 10 + (b9 - 48), - year: (b0 - 48) * 1000 + (b1 - 48) * 100 + (b2 - 48) * 10 + (b3 - 48), - mon: (b5 - 48) * 10 + (b6 - 48) - } - end - end + sc = StringScanner.new(string) + if sc.scan(/(\d{4})-(\d{2})-(\d{2})\z/) + return { mday: sc[3].to_i, year: sc[1].to_i, mon: sc[2].to_i } end end @@ -498,23 +382,14 @@ def _jisx0301(string, limit: 128) # Fast path: X##.##.## (9 bytes: era + YY.MM.DD) if string.length == 9 - b0 = string.getbyte(0) | 32 # downcase - era_offset = JISX0301_ERA[b0.chr] - if era_offset && - string.getbyte(3) == 46 && string.getbyte(6) == 46 # '.' - b1 = string.getbyte(1) - b2 = string.getbyte(2) - b4 = string.getbyte(4) - b5 = string.getbyte(5) - b7 = string.getbyte(7) - b8 = string.getbyte(8) - if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && - b4 >= 48 && b4 <= 57 && b5 >= 48 && b5 <= 57 && - b7 >= 48 && b7 <= 57 && b8 >= 48 && b8 <= 57 + sc = StringScanner.new(string) + if sc.scan(/([A-Za-z])(\d{2})\.(\d{2})\.(\d{2})\z/) + era_offset = JISX0301_ERA[sc[1].downcase] + if era_offset return { - year: (b1 - 48) * 10 + (b2 - 48) + era_offset, - mon: (b4 - 48) * 10 + (b5 - 48), - mday: (b7 - 48) * 10 + (b8 - 48) + year: sc[2].to_i + era_offset, + mon: sc[3].to_i, + mday: sc[4].to_i } end end @@ -582,49 +457,17 @@ def _parse(string, comp = true, limit: 128) # Fast ISO: YYYY-MM-DD (exactly 10 ASCII bytes) if len == 10 - b0 = string.getbyte(0) - if b0 >= 48 && b0 <= 57 - b1 = string.getbyte(1) - b2 = string.getbyte(2) - b3 = string.getbyte(3) - if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && - string.getbyte(4) == 45 && string.getbyte(7) == 45 - b5 = string.getbyte(5) - b6 = string.getbyte(6) - b8 = string.getbyte(8) - b9 = string.getbyte(9) - if b5 >= 48 && b5 <= 57 && b6 >= 48 && b6 <= 57 && - b8 >= 48 && b8 <= 57 && b9 >= 48 && b9 <= 57 - return { - year: (b0 - 48) * 1000 + (b1 - 48) * 100 + (b2 - 48) * 10 + (b3 - 48), - mon: (b5 - 48) * 10 + (b6 - 48), - mday: (b8 - 48) * 10 + (b9 - 48) - } - end - end + sc = StringScanner.new(string) + if sc.scan(/(\d{4})-(\d{2})-(\d{2})\z/) + return { year: sc[1].to_i, mon: sc[2].to_i, mday: sc[3].to_i } end end # Fast compact: YYYYMMDD (exactly 8 ASCII digit bytes) if len == 8 - b0 = string.getbyte(0) - if b0 >= 48 && b0 <= 57 - b1 = string.getbyte(1) - b2 = string.getbyte(2) - b3 = string.getbyte(3) - b4 = string.getbyte(4) - b5 = string.getbyte(5) - b6 = string.getbyte(6) - b7 = string.getbyte(7) - if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && - b4 >= 48 && b4 <= 57 && b5 >= 48 && b5 <= 57 && - b6 >= 48 && b6 <= 57 && b7 >= 48 && b7 <= 57 - return { - year: (b0 - 48) * 1000 + (b1 - 48) * 100 + (b2 - 48) * 10 + (b3 - 48), - mon: (b4 - 48) * 10 + (b5 - 48), - mday: (b6 - 48) * 10 + (b7 - 48) - } - end + sc = StringScanner.new(string) + if sc.scan(/(\d{4})(\d{2})(\d{2})\z/) + return { year: sc[1].to_i, mon: sc[2].to_i, mday: sc[3].to_i } end end @@ -981,33 +824,18 @@ def parse_sec_fraction(frac_str) # Fast zone offset calculation for common patterns. # Handles: Z/z, +HH:MM/-HH:MM, +HHMM/-HHMM, short named zones. - # Falls back to _sp_zone_to_diff for complex cases. - def fast_zone_offset(zone_str) # rubocop:disable Metrics/CyclomaticComplexity + # Falls back to sp_zone_to_diff for complex cases. + def fast_zone_offset(zone_str) len = zone_str.length - b0 = zone_str.getbyte(0) # Z/z - return 0 if len == 1 && (b0 == 90 || b0 == 122) - - if b0 == 43 || b0 == 45 # '+' or '-' - sign = b0 == 45 ? -1 : 1 - if len == 6 && zone_str.getbyte(3) == 58 # +HH:MM - b1 = zone_str.getbyte(1) - b2 = zone_str.getbyte(2) - b4 = zone_str.getbyte(4) - b5 = zone_str.getbyte(5) - if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b4 >= 48 && b4 <= 57 && b5 >= 48 && b5 <= 57 - return sign * ((b1 - 48) * 36000 + (b2 - 48) * 3600 + (b4 - 48) * 600 + (b5 - 48) * 60) - end - end - if len == 5 # +HHMM - b1 = zone_str.getbyte(1) - b2 = zone_str.getbyte(2) - b3 = zone_str.getbyte(3) - b4 = zone_str.getbyte(4) - if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && b4 >= 48 && b4 <= 57 - return sign * ((b1 - 48) * 36000 + (b2 - 48) * 3600 + (b3 - 48) * 600 + (b4 - 48) * 60) - end + return 0 if len == 1 && (zone_str[0] == 'Z' || zone_str[0] == 'z') + + if zone_str[0] == '+' || zone_str[0] == '-' + sc = StringScanner.new(zone_str) + if sc.scan(/([+-])(\d{2}):?(\d{2})\z/) + sign = sc[1] == '-' ? -1 : 1 + return sign * (sc[2].to_i * 3600 + sc[3].to_i * 60) end end @@ -1018,7 +846,7 @@ def fast_zone_offset(zone_str) # rubocop:disable Metrics/CyclomaticComplexity end # Fall back to full parser - _sp_zone_to_diff(zone_str) + sp_zone_to_diff(zone_str) end # ------------------------------------------------------------------ @@ -1522,7 +1350,7 @@ def parse_frag(str, h) # s3e: 3-element (year, month, day) disambiguation # Faithfully mirrors the C implementation's s3e() logic. # Arguments: y, m, d are strings (or Integer for m when month name was parsed) - def s3e(h, y, m, d, bc) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + def s3e(h, y, m, d, bc) # Fast path: y is unambiguously a year (3+ digits or signed), m and d are simple digits. # This covers ISO "2001-02-03" but not ambiguous cases like "23/5/1999". if y && m && d && !bc && y.is_a?(String) && m.is_a?(String) && d.is_a?(String) && @@ -1695,7 +1523,7 @@ def fast_new_date(hash, sg) new_from_jd(jd, sg) end else - _new_by_frags(hash, sg) + internal_new_by_frags(hash, sg) end end diff --git a/lib/date/shared.rb b/lib/date/shared.rb new file mode 100644 index 00000000..24dd65f3 --- /dev/null +++ b/lib/date/shared.rb @@ -0,0 +1,13 @@ +# frozen_string_literal: true + +# Shared methods used across multiple Date implementation files. +class Date + # Generate a case-insensitive 3-byte integer key from a 3-character string. + # Used for O(1) abbreviated day/month name lookup in parse.rb and strptime.rb. + # Key = (byte0_lower << 16) | (byte1_lower << 8) | byte2_lower + def self.compute_3key(s) + b = s.bytes + ((b[0] | 0x20) << 16) | ((b[1] | 0x20) << 8) | (b[2] | 0x20) + end + private_class_method :compute_3key +end diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 681854c2..65e6444c 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -15,24 +15,24 @@ class Date def strftime(format = DEFAULT_STRFTIME_FMT) if format.equal?(DEFAULT_STRFTIME_FMT) internal_civil unless @year - return _fast_ymd.force_encoding(Encoding::US_ASCII) + return fast_ymd.force_encoding(Encoding::US_ASCII) end fmt = format.to_str if fmt == YMD_FMT internal_civil unless @year - return _fast_ymd.force_encoding(Encoding::US_ASCII) + return fast_ymd.force_encoding(Encoding::US_ASCII) end internal_strftime(fmt).force_encoding(fmt.encoding) end private - def internal_strftime(fmt) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + def internal_strftime(fmt) # Fast path for common format strings (whole-string match) case fmt when '%Y-%m-%d', '%F' internal_civil unless @year - return _fast_ymd + return fast_ymd when '%H:%M:%S', '%T', '%X' return instance_of?(Date) ? +'00:00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}" when '%m/%d/%y', '%D', '%x' @@ -41,16 +41,16 @@ def internal_strftime(fmt) # rubocop:disable Metrics/MethodLength,Metrics/Cyclom when '%Y-%m-%dT%H:%M:%S%z' internal_civil unless @year if instance_of?(Date) - return _fast_ymd << 'T00:00:00+0000' + return fast_ymd << 'T00:00:00+0000' else - of = _of_seconds + of = of_seconds sign = of < 0 ? '-' : '+' abs = of.abs - return "#{_fast_ymd}T#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}#{sign}#{PAD2[abs / 3600]}#{PAD2[(abs % 3600) / 60]}" + return "#{fast_ymd}T#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}#{sign}#{PAD2[abs / 3600]}#{PAD2[(abs % 3600) / 60]}" end when '%a %b %e %H:%M:%S %Y', '%c' internal_civil unless @year - return _fmt_asctime_str + return fmt_asctime_str when '%A, %B %d, %Y' internal_civil unless @year w = (@jd + 1) % 7 @@ -60,124 +60,87 @@ def internal_strftime(fmt) # rubocop:disable Metrics/MethodLength,Metrics/Cyclom end result = +''.encode(fmt.encoding) - i = 0 - len = fmt.bytesize - - while i < len - b = fmt.getbyte(i) + sc = StringScanner.new(fmt) + until sc.eos? # Batch collect literal (non-%) characters - if b != 37 # '%' - lit_start = i - i += 1 - i += 1 while i < len && fmt.getbyte(i) != 37 - result << fmt.byteslice(lit_start, i - lit_start) + if (lit = sc.scan(/[^%]+/)) + result << lit next end - i += 1 # skip '%' - if i >= len + # Must be '%' or something unexpected + unless sc.skip(/%/) + result << sc.getch + next + end + + if sc.eos? result << '%' break end - # Quick dispatch: if next byte is a simple letter spec (A-Z or a-z, - # excluding E/O locale modifiers), skip flag/width/prec parsing entirely. - # Flag chars '-'(45) '_'(95) '0'(48) '^'(94) '#'(35) ':'(58) are all - # outside A-Z(65-90) and a-z(97-122) ranges. - b = fmt.getbyte(i) - if (b >= 65 && b <= 90 && b != 69 && b != 79) || (b >= 97 && b <= 122) - fast = _fast_spec(b) + # Quick dispatch: if next char is a simple letter spec (A-Z excluding E/O, + # or a-z), skip flag/width/prec parsing entirely. + if (quick = sc.scan(/[A-DFG-NP-Za-z]/)) + fast = fast_spec(quick.ord) if fast result << fast - i += 1 next end + sc.unscan end - # Parse flags (bitmask — no Hash allocation) + # Parse flags (bitmask) flags = 0 colons = 0 - loop do - b = fmt.getbyte(i) - case b - when 45 then flags |= FL_LEFT # '-' - when 95 then flags |= FL_SPACE # '_' - when 48 then flags |= FL_ZERO # '0' - when 94 then flags |= FL_UPPER # '^' - when 35 then flags |= FL_CHCASE # '#' - when 58 # ':' - colons += 1 - i += 1 - redo if fmt.getbyte(i) == 58 - break - else break + while (f = sc.scan(/[-_0^#]/)) + case f + when '-' then flags |= FL_LEFT + when '_' then flags |= FL_SPACE + when '0' then flags |= FL_ZERO + when '^' then flags |= FL_UPPER + when '#' then flags |= FL_CHCASE end - i += 1 end - - # Parse width (byte range check — no Regexp) - width = nil - b = fmt.getbyte(i) - if b && b >= 48 && b <= 57 # '0'..'9' - width = b - 48 - i += 1 - b = fmt.getbyte(i) - while b && b >= 48 && b <= 57 - width = width * 10 + (b - 48) - i += 1 - b = fmt.getbyte(i) - end - raise Errno::ERANGE, "strftime" if width > STRFTIME_MAX_WIDTH + if (c = sc.scan(/:+/)) + colons = c.length end + # Parse width + width = sc.scan(/\d+/)&.to_i + raise Errno::ERANGE, "strftime" if width && width > STRFTIME_MAX_WIDTH + # Parse precision (after '.') - prec = nil - if fmt.getbyte(i) == 46 # '.' - i += 1 - prec = 0 - b = fmt.getbyte(i) - while b && b >= 48 && b <= 57 - prec = prec * 10 + (b - 48) - i += 1 - b = fmt.getbyte(i) - end - end + prec = sc.skip(/\./) ? (sc.scan(/\d+/)&.to_i || 0) : nil # Post-width colons (for %8:z, %11::z etc.) - while fmt.getbyte(i) == 58 # ':' - colons += 1 - i += 1 + if (c = sc.scan(/:+/)) + colons += c.length end # Locale modifier (%E or %O) - locale_mod = nil - b = fmt.getbyte(i) - if b == 69 || b == 79 # 'E' or 'O' - locale_mod = b - i += 1 - end + locale_mod = sc.scan(/[EO]/)&.ord - spec = fmt.getbyte(i) - i += 1 + spec = sc.getch&.ord # Inline fast path: no flags, no width, no prec, no locale mod, no colons if flags == 0 && width.nil? && prec.nil? && locale_mod.nil? && colons == 0 - fast = _fast_spec(spec) + fast = fast_spec(spec) if fast result << fast next end end - result << _format_spec_b(spec, flags, colons, width, prec, locale_mod) + result << format_spec_b(spec, flags, colons, width, prec, locale_mod) end result end # Format "%a %b %e %H:%M:%S %Y" directly (used by %c expansion and asctime) - def _fmt_asctime_str + def fmt_asctime_str w = (@jd + 1) % 7 d = @day d_s = d < 10 ? " #{d}" : d.to_s @@ -191,7 +154,7 @@ def _fmt_asctime_str end # Inline fast path for common specs with default formatting (no flags/width/prec) - def _fast_spec(spec) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + def fast_spec(spec) case spec when 89 # 'Y' internal_civil unless @year @@ -258,21 +221,21 @@ def _fast_spec(spec) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticCo internal_civil unless @year PAD2[@year.abs % 100] when 90 # 'Z' - _zone_str + zone_str when 122 # 'z' - of = _of_seconds + of = of_seconds sign = of < 0 ? '-' : '+' abs = of.abs "#{sign}#{PAD2[abs / 3600]}#{PAD2[(abs % 3600) / 60]}" when 115 # 's' - ((@jd - 2440588) * 86400 - _of_seconds + internal_hour * 3600 + internal_min * 60 + internal_sec).to_s + ((@jd - 2440588) * 86400 - of_seconds + internal_hour * 3600 + internal_min * 60 + internal_sec).to_s # Composite specs — inline expansion when 99 # 'c' internal_civil unless @year - _fmt_asctime_str + fmt_asctime_str when 70 # 'F' internal_civil unless @year - _fast_ymd + fast_ymd when 84, 88 # 'T', 'X' instance_of?(Date) ? '00:00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}" when 68, 120 # 'D', 'x' @@ -289,12 +252,12 @@ def _fast_spec(spec) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticCo "#{PAD2[h]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} #{internal_hour < 12 ? 'AM' : 'PM'}" end else - nil # fall through to _format_spec_b + nil # fall through to format_spec_b end end - # Full spec handling with bitmask flags (called when _fast_spec returns nil or flags/width/prec present) - def _format_spec_b(spec, flags, colons, width, prec, locale_mod) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + # Full spec handling with bitmask flags (called when fast_spec returns nil or flags/width/prec present) + def format_spec_b(spec, flags, colons, width, prec, locale_mod) # Handle %E/%O locale modifiers if locale_mod valid = locale_mod == 69 ? STRFTIME_E_VALID_BYTES : STRFTIME_O_VALID_BYTES # 69='E' @@ -307,92 +270,92 @@ def _format_spec_b(spec, flags, colons, width, prec, locale_mod) # rubocop:disab case spec when 89, 71 # 'Y', 'G' y = spec == 89 ? year : cwyear - _fmt_year(y, width, prec, flags) + fmt_year(y, width, prec, flags) when 67 # 'C' cent = year.div(100) - _pad_num(cent, width || 2, flags) + pad_num(cent, width || 2, flags) when 121 # 'y' - _pad_num(year.abs % 100, width || 2, flags, zero: true) + pad_num(year.abs % 100, width || 2, flags, zero: true) when 103 # 'g' - _pad_num(cwyear.abs % 100, width || 2, flags, zero: true) + pad_num(cwyear.abs % 100, width || 2, flags, zero: true) when 109 # 'm' - _pad_num(month, width || 2, flags, zero: true) + pad_num(month, width || 2, flags, zero: true) when 100 # 'd' - _pad_num(day, width || 2, flags, zero: true) + pad_num(day, width || 2, flags, zero: true) when 101 # 'e' - _pad_num(day, width || 2, flags, zero: false) + pad_num(day, width || 2, flags, zero: false) when 106 # 'j' - _pad_num(yday, width || 3, flags, zero: true) + pad_num(yday, width || 3, flags, zero: true) when 72 # 'H' - _pad_num(internal_hour, width || 2, flags, zero: true) + pad_num(internal_hour, width || 2, flags, zero: true) when 107 # 'k' - _pad_num(internal_hour, width || 2, flags, zero: false) + pad_num(internal_hour, width || 2, flags, zero: false) when 73 # 'I' h = internal_hour % 12 h = 12 if h == 0 - _pad_num(h, width || 2, flags, zero: true) + pad_num(h, width || 2, flags, zero: true) when 108 # 'l' h = internal_hour % 12 h = 12 if h == 0 - _pad_num(h, width || 2, flags, zero: false) + pad_num(h, width || 2, flags, zero: false) when 77 # 'M' - _pad_num(internal_min, width || 2, flags, zero: true) + pad_num(internal_min, width || 2, flags, zero: true) when 83 # 'S' - _pad_num(internal_sec, width || 2, flags, zero: true) + pad_num(internal_sec, width || 2, flags, zero: true) when 76 # 'L' w = width || 3 - ms = (_sec_frac * (10**w)).floor + ms = (sec_frac * (10**w)).floor ms.to_s.rjust(w, '0') when 78 # 'N' w = width || prec || 9 - ns = (_sec_frac * (10**w)).floor + ns = (sec_frac * (10**w)).floor ns.to_s.rjust(w, '0') when 115 # 's' - unix = (@jd - 2440588) * 86400 - _of_seconds + + unix = (@jd - 2440588) * 86400 - of_seconds + internal_hour * 3600 + internal_min * 60 + internal_sec - _pad_num(unix, width || 1, flags) + pad_num(unix, width || 1, flags) when 81 # 'Q' - ms = ((@jd - 2440588) * 86400 - _of_seconds + + ms = ((@jd - 2440588) * 86400 - of_seconds + internal_hour * 3600 + internal_min * 60 + internal_sec) * 1000 + - (_sec_frac * 1000).floor - _pad_num(ms, width || 1, flags) + (sec_frac * 1000).floor + pad_num(ms, width || 1, flags) when 65 # 'A' - _fmt_str(STRFTIME_DAYS_FULL[wday], width, flags) + fmt_str(STRFTIME_DAYS_FULL[wday], width, flags) when 97 # 'a' - _fmt_str(STRFTIME_DAYS_ABBR[wday], width, flags) + fmt_str(STRFTIME_DAYS_ABBR[wday], width, flags) when 66 # 'B' - _fmt_str(STRFTIME_MONTHS_FULL[month], width, flags) + fmt_str(STRFTIME_MONTHS_FULL[month], width, flags) when 98, 104 # 'b', 'h' - _fmt_str(STRFTIME_MONTHS_ABBR[month], width, flags) + fmt_str(STRFTIME_MONTHS_ABBR[month], width, flags) when 112 # 'p' - _fmt_str(internal_hour < 12 ? 'AM' : 'PM', width, flags) + fmt_str(internal_hour < 12 ? 'AM' : 'PM', width, flags) when 80 # 'P' - _fmt_str(internal_hour < 12 ? 'am' : 'pm', width, flags) + fmt_str(internal_hour < 12 ? 'am' : 'pm', width, flags) when 90 # 'Z' - _fmt_str(_zone_str, width, flags) + fmt_str(zone_str, width, flags) when 122 # 'z' - _fmt_z(colons, width, prec, flags) + fmt_z(colons, width, prec, flags) when 117 # 'u' - _pad_num(cwday, width || 1, flags) + pad_num(cwday, width || 1, flags) when 119 # 'w' - _pad_num(wday, width || 1, flags) + pad_num(wday, width || 1, flags) when 85 # 'U' - _pad_num(_week_number(0), width || 2, flags, zero: true) + pad_num(week_number(0), width || 2, flags, zero: true) when 87 # 'W' - _pad_num(_week_number(1), width || 2, flags, zero: true) + pad_num(week_number(1), width || 2, flags, zero: true) when 86 # 'V' - _pad_num(cweek, width || 2, flags, zero: true) + pad_num(cweek, width || 2, flags, zero: true) when 37 # '%' '%' when 43 # '+' s = internal_strftime('%a %b %e %H:%M:%S %Z %Y') - _fmt_str(s, width, flags) + fmt_str(s, width, flags) else # Try composite expansion = STRFTIME_COMPOSITE_BYTE[spec] if expansion s = internal_strftime(expansion) - _fmt_str(s, width, flags) + fmt_str(s, width, flags) else "%#{spec&.chr}" end @@ -400,7 +363,7 @@ def _format_spec_b(spec, flags, colons, width, prec, locale_mod) # rubocop:disab end # Format year (handles negative years, precision, and all flag variants) - def _fmt_year(y, width, prec, flags) + def fmt_year(y, width, prec, flags) if prec s = y.abs.to_s.rjust(prec, '0') s = (y < 0 ? '-' : '') + s @@ -425,7 +388,7 @@ def _fmt_year(y, width, prec, flags) end end - def _pad_num(n, default_w, flags, zero: nil) + def pad_num(n, default_w, flags, zero: nil) sign = n < 0 ? '-' : '' abs = n.abs.to_s w = default_w @@ -440,7 +403,7 @@ def _pad_num(n, default_w, flags, zero: nil) end end - def _fmt_str(s, width, flags) + def fmt_str(s, width, flags) s = s.dup if flags & FL_CHCASE != 0 s = (s == s.upcase) ? s.downcase : s.upcase @@ -458,7 +421,7 @@ def _fmt_str(s, width, flags) end # Week number (0=first partial week) - def _week_number(ws) + def week_number(ws) yd = yday wd = wday # 0=Sun if ws == 1 @@ -469,8 +432,8 @@ def _week_number(ws) end # Format %z with colons variant and GNU extension flag support - def _fmt_z(colons, width, _prec, flags) - of = _of_seconds + def fmt_z(colons, width, _prec, flags) + of = of_seconds sign = of < 0 ? '-' : '+' abs = of.abs hh = abs / 3600 @@ -534,7 +497,7 @@ def _fmt_z(colons, width, _prec, flags) end # Fast path helper: format '%Y-%m-%d' without allocation overhead - def _fast_ymd + def fast_ymd y = @year suffix = MONTH_DAY_SUFFIX[@month][@day] if y >= 1000 @@ -559,15 +522,15 @@ def internal_sec 0 end - def _sec_frac + def sec_frac Rational(0) end - def _of_seconds + def of_seconds 0 end - def _zone_str + def zone_str '+00:00' end diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index 3a482be0..cd615b03 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -21,14 +21,14 @@ def _strptime(string, format = '%F') string = String === string ? string : string.to_str format = String === format ? format : format.to_str if format == '%F' || format == '%Y-%m-%d' - return _strptime_ymd(string) + return internal_strptime_ymd(string) end if format == '%a %b %d %Y' - return _strptime_abdy(string) + return internal_strptime_abdy(string) end hash = {} - si = _sp_run(string, 0, format, hash) - return nil if hash.delete(:_fail) + si = catch(:sp_fail) { sp_run(string, 0, format, hash) } + return nil unless si hash[:leftover] = string[si..] if si < string.length if (cent = hash.delete(:_cent)) hash[:year] = hash[:year] + cent * 100 if hash.key?(:year) @@ -66,12 +66,12 @@ def _strptime(string, format = '%F') def strptime(string = JULIAN_EPOCH_DATE, format = '%F', start = DEFAULT_SG) str = String === string ? string : string.to_str if format == '%F' || format == '%Y-%m-%d' - result = _strptime_ymd_to_date(str, start) + result = internalinternal_strptime_ymd_to_date(str, start) return result if result raise Error, 'invalid date' end if format == '%a %b %d %Y' - result = _strptime_abdy_to_date(str, start) + result = internalinternal_strptime_abdy_to_date(str, start) return result if result raise Error, 'invalid date' end @@ -84,870 +84,462 @@ def strptime(string = JULIAN_EPOCH_DATE, format = '%F', start = DEFAULT_SG) raise Error, 'invalid date' if jd.nil? return new_from_jd(jd, start) end - _new_by_frags(hash, start) + internal_new_by_frags(hash, start) end private - # Returns true if the format at position fi starts a numeric conversion spec. - # All byte-level comparison, no String allocation. - def _sp_num_p_b?(fmt, fi, flen) - return false if fi >= flen - c = fmt.getbyte(fi) - return true if c >= 48 && c <= 57 # '0'..'9' - if c == 37 # '%' - i = fi + 1 - return false if i >= flen - c2 = fmt.getbyte(i) - if c2 == 69 || c2 == 79 # 'E' or 'O' - i += 1 - return false if i >= flen - c2 = fmt.getbyte(i) - end - return STRPTIME_NUMERIC_SPEC_SET[c2] - end - false - end - - # Read up to max_w decimal digits from str starting at si. - # Returns [value, chars_consumed] or [nil, 0] if no digit found. - def _sp_digits(str, si, slen, max_w) - l = 0 - v = 0 - while si + l < slen - c = str.getbyte(si + l) - break unless c && c >= 48 && c <= 57 # '0'..'9' - break if l >= max_w - v = v * 10 + (c - 48) - l += 1 - end - return nil, 0 if l == 0 - return v, l - end - - # Whitespace byte check (space, tab, newline, carriage return, vertical tab, form feed) - def _sp_ws?(b) - b == 32 || b == 9 || b == 10 || b == 13 || b == 11 || b == 12 - end - - # Core scanner: walks format string and string simultaneously. - # All comparisons use getbyte for zero-allocation byte-level operation. - # Returns new string index si on success. - # Sets hash[:_fail]=true and returns -1 on failure. - def _sp_run(str, si, fmt, hash) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity - fi = 0 - flen = fmt.bytesize - slen = str.bytesize - - while fi < flen - ch = fmt.getbyte(fi) - + # Pre-compiled regex constants for sp_run + SP_WHITESPACE = /[ \t\n\r\v\f]+/ + SP_COLONS = /:+/ + SP_EO_CHECK = /[EO]/ + SP_E_COMBO = /E[cCxXyY]/ + SP_O_COMBO = /O[deHImMSuUVwWy]/ + SP_ALPHA3 = /[A-Za-z]{3}/ + SP_SIGN = /[+-]/ + SP_SPACE_OR_DIGIT = / \d|\d{1,2}/ + SP_AMPM_DOT = /[AaPp]\.[Mm]\./ + SP_AMPM = /[AaPp][Mm]/ + SP_NUM_CHECK = /\d|%[EO]?[CDdeFGgHIjkLlMmNQRrSsTUuVvWwXxYy0-9]/ + SP_DIGITS_1 = /\d/ + SP_DIGITS_2 = /\d{1,2}/ + SP_DIGITS_3 = /\d{1,3}/ + SP_DIGITS_4 = /\d{1,4}/ + SP_DIGITS_9 = /\d{1,9}/ + SP_DIGITS_MAX = /\d+/ + private_constant :SP_WHITESPACE, :SP_COLONS, :SP_EO_CHECK, :SP_E_COMBO, + :SP_O_COMBO, :SP_ALPHA3, :SP_SIGN, :SP_SPACE_OR_DIGIT, + :SP_AMPM_DOT, :SP_AMPM, :SP_NUM_CHECK, + :SP_DIGITS_1, :SP_DIGITS_2, :SP_DIGITS_3, :SP_DIGITS_4, + :SP_DIGITS_9, :SP_DIGITS_MAX + + # Core scanner: walks format string and string simultaneously using StringScanner. + # Returns new string position on success; throws :sp_fail on failure. + def sp_run(str, si, fmt, hash) + fmt_sc = StringScanner.new(fmt) + str_sc = StringScanner.new(str) + str_sc.pos = si + + until fmt_sc.eos? # Whitespace in format: skip any whitespace in both format and string - if _sp_ws?(ch) - while si < slen && _sp_ws?(str.getbyte(si)) - si += 1 - end - fi += 1 - while fi < flen && _sp_ws?(fmt.getbyte(fi)) - fi += 1 - end + if fmt_sc.skip(SP_WHITESPACE) + str_sc.skip(SP_WHITESPACE) next end - if ch != 37 # '%' - if si >= slen - hash[:_fail] = true - return -1 - end - if str.getbyte(si) != ch - hash[:_fail] = true - return -1 - end - si += 1 - fi += 1 + # Non-% literal: must match exactly + unless fmt_sc.check(/%/) + fc = fmt_sc.getch + throw(:sp_fail) if str_sc.eos? + throw(:sp_fail) if str_sc.getch != fc next end - fi += 1 # skip '%' + fmt_sc.skip(/%/) # skip '%' # Handle colon modifiers: %:z, %::z, %:::z - colons = 0 - while fi < flen && fmt.getbyte(fi) == 58 # ':' - colons += 1 - fi += 1 - end - if colons > 0 - unless fi < flen && fmt.getbyte(fi) == 122 # 'z' - hash[:_fail] = true - return -1 - end - fi += 1 - new_si = _sp_zone(str, si, slen, hash) - if new_si < 0 - hash[:_fail] = true - return -1 - end - si = new_si + if fmt_sc.scan(SP_COLONS) + throw(:sp_fail) unless fmt_sc.skip(/z/) + str_sc.pos = sp_zone(str, str_sc.pos, str.bytesize, hash) next end # Handle E/O locale modifiers - fb = fi < flen ? fmt.getbyte(fi) : nil - if fb == 69 || fb == 79 # 'E' or 'O' - valid_set = fb == 69 ? STRPTIME_E_VALID_SET : STRPTIME_O_VALID_SET - fb2 = fi + 1 < flen ? fmt.getbyte(fi + 1) : nil - if fb2 && valid_set[fb2] - fi += 1 # skip E/O, fall through to handle spec + if fmt_sc.check(SP_EO_CHECK) + if fmt_sc.check(SP_E_COMBO) || fmt_sc.check(SP_O_COMBO) + fmt_sc.skip(SP_EO_CHECK) # skip modifier, fall through to spec else # Invalid combo: match '%' literally in string - if si >= slen || str.getbyte(si) != 37 # '%' - hash[:_fail] = true - return -1 - end - si += 1 + throw(:sp_fail) if str_sc.eos? || str_sc.peek(1) != '%' + str_sc.skip(/%/) next end end - spec = fi < flen ? fmt.getbyte(fi) : nil - fi += 1 + spec_ch = fmt_sc.getch + spec = spec_ch&.ord case spec when 65, 97 # 'A', 'a' - # Weekday name: 3-byte key O(1) lookup - if si + 2 >= slen - hash[:_fail] = true - return -1 - end - key = ((str.getbyte(si) | 0x20) << 16) | ((str.getbyte(si + 1) | 0x20) << 8) | (str.getbyte(si + 2) | 0x20) + s3 = str_sc.scan(SP_ALPHA3) + throw(:sp_fail) unless s3 + key = compute_3key(s3) entry = ABBR_DAY_3KEY[key] - unless entry - hash[:_fail] = true - return -1 - end + throw(:sp_fail) unless entry wday_i = entry[0] - day_full_len = entry[1] - if si + day_full_len <= slen && _sp_head_match?(str, si, slen, DAY_LOWER_BYTES[wday_i], day_full_len) - si += day_full_len - else - si += 3 + remaining = entry[1] - 3 + if remaining > 0 + tail = str_sc.peek(remaining) + if tail.length == remaining && tail.downcase == DAY_LOWER_STRS[wday_i][3..] + str_sc.pos += remaining + end end hash[:wday] = wday_i when 66, 98, 104 # 'B', 'b', 'h' - # Month name: 3-byte key O(1) lookup - if si + 2 >= slen - hash[:_fail] = true - return -1 - end - key = ((str.getbyte(si) | 0x20) << 16) | ((str.getbyte(si + 1) | 0x20) << 8) | (str.getbyte(si + 2) | 0x20) + s3 = str_sc.scan(SP_ALPHA3) + throw(:sp_fail) unless s3 + key = compute_3key(s3) entry = ABBR_MONTH_3KEY[key] - unless entry - hash[:_fail] = true - return -1 - end + throw(:sp_fail) unless entry mon_i = entry[0] - mon_full_len = entry[1] - if si + mon_full_len <= slen && _sp_head_match?(str, si, slen, MONTH_LOWER_BYTES[mon_i], mon_full_len) - si += mon_full_len - else - si += 3 + remaining = entry[1] - 3 + if remaining > 0 + tail = str_sc.peek(remaining) + if tail.length == remaining && tail.downcase == MONTH_LOWER_STRS[mon_i][3..] + str_sc.pos += remaining + end end hash[:mon] = mon_i when 67 # 'C' - # Century: greedy unless next spec is numeric - w = _sp_num_p_b?(fmt, fi, flen) ? 2 : 10000 - sb = si < slen ? str.getbyte(si) : nil - if sb == 43 || sb == 45 # '+' or '-' - sign = sb == 45 ? -1 : 1 - si += 1 + num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) + if str_sc.scan(SP_SIGN) + sign = str_sc.matched == '-' ? -1 : 1 else sign = 1 end - n, l = _sp_digits(str, si, slen, w) - if l == 0 - hash[:_fail] = true - return -1 - end - si += l - hash[:_cent] = sign * n + s = str_sc.scan(num_next ? SP_DIGITS_2 : SP_DIGITS_MAX) + throw(:sp_fail) unless s + hash[:_cent] = sign * s.to_i when 99 # 'c' - new_si = _sp_run(str, si, '%a %b %e %H:%M:%S %Y', hash) - return new_si if new_si < 0 - si = new_si + str_sc.pos = sp_run(str, str_sc.pos, '%a %b %e %H:%M:%S %Y', hash) when 68 # 'D' - new_si = _sp_run(str, si, '%m/%d/%y', hash) - return new_si if new_si < 0 - si = new_si + str_sc.pos = sp_run(str, str_sc.pos, '%m/%d/%y', hash) when 100, 101 # 'd', 'e' - # Day of month (leading space allowed for single-digit) - inlined - if si < slen && str.getbyte(si) == 32 # ' ' - si += 1 - b = si < slen ? str.getbyte(si) : nil - unless b && b >= 48 && b <= 57 - hash[:_fail] = true - return -1 - end - n = b - 48 - si += 1 - else - b = si < slen ? str.getbyte(si) : nil - unless b && b >= 48 && b <= 57 - hash[:_fail] = true - return -1 - end - n = b - 48 - si += 1 - b = si < slen ? str.getbyte(si) : nil - if b && b >= 48 && b <= 57 - n = n * 10 + (b - 48) - si += 1 - end - end - if n < 1 || n > 31 - hash[:_fail] = true - return -1 - end + s = str_sc.scan(SP_SPACE_OR_DIGIT) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n < 1 || n > 31 hash[:mday] = n when 70 # 'F' - new_si = _sp_run(str, si, '%Y-%m-%d', hash) - return new_si if new_si < 0 - si = new_si + str_sc.pos = sp_run(str, str_sc.pos, '%Y-%m-%d', hash) when 71 # 'G' - # ISO week-based year: greedy unless next spec is numeric - sb = si < slen ? str.getbyte(si) : nil - if sb == 43 || sb == 45 # '+' or '-' - sign = sb == 45 ? -1 : 1 - si += 1 + if str_sc.scan(SP_SIGN) + sign = str_sc.matched == '-' ? -1 : 1 else sign = 1 end - w = _sp_num_p_b?(fmt, fi, flen) ? 4 : 10000 - n, l = _sp_digits(str, si, slen, w) - if l == 0 - hash[:_fail] = true - return -1 - end - si += l - hash[:cwyear] = sign * n + num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) + s = str_sc.scan(num_next ? SP_DIGITS_4 : SP_DIGITS_MAX) + throw(:sp_fail) unless s + hash[:cwyear] = sign * s.to_i when 103 # 'g' - # 2-digit ISO week year - n, l = _sp_digits(str, si, slen, 2) - if l == 0 || n > 99 - hash[:_fail] = true - return -1 - end - si += l + s = str_sc.scan(SP_DIGITS_2) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n > 99 hash[:cwyear] = n hash[:_cent] ||= n >= 69 ? 19 : 20 when 72, 107 # 'H', 'k' - # 24-hour clock (leading space allowed) - inlined - if si < slen && str.getbyte(si) == 32 # ' ' - si += 1 - b = si < slen ? str.getbyte(si) : nil - unless b && b >= 48 && b <= 57 - hash[:_fail] = true - return -1 - end - n = b - 48 - si += 1 - else - b = si < slen ? str.getbyte(si) : nil - unless b && b >= 48 && b <= 57 - hash[:_fail] = true - return -1 - end - n = b - 48 - si += 1 - b = si < slen ? str.getbyte(si) : nil - if b && b >= 48 && b <= 57 - n = n * 10 + (b - 48) - si += 1 - end - end - if n > 24 - hash[:_fail] = true - return -1 - end + s = str_sc.scan(SP_SPACE_OR_DIGIT) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n > 24 hash[:hour] = n when 73, 108 # 'I', 'l' - # 12-hour clock (leading space allowed) - inlined - if si < slen && str.getbyte(si) == 32 # ' ' - si += 1 - b = si < slen ? str.getbyte(si) : nil - unless b && b >= 48 && b <= 57 - hash[:_fail] = true - return -1 - end - n = b - 48 - si += 1 - else - b = si < slen ? str.getbyte(si) : nil - unless b && b >= 48 && b <= 57 - hash[:_fail] = true - return -1 - end - n = b - 48 - si += 1 - b = si < slen ? str.getbyte(si) : nil - if b && b >= 48 && b <= 57 - n = n * 10 + (b - 48) - si += 1 - end - end - if n < 1 || n > 12 - hash[:_fail] = true - return -1 - end + s = str_sc.scan(SP_SPACE_OR_DIGIT) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n < 1 || n > 12 hash[:hour] = n when 106 # 'j' - # Day of year (3-digit) - n, l = _sp_digits(str, si, slen, 3) - if l == 0 || n < 1 || n > 366 - hash[:_fail] = true - return -1 - end - si += l + s = str_sc.scan(SP_DIGITS_3) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n < 1 || n > 366 hash[:yday] = n when 76 # 'L' - # Milliseconds: greedy unless next spec is numeric - sb = si < slen ? str.getbyte(si) : nil - if sb == 43 || sb == 45 # '+' or '-' - sign = sb == 45 ? -1 : 1 - si += 1 + if str_sc.scan(SP_SIGN) + sign = str_sc.matched == '-' ? -1 : 1 else sign = 1 end - osi = si - w = _sp_num_p_b?(fmt, fi, flen) ? 3 : 10000 - n, l = _sp_digits(str, si, slen, w) - if l == 0 - hash[:_fail] = true - return -1 - end - si += l + osi = str_sc.pos + num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) + s = str_sc.scan(num_next ? SP_DIGITS_3 : SP_DIGITS_MAX) + throw(:sp_fail) unless s + n = s.to_i n = -n if sign == -1 - hash[:sec_fraction] = Rational(n, 10**(si - osi)) + hash[:sec_fraction] = Rational(n, 10**(str_sc.pos - osi)) when 77 # 'M' - # Minute - inlined - b = si < slen ? str.getbyte(si) : nil - unless b && b >= 48 && b <= 57 - hash[:_fail] = true - return -1 - end - n = b - 48 - si += 1 - b = si < slen ? str.getbyte(si) : nil - if b && b >= 48 && b <= 57 - n = n * 10 + (b - 48) - si += 1 - end - if n > 59 - hash[:_fail] = true - return -1 - end + s = str_sc.scan(SP_DIGITS_2) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n > 59 hash[:min] = n when 109 # 'm' - # Month - inlined - b = si < slen ? str.getbyte(si) : nil - unless b && b >= 48 && b <= 57 - hash[:_fail] = true - return -1 - end - n = b - 48 - si += 1 - b = si < slen ? str.getbyte(si) : nil - if b && b >= 48 && b <= 57 - n = n * 10 + (b - 48) - si += 1 - end - if n < 1 || n > 12 - hash[:_fail] = true - return -1 - end + s = str_sc.scan(SP_DIGITS_2) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n < 1 || n > 12 hash[:mon] = n when 78 # 'N' - # Nanoseconds (or sub-second fraction): greedy unless next spec is numeric - sb = si < slen ? str.getbyte(si) : nil - if sb == 43 || sb == 45 # '+' or '-' - sign = sb == 45 ? -1 : 1 - si += 1 + if str_sc.scan(SP_SIGN) + sign = str_sc.matched == '-' ? -1 : 1 else sign = 1 end - osi = si - w = _sp_num_p_b?(fmt, fi, flen) ? 9 : 10000 - n, l = _sp_digits(str, si, slen, w) - if l == 0 - hash[:_fail] = true - return -1 - end - si += l + osi = str_sc.pos + num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) + s = str_sc.scan(num_next ? SP_DIGITS_9 : SP_DIGITS_MAX) + throw(:sp_fail) unless s + n = s.to_i n = -n if sign == -1 - hash[:sec_fraction] = Rational(n, 10**(si - osi)) + hash[:sec_fraction] = Rational(n, 10**(str_sc.pos - osi)) when 110, 116 # 'n', 't' - # Match any whitespace - new_si = _sp_run(str, si, ' ', hash) - return new_si if new_si < 0 - si = new_si + str_sc.pos = sp_run(str, str_sc.pos, ' ', hash) when 80, 112 # 'P', 'p' - # AM/PM with optional dot notation (A.M./P.M.) - if si >= slen - hash[:_fail] = true - return -1 - end - c0 = str.getbyte(si) - if c0 == 80 || c0 == 112 # 'P' or 'p' + throw(:sp_fail) if str_sc.eos? + c0 = str_sc.peek(1) + if c0 == 'P' || c0 == 'p' merid = 12 - elsif c0 == 65 || c0 == 97 # 'A' or 'a' + elsif c0 == 'A' || c0 == 'a' merid = 0 else - hash[:_fail] = true - return -1 + throw(:sp_fail) end - if si + 1 < slen && str.getbyte(si + 1) == 46 # '.' - # Dot notation: X.M. - if si + 3 >= slen || str.getbyte(si + 3) != 46 # '.' - hash[:_fail] = true - return -1 - end - c_m = str.getbyte(si + 2) - unless c_m == 77 || c_m == 109 # 'M' or 'm' - hash[:_fail] = true - return -1 - end - si += 4 - else - if si + 1 >= slen - hash[:_fail] = true - return -1 - end - c_m = str.getbyte(si + 1) - unless c_m == 77 || c_m == 109 # 'M' or 'm' - hash[:_fail] = true - return -1 - end - si += 2 + unless str_sc.scan(SP_AMPM_DOT) || str_sc.scan(SP_AMPM) + throw(:sp_fail) end hash[:_merid] = merid when 81 # 'Q' - # Milliseconds since Unix epoch sign = 1 - if si < slen && str.getbyte(si) == 45 # '-' + if str_sc.skip(/-/) sign = -1 - si += 1 end - n, l = _sp_digits(str, si, slen, 10000) - if l == 0 - hash[:_fail] = true - return -1 - end - si += l + s = str_sc.scan(SP_DIGITS_MAX) + throw(:sp_fail) unless s + n = s.to_i n = -n if sign == -1 hash[:seconds] = Rational(n, 1000) when 82 # 'R' - new_si = _sp_run(str, si, '%H:%M', hash) - return new_si if new_si < 0 - si = new_si + str_sc.pos = sp_run(str, str_sc.pos, '%H:%M', hash) when 114 # 'r' - new_si = _sp_run(str, si, '%I:%M:%S %p', hash) - return new_si if new_si < 0 - si = new_si + str_sc.pos = sp_run(str, str_sc.pos, '%I:%M:%S %p', hash) when 83 # 'S' - # Second (0-60 to allow leap second) - inlined - b = si < slen ? str.getbyte(si) : nil - unless b && b >= 48 && b <= 57 - hash[:_fail] = true - return -1 - end - n = b - 48 - si += 1 - b = si < slen ? str.getbyte(si) : nil - if b && b >= 48 && b <= 57 - n = n * 10 + (b - 48) - si += 1 - end - if n > 60 - hash[:_fail] = true - return -1 - end + s = str_sc.scan(SP_DIGITS_2) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n > 60 hash[:sec] = n when 115 # 's' - # Seconds since Unix epoch sign = 1 - if si < slen && str.getbyte(si) == 45 # '-' + if str_sc.skip(/-/) sign = -1 - si += 1 end - n, l = _sp_digits(str, si, slen, 10000) - if l == 0 - hash[:_fail] = true - return -1 - end - si += l + s = str_sc.scan(SP_DIGITS_MAX) + throw(:sp_fail) unless s + n = s.to_i n = -n if sign == -1 hash[:seconds] = n when 84 # 'T' - new_si = _sp_run(str, si, '%H:%M:%S', hash) - return new_si if new_si < 0 - si = new_si + str_sc.pos = sp_run(str, str_sc.pos, '%H:%M:%S', hash) when 85 # 'U' - # Week number (Sunday-based) - n, l = _sp_digits(str, si, slen, 2) - if l == 0 || n > 53 - hash[:_fail] = true - return -1 - end - si += l + s = str_sc.scan(SP_DIGITS_2) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n > 53 hash[:wnum0] = n when 117 # 'u' - # ISO weekday (1=Mon..7=Sun) - n, l = _sp_digits(str, si, slen, 1) - if l == 0 || n < 1 || n > 7 - hash[:_fail] = true - return -1 - end - si += l + s = str_sc.scan(SP_DIGITS_1) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n < 1 || n > 7 hash[:cwday] = n when 86 # 'V' - # ISO week number - n, l = _sp_digits(str, si, slen, 2) - if l == 0 || n < 1 || n > 53 - hash[:_fail] = true - return -1 - end - si += l + s = str_sc.scan(SP_DIGITS_2) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n < 1 || n > 53 hash[:cweek] = n when 118 # 'v' - new_si = _sp_run(str, si, '%e-%b-%Y', hash) - return new_si if new_si < 0 - si = new_si + str_sc.pos = sp_run(str, str_sc.pos, '%e-%b-%Y', hash) when 87 # 'W' - # Week number (Monday-based) - n, l = _sp_digits(str, si, slen, 2) - if l == 0 || n > 53 - hash[:_fail] = true - return -1 - end - si += l + s = str_sc.scan(SP_DIGITS_2) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n > 53 hash[:wnum1] = n when 119 # 'w' - # Weekday (0=Sun..6=Sat) - n, l = _sp_digits(str, si, slen, 1) - if l == 0 || n > 6 - hash[:_fail] = true - return -1 - end - si += l + s = str_sc.scan(SP_DIGITS_1) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n > 6 hash[:wday] = n when 88 # 'X' - new_si = _sp_run(str, si, '%H:%M:%S', hash) - return new_si if new_si < 0 - si = new_si + str_sc.pos = sp_run(str, str_sc.pos, '%H:%M:%S', hash) when 120 # 'x' - new_si = _sp_run(str, si, '%m/%d/%y', hash) - return new_si if new_si < 0 - si = new_si + str_sc.pos = sp_run(str, str_sc.pos, '%m/%d/%y', hash) when 89 # 'Y' - # Full year: greedy unless next spec is numeric - inlined - sb = si < slen ? str.getbyte(si) : nil - if sb == 43 || sb == 45 # '+' or '-' - sign = sb == 45 ? -1 : 1 - si += 1 + if str_sc.scan(SP_SIGN) + sign = str_sc.matched == '-' ? -1 : 1 else sign = 1 end - w = _sp_num_p_b?(fmt, fi, flen) ? 4 : 10000 - b = si < slen ? str.getbyte(si) : nil - unless b && b >= 48 && b <= 57 - hash[:_fail] = true - return -1 - end - n = b - 48 - si += 1 - l = 1 - while l < w && si < slen - b = str.getbyte(si) - break unless b && b >= 48 && b <= 57 - n = n * 10 + (b - 48) - si += 1 - l += 1 - end - hash[:year] = sign * n + num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) + s = str_sc.scan(num_next ? SP_DIGITS_4 : SP_DIGITS_MAX) + throw(:sp_fail) unless s + hash[:year] = sign * s.to_i when 121 # 'y' - # 2-digit year - inlined - b = si < slen ? str.getbyte(si) : nil - unless b && b >= 48 && b <= 57 - hash[:_fail] = true - return -1 - end - n = b - 48 - si += 1 - b = si < slen ? str.getbyte(si) : nil - if b && b >= 48 && b <= 57 - n = n * 10 + (b - 48) - si += 1 - end - if n > 99 - hash[:_fail] = true - return -1 - end + s = str_sc.scan(SP_DIGITS_2) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n > 99 hash[:year] = n hash[:_cent] ||= n >= 69 ? 19 : 20 when 90, 122 # 'Z', 'z' - new_si = _sp_zone(str, si, slen, hash) - if new_si < 0 - hash[:_fail] = true - return -1 - end - si = new_si + str_sc.pos = sp_zone(str, str_sc.pos, str.bytesize, hash) when 37 # '%' - if si >= slen || str.getbyte(si) != 37 - hash[:_fail] = true - return -1 - end - si += 1 + throw(:sp_fail) if str_sc.eos? || str_sc.peek(1) != '%' + str_sc.skip(/%/) when 43 # '+' - new_si = _sp_run(str, si, '%a %b %e %H:%M:%S %Z %Y', hash) - return new_si if new_si < 0 - si = new_si + str_sc.pos = sp_run(str, str_sc.pos, '%a %b %e %H:%M:%S %Z %Y', hash) else # Unknown spec: match '%' then spec literally - if si >= slen || str.getbyte(si) != 37 # '%' - hash[:_fail] = true - return -1 - end - si += 1 - if spec - if si >= slen || str.getbyte(si) != spec - hash[:_fail] = true - return -1 - end - si += 1 + throw(:sp_fail) if str_sc.eos? || str_sc.peek(1) != '%' + str_sc.skip(/%/) + if spec_ch + throw(:sp_fail) if str_sc.eos? || str_sc.peek(1) != spec_ch + str_sc.getch end end end - si - end - - # Case-insensitive byte-level head match. - # Compares str[si..si+len-1] against pre-computed lowercase byte array. - # Uses | 0x20 for ASCII alpha downcase (works for A-Z only). - def _sp_head_match?(str, si, slen, lower_bytes, len) - return false if si + len > slen - i = 0 - while i < len - return false if (str.getbyte(si + i) | 0x20) != lower_bytes[i] - i += 1 - end - true + str_sc.pos end # Fast path for %Y-%m-%d / %F format. - # For common "YYYY-MM-DD" format, uses byteslice+to_i (fewer method calls). - # Falls back to getbyte loop for non-standard lengths or signed years. - def _strptime_ymd(str) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + # Uses match? + byteslice to avoid StringScanner allocation overhead. + STRPTIME_YMD_EXACT = /\A\d{4}-\d{2}-\d{2}\z/ + STRPTIME_YMD_PREFIX = /\A\d{4}-\d{2}-\d{2}/ + STRPTIME_YMD_GENERAL = /\A([+-]?\d+)-(\d{1,2})-(\d{1,2})(.*)\z/m + private_constant :STRPTIME_YMD_EXACT, :STRPTIME_YMD_PREFIX, :STRPTIME_YMD_GENERAL + + def internal_strptime_ymd(str) slen = str.bytesize - # Fast path for "YYYY-MM-DD" (exactly 10 chars) or "YYYY-MM-DD..." - if slen >= 10 && str.getbyte(4) == 45 && str.getbyte(7) == 45 - b0 = str.getbyte(0) - if b0 >= 48 && b0 <= 57 # first char is digit (positive 4-digit year) - year = str.byteslice(0, 4).to_i - mon = str.byteslice(5, 2).to_i - mday = str.byteslice(8, 2).to_i - return nil if mon < 1 || mon > 12 || mday < 1 || mday > 31 + # Fast path for "YYYY-MM-DD" (exactly 10 chars) + if slen == 10 && STRPTIME_YMD_EXACT.match?(str) + year = str.byteslice(0, 4).to_i + mon = str.byteslice(5, 2).to_i + mday = str.byteslice(8, 2).to_i + return nil if mon < 1 || mon > 12 || mday < 1 || mday > 31 + return { year: year, mon: mon, mday: mday } + end + + # Medium path for "YYYY-MM-DD..." (10+ chars, standard 4-digit year with leftover) + if slen > 10 && STRPTIME_YMD_PREFIX.match?(str) + year = str.byteslice(0, 4).to_i + mon = str.byteslice(5, 2).to_i + mday = str.byteslice(8, 2).to_i + if mon >= 1 && mon <= 12 && mday >= 1 && mday <= 31 hash = { year: year, mon: mon, mday: mday } - hash[:leftover] = str.byteslice(10, slen - 10) if slen > 10 + hash[:leftover] = str.byteslice(10..) return hash end end # General path for signed years, short years, etc. - si = 0 - sign = 1 - b = str.getbyte(si) - if b == 43 # '+' - si += 1 - b = str.getbyte(si) - elsif b == 45 # '-' - sign = -1 - si += 1 - b = str.getbyte(si) - end - return nil unless b && b >= 48 && b <= 57 - year = b - 48 - si += 1 - while si < slen - b = str.getbyte(si) - break unless b && b >= 48 && b <= 57 - year = year * 10 + (b - 48) - si += 1 - end - year = -year if sign == -1 - - return nil unless si < slen && str.getbyte(si) == 45 - si += 1 - b = str.getbyte(si) - return nil unless b && b >= 48 && b <= 57 - mon = b - 48 - si += 1 - b = str.getbyte(si) - if b && b >= 48 && b <= 57 - mon = mon * 10 + (b - 48) - si += 1 - end - return nil if mon < 1 || mon > 12 - - return nil unless si < slen && str.getbyte(si) == 45 - si += 1 - b = str.getbyte(si) - return nil unless b && b >= 48 && b <= 57 - mday = b - 48 - si += 1 - b = str.getbyte(si) - if b && b >= 48 && b <= 57 - mday = mday * 10 + (b - 48) - si += 1 - end - return nil if mday < 1 || mday > 31 - + m = STRPTIME_YMD_GENERAL.match(str) + return nil unless m + year = m[1].to_i + mon = m[2].to_i + mday = m[3].to_i + return nil if mon < 1 || mon > 12 || mday < 1 || mday > 31 hash = { year: year, mon: mon, mday: mday } - hash[:leftover] = str.byteslice(si, slen - si) if si < slen + rest = m[4] + hash[:leftover] = rest unless rest.empty? hash end - # Ultra-fast path: parse %Y-%m-%d and directly create Date object. - # Skips Hash creation, _sp_complete_frags, and _sp_valid_date_frags_p entirely. + # Parse %Y-%m-%d and directly create Date object. # Returns Date object on success, nil on failure. - def _strptime_ymd_to_date(str, sg) # rubocop:disable Metrics/MethodLength + # Uses match? + byteslice to avoid StringScanner allocation overhead. + STRPTIME_YMD_GENERAL_EXACT = /\A([+-]?\d+)-(\d{1,2})-(\d{1,2})\z/ + private_constant :STRPTIME_YMD_GENERAL_EXACT + + def internalinternal_strptime_ymd_to_date(str, sg) slen = str.bytesize - # Ultra-fast path for exactly "YYYY-MM-DD" (10 chars, positive 4-digit year) - if slen == 10 && str.getbyte(4) == 45 && str.getbyte(7) == 45 - b0 = str.getbyte(0) - if b0 >= 48 && b0 <= 57 - year = str.byteslice(0, 4).to_i - mon = str.byteslice(5, 2).to_i - mday = str.byteslice(8, 2).to_i - if mon >= 1 && mon <= 12 && mday >= 1 && mday <= 31 - # Inline civil validation + JD - if sg != Float::INFINITY - dim = DAYS_IN_MONTH_GREGORIAN[mon] - if mon == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) - dim = 29 - end - return nil if mday > dim - gy = mon <= 2 ? year - 1 : year - gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[mon] + mday - a = gy / 100 - gjd = gjd_base - 1524 + 2 - a + a / 4 - jd = gjd >= sg ? gjd : gjd_base - 1524 - return new_from_jd(jd, sg) - else - jd = internal_valid_civil?(year, mon, mday, sg) - return jd ? new_from_jd(jd, sg) : nil + # Fast path for exactly "YYYY-MM-DD" (10 chars, positive 4-digit year) + if slen == 10 && STRPTIME_YMD_EXACT.match?(str) + year = str.byteslice(0, 4).to_i + mon = str.byteslice(5, 2).to_i + mday = str.byteslice(8, 2).to_i + if mon >= 1 && mon <= 12 && mday >= 1 && mday <= 31 + # Inline civil validation + JD + if sg != Float::INFINITY + dim = DAYS_IN_MONTH_GREGORIAN[mon] + if mon == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) + dim = 29 end + return nil if mday > dim + gy = mon <= 2 ? year - 1 : year + gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[mon] + mday + a = gy / 100 + gjd = gjd_base - 1524 + 2 - a + a / 4 + jd = gjd >= sg ? gjd : gjd_base - 1524 + return new_from_jd(jd, sg) + else + jd = internal_valid_civil?(year, mon, mday, sg) + return jd ? new_from_jd(jd, sg) : nil end - return nil end + return nil end # General path for signed years, non-standard lengths - si = 0 - sign = 1 - b = str.getbyte(si) - if b == 43 # '+' - si += 1 - b = str.getbyte(si) - elsif b == 45 # '-' - sign = -1 - si += 1 - b = str.getbyte(si) - end - return nil unless b && b >= 48 && b <= 57 - year = b - 48 - si += 1 - while si < slen - b = str.getbyte(si) - break unless b && b >= 48 && b <= 57 - year = year * 10 + (b - 48) - si += 1 - end - year = -year if sign == -1 - return nil unless si < slen && str.getbyte(si) == 45 - si += 1 - b = str.getbyte(si) - return nil unless b && b >= 48 && b <= 57 - mon = b - 48 - si += 1 - b = str.getbyte(si) - if b && b >= 48 && b <= 57 - mon = mon * 10 + (b - 48) - si += 1 - end - return nil if mon < 1 || mon > 12 - return nil unless si < slen && str.getbyte(si) == 45 - si += 1 - b = str.getbyte(si) - return nil unless b && b >= 48 && b <= 57 - mday = b - 48 - si += 1 - b = str.getbyte(si) - if b && b >= 48 && b <= 57 - mday = mday * 10 + (b - 48) - si += 1 - end - return nil if mday < 1 || mday > 31 - return nil if si < slen + m = STRPTIME_YMD_GENERAL_EXACT.match(str) + return nil unless m + year = m[1].to_i + mon = m[2].to_i + mday = m[3].to_i + return nil if mon < 1 || mon > 12 || mday < 1 || mday > 31 # Inline civil validation + JD computation - # For common Gregorian dates with valid day-of-month, compute JD directly - if sg != Float::INFINITY # Gregorian path (most common) + if sg != Float::INFINITY dim = DAYS_IN_MONTH_GREGORIAN[mon] if mon == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) dim = 29 end return nil if mday > dim - # Inline civil_to_jd for Gregorian gy = mon <= 2 ? year - 1 : year offset = GJD_MONTH_OFFSET[mon] gjd_base = (1461 * (gy + 4716)) / 4 + offset + mday @@ -961,176 +553,74 @@ def _strptime_ymd_to_date(str, sg) # rubocop:disable Metrics/MethodLength new_from_jd(jd, sg) end - # Fast path for "%a %b %d %Y" format (complex benchmark). - # Byte-level name matching + digit parsing. Zero String allocation. - def _strptime_abdy(str) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity - slen = str.bytesize - si = 0 + # Fast path for "%a %b %d %Y" format. + # Uses single regex match to avoid StringScanner allocation. + STRPTIME_ABDY_PAT = /\A([A-Za-z]{3})([A-Za-z]*) +([A-Za-z]{3})([A-Za-z]*) +(\d{1,2}) +([+-]?\d+)/ + private_constant :STRPTIME_ABDY_PAT - # Match weekday name using 3-byte key lookup - return nil if si + 2 >= slen - key = ((str.getbyte(si) | 0x20) << 16) | ((str.getbyte(si + 1) | 0x20) << 8) | (str.getbyte(si + 2) | 0x20) + def internal_strptime_abdy(str) + m = STRPTIME_ABDY_PAT.match(str) + return nil unless m + + # Validate weekday via 3-byte key lookup + key = compute_3key(m[1]) entry = ABBR_DAY_3KEY[key] return nil unless entry wday = entry[0] - full_len = entry[1] - if si + full_len <= slen && _sp_head_match?(str, si, slen, DAY_LOWER_BYTES[wday], full_len) - si += full_len - else - si += 3 + day_rest = m[2] + unless day_rest.empty? + return nil unless day_rest.length == entry[1] - 3 && day_rest.downcase == DAY_LOWER_STRS[wday][3..] end - # Expect space(s) - return nil if si >= slen || str.getbyte(si) != 32 - si += 1 - si += 1 while si < slen && str.getbyte(si) == 32 - - # Match month name using 3-byte key lookup - return nil if si + 2 >= slen - key = ((str.getbyte(si) | 0x20) << 16) | ((str.getbyte(si + 1) | 0x20) << 8) | (str.getbyte(si + 2) | 0x20) + # Validate month via 3-byte key lookup + key = compute_3key(m[3]) entry = ABBR_MONTH_3KEY[key] return nil unless entry mon = entry[0] - full_len = entry[1] - if si + full_len <= slen && _sp_head_match?(str, si, slen, MONTH_LOWER_BYTES[mon], full_len) - si += full_len - else - si += 3 + mon_rest = m[4] + unless mon_rest.empty? + return nil unless mon_rest.length == entry[1] - 3 && mon_rest.downcase == MONTH_LOWER_STRS[mon][3..] end - # Expect space(s) - return nil if si >= slen || str.getbyte(si) != 32 - si += 1 - si += 1 while si < slen && str.getbyte(si) == 32 - - # Parse day (1-2 digits) - b = str.getbyte(si) - return nil unless b && b >= 48 && b <= 57 - mday = b - 48 - si += 1 - b = str.getbyte(si) - if b && b >= 48 && b <= 57 - mday = mday * 10 + (b - 48) - si += 1 - end + mday = m[5].to_i return nil if mday < 1 || mday > 31 - - # Expect space(s) - return nil if si >= slen || str.getbyte(si) != 32 - si += 1 - si += 1 while si < slen && str.getbyte(si) == 32 - - # Parse year: optional sign + greedy digits - sign = 1 - b = str.getbyte(si) - if b == 43 # '+' - si += 1 - b = str.getbyte(si) - elsif b == 45 # '-' - sign = -1 - si += 1 - b = str.getbyte(si) - end - - return nil unless b && b >= 48 && b <= 57 - year = b - 48 - si += 1 - while si < slen - b = str.getbyte(si) - break unless b && b >= 48 && b <= 57 - year = year * 10 + (b - 48) - si += 1 - end - year = -year if sign == -1 + year = m[6].to_i hash = { year: year, mon: mon, mday: mday, wday: wday } - hash[:leftover] = str.byteslice(si, slen - si) if si < slen + post = m.post_match + hash[:leftover] = post unless post.empty? hash end - # Ultra-fast path: parse "%a %b %d %Y" and directly create Date object. - # Combines parsing + civil validation + JD computation without Hash. - def _strptime_abdy_to_date(str, sg) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity - slen = str.bytesize - si = 0 + # Parse "%a %b %d %Y" and directly create Date object. + # Uses single regex match to avoid StringScanner allocation. + def internalinternal_strptime_abdy_to_date(str, sg) + m = STRPTIME_ABDY_PAT.match(str) + return nil unless m + return nil unless m.post_match.empty? - # Match weekday name using 3-byte key lookup - return nil if si + 2 >= slen - key = ((str.getbyte(si) | 0x20) << 16) | ((str.getbyte(si + 1) | 0x20) << 8) | (str.getbyte(si + 2) | 0x20) + # Validate weekday via 3-byte key lookup + key = compute_3key(m[1]) entry = ABBR_DAY_3KEY[key] return nil unless entry - full_len = entry[1] - # Try full name first, then abbreviation - if si + full_len <= slen && _sp_head_match?(str, si, slen, DAY_LOWER_BYTES[entry[0]], full_len) - si += full_len - else - si += 3 + day_rest = m[2] + unless day_rest.empty? + return nil unless day_rest.length == entry[1] - 3 && day_rest.downcase == DAY_LOWER_STRS[entry[0]][3..] end - # Expect space(s) - return nil if si >= slen || str.getbyte(si) != 32 - si += 1 - si += 1 while si < slen && str.getbyte(si) == 32 - - # Match month name using 3-byte key lookup - return nil if si + 2 >= slen - key = ((str.getbyte(si) | 0x20) << 16) | ((str.getbyte(si + 1) | 0x20) << 8) | (str.getbyte(si + 2) | 0x20) + # Validate month via 3-byte key lookup + key = compute_3key(m[3]) entry = ABBR_MONTH_3KEY[key] return nil unless entry mon = entry[0] - full_len = entry[1] - if si + full_len <= slen && _sp_head_match?(str, si, slen, MONTH_LOWER_BYTES[mon], full_len) - si += full_len - else - si += 3 + mon_rest = m[4] + unless mon_rest.empty? + return nil unless mon_rest.length == entry[1] - 3 && mon_rest.downcase == MONTH_LOWER_STRS[mon][3..] end - # Expect space(s) - return nil if si >= slen || str.getbyte(si) != 32 - si += 1 - si += 1 while si < slen && str.getbyte(si) == 32 - - # Parse day (1-2 digits) - b = str.getbyte(si) - return nil unless b && b >= 48 && b <= 57 - mday = b - 48 - si += 1 - b = str.getbyte(si) - if b && b >= 48 && b <= 57 - mday = mday * 10 + (b - 48) - si += 1 - end + mday = m[5].to_i return nil if mday < 1 || mday > 31 - - # Expect space(s) - return nil if si >= slen || str.getbyte(si) != 32 - si += 1 - si += 1 while si < slen && str.getbyte(si) == 32 - - # Parse year: optional sign + greedy digits - sign = 1 - b = str.getbyte(si) - if b == 43 # '+' - si += 1 - b = str.getbyte(si) - elsif b == 45 # '-' - sign = -1 - si += 1 - b = str.getbyte(si) - end - return nil unless b && b >= 48 && b <= 57 - year = b - 48 - si += 1 - while si < slen - b = str.getbyte(si) - break unless b && b >= 48 && b <= 57 - year = year * 10 + (b - 48) - si += 1 - end - year = -year if sign == -1 - - # Must consume entire string - return nil if si < slen + year = m[6].to_i # Inline civil validation + JD computation if sg != Float::INFINITY @@ -1153,46 +643,33 @@ def _strptime_abdy_to_date(str, sg) # rubocop:disable Metrics/MethodLength,Metri end # Parse zone from string at position si; update hash[:zone] and hash[:offset]. - # Returns new si on success, -1 on failure. - def _sp_zone(str, si, slen, hash) + # Returns new si on success; throws :sp_fail on failure. + def sp_zone(str, si, slen, hash) m = STRPTIME_ZONE_PAT.match(str[si..]) - return -1 unless m + throw(:sp_fail) unless m zone_str = m[1] hash[:zone] = zone_str - hash[:offset] = _sp_zone_to_diff(zone_str) + hash[:offset] = sp_zone_to_diff(zone_str) si + m[0].length end # Convert a zone string to seconds offset from UTC. # Returns Integer (seconds) or Rational, or nil if unparseable. # Mirrors date_zone_to_diff() in ext/date/date_parse.c. - def _sp_zone_to_diff(zone_str) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + def sp_zone_to_diff(zone_str) # Fast path for common numeric zones len = zone_str.length - b0 = zone_str.getbyte(0) - if b0 == 43 || b0 == 45 # '+' or '-' - sign = b0 == 45 ? -1 : 1 - if len == 6 && zone_str.getbyte(3) == 58 # +HH:MM - b1 = zone_str.getbyte(1) - b2 = zone_str.getbyte(2) - b4 = zone_str.getbyte(4) - b5 = zone_str.getbyte(5) - if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b4 >= 48 && b4 <= 57 && b5 >= 48 && b5 <= 57 - h = (b1 - 48) * 10 + (b2 - 48) - m = (b4 - 48) * 10 + (b5 - 48) - return nil if h > 23 || m > 59 - return sign * (h * 3600 + m * 60) - end - elsif len == 5 # +HHMM - b1 = zone_str.getbyte(1) - b2 = zone_str.getbyte(2) - b3 = zone_str.getbyte(3) - b4 = zone_str.getbyte(4) - if b1 >= 48 && b1 <= 57 && b2 >= 48 && b2 <= 57 && b3 >= 48 && b3 <= 57 && b4 >= 48 && b4 <= 57 - return sign * ((b1 - 48) * 36000 + (b2 - 48) * 3600 + (b3 - 48) * 600 + (b4 - 48) * 60) - end + c0 = zone_str[0] + if c0 == '+' || c0 == '-' + sc = StringScanner.new(zone_str) + if sc.scan(/([+-])(\d{2}):?(\d{2})\z/) + sign = sc[1] == '-' ? -1 : 1 + h = sc[2].to_i + m = sc[3].to_i + return nil if h > 23 || m > 59 + return sign * (h * 3600 + m * 60) end - elsif len == 1 && (b0 == 90 || b0 == 122) # Z/z + elsif len == 1 && (c0 == 'Z' || c0 == 'z') return 0 elsif len <= 3 off = ZONE_TABLE[zone_str.downcase] @@ -1283,7 +760,7 @@ def _sp_zone_to_diff(zone_str) # rubocop:disable Metrics/MethodLength,Metrics/Cy # Rewrite :seconds (from %s/%Q) into jd + time components. # Offset is applied first (converts UTC epoch to local time). - def _sp_rewrite_frags(hash) + def sp_rewrite_frags(hash) seconds = hash.delete(:seconds) return hash unless seconds @@ -1305,7 +782,7 @@ def _sp_rewrite_frags(hash) # Complete partial date fragments by filling defaults from today's date. # Mirrors rt_complete_frags() in C. - def _sp_complete_frags(klass, hash) # rubocop:disable Metrics/MethodLength,Metrics/CyclomaticComplexity + def sp_complete_frags(klass, hash) # Fast path: detect :civil case (most common) without iterating all entries k = nil a = nil @@ -1423,7 +900,7 @@ def _sp_complete_frags(klass, hash) # rubocop:disable Metrics/MethodLength,Metri # Mirrors c_weeknum_to_jd() in ext/date/date_core.c: # rjd2 = JD(Jan 1) + 6 (= JD of Jan 7) # return (rjd2 - MOD((rjd2 - f + 1), 7) - 7) + 7*w + d - def _sp_weeknum_to_jd(y, w, d, f, sg) + def sp_weeknum_to_jd(y, w, d, f, sg) jd_jan7 = civil_to_jd(y, 1, 1, sg) + 6 (jd_jan7 - (jd_jan7 - f + 1) % 7 - 7) + 7 * w + d end @@ -1431,7 +908,7 @@ def _sp_weeknum_to_jd(y, w, d, f, sg) # Find the Julian Day number from the fragment hash. # Tries jd, ordinal, civil, commercial, wnum0, wnum1 in order. # Returns jd integer or nil. - def _sp_valid_date_frags_p(hash, sg) # rubocop:disable Metrics/CyclomaticComplexity + def sp_valid_date_frags_p(hash, sg) return hash[:jd] if hash[:jd] if (yday = hash[:yday]) && (year = hash[:year]) @@ -1462,7 +939,7 @@ def _sp_valid_date_frags_p(hash, sg) # rubocop:disable Metrics/CyclomaticComplex wday = 0 if !wday.nil? && wday == 7 end if wday && (week = hash[:wnum0]) && (year = hash[:year]) - jd = _sp_weeknum_to_jd(year, week, wday, 0, sg) + jd = sp_weeknum_to_jd(year, week, wday, 0, sg) return jd if jd end @@ -1472,7 +949,7 @@ def _sp_valid_date_frags_p(hash, sg) # rubocop:disable Metrics/CyclomaticComplex wday = hash[:cwday] if wday.nil? wday = (wday - 1) % 7 if wday if wday && (week = hash[:wnum1]) && (year = hash[:year]) - jd = _sp_weeknum_to_jd(year, week, wday, 1, sg) + jd = sp_weeknum_to_jd(year, week, wday, 1, sg) return jd if jd end @@ -1480,11 +957,11 @@ def _sp_valid_date_frags_p(hash, sg) # rubocop:disable Metrics/CyclomaticComplex end # Create a Date object from parsed fragment hash. - def _new_by_frags(hash, sg) + def internal_new_by_frags(hash, sg) raise Error, 'invalid date' if hash.nil? - hash = _sp_rewrite_frags(hash) - hash = _sp_complete_frags(Date, hash) - jd = _sp_valid_date_frags_p(hash, sg) + hash = sp_rewrite_frags(hash) + hash = sp_complete_frags(Date, hash) + jd = sp_valid_date_frags_p(hash, sg) raise Error, 'invalid date' if jd.nil? new_from_jd(jd, sg) end From 7e80db944823a45eeeb50df86bfbd18a1b9e1446 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 4 Mar 2026 13:32:10 +0900 Subject: [PATCH 010/144] Remove inlined civil_to_jd and other duplicated method bodies Replace 12 inlined copies of civil_to_jd computation and other duplicated method bodies (jd_to_gregorian, jd_to_commercial, days_in_month, new_from_jd) with calls to their canonical implementations. This addresses reviewer feedback that mechanical inlining made the codebase harder to maintain for humans. Changes: - Date.civil: replace inline JD calc with civil_to_jd + new_from_jd - Date.ordinal: replace inline JD calc with civil_to_jd - Date.commercial: replace inline with commercial_to_jd - Date#initialize: replace 3-way branch with civil_to_jd call - Date#yday: replace inline with civil_to_jd call - Date#>>: replace inline days_in_month/civil_to_jd/new_from_jd - Date#to_time: replace inline with jd_to_gregorian call - Date#compute_commercial: replace 47-line inline with jd_to_commercial - strptime fast paths: replace inline validation+JD with internal_valid_civil? - parse fast_new_date: replace inline Gregorian JD with internal_valid_civil? Performance (i/s, Ruby+YJIT vs C ext+YJIT): | Benchmark | C ext+YJIT | Ruby+YJIT | Ratio | |--------------------|------------|-----------|-------| | Date.new | 4,955,739 | 6,352,127 | 128% | | Date.civil | 5,129,273 | 6,013,617 | 117% | | Date.ordinal | 2,892,626 | 6,287,815 | 217% | | Date.commercial | 2,310,636 | 5,058,093 | 219% | | Date#yday | 18,071,960 |26,284,340 | 145% | | Date#cwyear | 4,386,845 |26,574,335 | 606% | | Date#cweek | 4,476,971 |26,579,913 | 594% | | Date#>>1 | 2,744,048 | 1,760,031 | 64% | | Date#next_month | 2,712,763 | 1,805,978 | 67% | | Date#to_time | 502,991 | 472,747 | 94% | | Date.strptime | 1,266,767 | 1,209,958 | 96% | Date#>> and methods using it (next_month, prev_month, next_year, prev_year) regressed ~50% due to self.class.__send__ overhead for calling private class methods from instance methods. This is an acceptable trade-off for maintainability. --- lib/date/core.rb | 140 +++++-------------------------------------- lib/date/parse.rb | 14 +---- lib/date/strptime.rb | 57 ++---------------- 3 files changed, 24 insertions(+), 187 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 886a7c02..325aa20f 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -14,14 +14,7 @@ class << self def civil(year = -4712, month = 1, day = 1, start = DEFAULT_SG) if Integer === year && Integer === month && Integer === day && month >= 1 && month <= 12 if day >= 1 && day <= 28 - gy = month > 2 ? year : year - 1 - gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[month] + day - a = gy / 100 - jd_julian = gjd_base - 1524 - gjd = jd_julian + 2 - a + a / 4 - obj = allocate - obj.__send__(:init_from_jd, gjd >= start ? gjd : jd_julian, start) - return obj + return new_from_jd(civil_to_jd(year, month, day, start), start) elsif day >= -31 dim = if month == 2 if start == Float::INFINITY @@ -34,14 +27,7 @@ def civil(year = -4712, month = 1, day = 1, start = DEFAULT_SG) end d = day < 0 ? day + dim + 1 : day if d >= 1 && d <= dim - gy = month > 2 ? year : year - 1 - gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[month] + d - a = gy / 100 - jd_julian = gjd_base - 1524 - gjd = jd_julian + 2 - a + a / 4 - obj = allocate - obj.__send__(:init_from_jd, gjd >= start ? gjd : jd_julian, start) - return obj + return new_from_jd(civil_to_jd(year, month, d, start), start) end end end @@ -178,14 +164,8 @@ def julian_leap?(year) # Related: Date.jd, Date.new. def ordinal(year = -4712, yday = 1, start = DEFAULT_SG) if Integer === year && Integer === yday && yday >= 1 && yday <= 365 - gy = year - 1 - gjd_base = (1461 * (gy + 4716)) / 4 + 429 # GJD_MONTH_OFFSET[1] + 1 - a = gy / 100 - gjd = gjd_base - 1524 + 2 - a + a / 4 - jd1 = gjd >= start ? gjd : gjd_base - 1524 - obj = allocate - obj.__send__(:init_from_jd, jd1 + yday - 1, start) - return obj + jd1 = civil_to_jd(year, 1, 1, start) + return new_from_jd(jd1 + yday - 1, start) end year = Integer(year) yday = Integer(yday) @@ -257,18 +237,8 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = DEFAULT_SG) if Integer === cwyear && Integer === cweek && Integer === cwday && cweek >= 1 && cweek <= 52 && cwday >= 1 && cwday <= 7 # ISO 8601: every year has at least 52 weeks, so weeks 1-52 are always valid. - # Inline civil_to_jd(cwyear, 1, 4, start): month=1, day=4 - gy = cwyear - 1 - gjd_base4 = (1461 * (gy + 4716)) / 4 + 432 # GJD_MONTH_OFFSET[1] + 4 - a = gy / 100 - gjd4 = gjd_base4 - 1524 + 2 - a + a / 4 - jd_jan4 = gjd4 >= start ? gjd4 : gjd_base4 - 1524 - wday_jan4 = (jd_jan4 + 1) % 7 - mon_wk1 = jd_jan4 - (wday_jan4 == 0 ? 6 : wday_jan4 - 1) - jd = mon_wk1 + (cweek - 1) * 7 + (cwday - 1) - obj = allocate - obj.__send__(:init_from_jd, jd, start) - return obj + jd = commercial_to_jd(cwyear, cweek, cwday, start) + return new_from_jd(jd, start) end cwyear = Integer(cwyear) cweek = Integer(cweek) @@ -683,18 +653,7 @@ def initialize(year = -4712, month = 1, day = 1, start = DEFAULT_SG) d = day d += dim + 1 if d < 0 if d >= 1 && d <= dim - gy = m <= 2 ? year - 1 : year - gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[m] + d - if start == Float::INFINITY - @jd = gjd_base - 1524 - elsif start == -Float::INFINITY - a = gy / 100 - @jd = gjd_base - 1524 + 2 - a + a / 4 - else - a = gy / 100 - gjd = gjd_base - 1524 + 2 - a + a / 4 - @jd = gjd >= start ? gjd : gjd_base - 1524 - end + @jd = self.class.__send__(:civil_to_jd, year, m, d, start) @sg = start @year = year @month = m @@ -852,12 +811,7 @@ def ld def yday return @yday if @yday internal_civil unless @year - # inline civil_to_jd(@year, 1, 1, @sg): month=1 (<= 2 so y-=1), day=1 - yy = @year - 1 - gjd_base = (1461 * (yy + 4716)) / 4 + 429 # GJD_MONTH_OFFSET[1](=428) + 1 - a = yy / 100 - gjd = gjd_base - 1524 + 2 - a + a / 4 - jd_jan1 = gjd >= @sg ? gjd : gjd_base - 1524 + jd_jan1 = self.class.__send__(:civil_to_jd, @year, 1, 1, @sg) val = @jd - jd_jan1 + 1 @yday = val unless frozen? val @@ -1335,29 +1289,14 @@ def >>(n) m2 = @month + n.to_i y2 = @year + (m2 - 1).div(12) m2 = (m2 - 1) % 12 + 1 - # inline days_in_month - if m2 == 2 - if @sg == Float::INFINITY - dim = y2 % 4 == 0 ? 29 : 28 - else - dim = ((y2 % 4 == 0 && y2 % 100 != 0) || y2 % 400 == 0) ? 29 : 28 - end + if @sg == Float::INFINITY + dim = self.class.__send__(:days_in_month_julian, y2, m2) else - dim = DAYS_IN_MONTH_GREGORIAN[m2] + dim = self.class.__send__(:days_in_month_gregorian, y2, m2) end d2 = @day < dim ? @day : dim - # inline civil_to_jd(y2, m2, d2, @sg) - offset = GJD_MONTH_OFFSET[m2] - yy = m2 <= 2 ? y2 - 1 : y2 - gjd_base = (1461 * (yy + 4716)) / 4 + offset + d2 - a = yy / 100 - gjd = gjd_base - 1524 + 2 - a + a / 4 - jd2 = gjd >= @sg ? gjd : gjd_base - 1524 - # inline new_from_jd - obj = self.class.allocate - obj.instance_variable_set(:@jd, jd2) - obj.instance_variable_set(:@sg, @sg) - obj + jd2 = self.class.__send__(:civil_to_jd, y2, m2, d2, @sg) + self.class.__send__(:new_from_jd, jd2, @sg) end # call-seq: @@ -1603,16 +1542,7 @@ def to_datetime # Date.new(2001, 2, 3, Date::JULIAN).to_time # => 2001-02-16 00:00:00 -0600 # def to_time - # Use Gregorian date for Time (inline jd_to_gregorian) - a = @jd + 32044 - b = (4 * a + 3) / 146097 - c = a - (146097 * b) / 4 - dd = (4 * c + 3) / 1461 - e = c - (1461 * dd) / 4 - m = (5 * e + 2) / 153 - day = e - (153 * m + 2) / 5 + 1 - month = m + 3 - 12 * (m / 10) - year = 100 * b + dd - 4800 + m / 10 + year, month, day = self.class.__send__(:jd_to_gregorian, @jd) Time.local(year, month, day) end @@ -1944,48 +1874,8 @@ def internal_civil @year = 100 * b + d - 4800 + m / 10 end - # Inline jd_to_commercial: compute and cache cwyear/cweek def compute_commercial - jd = @jd - wday_val = (jd + 1) % 7 - cwday_val = wday_val == 0 ? 7 : wday_val - thursday = jd + (4 - cwday_val) - sg = @sg - # inline jd_to_gregorian/jd_to_julian to get year only - if sg == Float::INFINITY - # Julian - c = thursday + 32082 - d = (4 * c + 3) / 1461 - e = c - (1461 * d) / 4 - m = (5 * e + 2) / 153 - y = d - 4800 + m / 10 - elsif thursday >= sg - # Gregorian - a = thursday + 32044 - b = (4 * a + 3) / 146097 - c = a - (146097 * b) / 4 - d = (4 * c + 3) / 1461 - e = c - (1461 * d) / 4 - m = (5 * e + 2) / 153 - y = 100 * b + d - 4800 + m / 10 - else - # Julian - c = thursday + 32082 - d = (4 * c + 3) / 1461 - e = c - (1461 * d) / 4 - m = (5 * e + 2) / 153 - y = d - 4800 + m / 10 - end - # inline civil_to_jd(y, 1, 4, sg): month=1 (<= 2), day=4 - yy = y - 1 - gjd_base = (1461 * (yy + 4716)) / 4 + 432 # GJD_MONTH_OFFSET[1](=428) + 4 - a2 = yy / 100 - gjd = gjd_base - 1524 + 2 - a2 + a2 / 4 - jd_jan4 = gjd >= sg ? gjd : gjd_base - 1524 - wday_jan4 = (jd_jan4 + 1) % 7 - iso_wday_jan4 = wday_jan4 == 0 ? 7 : wday_jan4 - mon_wk1 = jd_jan4 - (iso_wday_jan4 - 1) - cw = (jd - mon_wk1) / 7 + 1 + y, cw, = self.class.__send__(:jd_to_commercial, @jd, @sg) unless frozen? @cweek = cw @cwyear = y diff --git a/lib/date/parse.rb b/lib/date/parse.rb index 72f55646..7f2ffaa0 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -1511,17 +1511,9 @@ def fast_new_date(hash, sg) if y && m && d && !hash.key?(:jd) && !hash.key?(:yday) && !hash.key?(:cwyear) && !hash.key?(:wnum0) && !hash.key?(:wnum1) && !hash.key?(:seconds) - # Ultra-fast path: inline Gregorian JD for obviously valid dates - # (year > 1582 ensures JD > ITALY for any month/day; d <= 28 is always valid) - if y >= 1583 && m >= 1 && m <= 12 && d >= 1 && d <= 28 && sg <= 2299161 - gy = m <= 2 ? y - 1 : y - a = gy / 100 - new_from_jd((1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[m] + d - 1524 + 2 - a + a / 4, sg) - else - jd = internal_valid_civil?(y, m, d, sg) - raise Error, 'invalid date' if jd.nil? - new_from_jd(jd, sg) - end + jd = internal_valid_civil?(y, m, d, sg) + raise Error, 'invalid date' if jd.nil? + new_from_jd(jd, sg) else internal_new_by_frags(hash, sg) end diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index cd615b03..d905daba 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -504,23 +504,8 @@ def internalinternal_strptime_ymd_to_date(str, sg) mon = str.byteslice(5, 2).to_i mday = str.byteslice(8, 2).to_i if mon >= 1 && mon <= 12 && mday >= 1 && mday <= 31 - # Inline civil validation + JD - if sg != Float::INFINITY - dim = DAYS_IN_MONTH_GREGORIAN[mon] - if mon == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) - dim = 29 - end - return nil if mday > dim - gy = mon <= 2 ? year - 1 : year - gjd_base = (1461 * (gy + 4716)) / 4 + GJD_MONTH_OFFSET[mon] + mday - a = gy / 100 - gjd = gjd_base - 1524 + 2 - a + a / 4 - jd = gjd >= sg ? gjd : gjd_base - 1524 - return new_from_jd(jd, sg) - else - jd = internal_valid_civil?(year, mon, mday, sg) - return jd ? new_from_jd(jd, sg) : nil - end + jd = internal_valid_civil?(year, mon, mday, sg) + return jd ? new_from_jd(jd, sg) : nil end return nil end @@ -533,23 +518,8 @@ def internalinternal_strptime_ymd_to_date(str, sg) mday = m[3].to_i return nil if mon < 1 || mon > 12 || mday < 1 || mday > 31 - # Inline civil validation + JD computation - if sg != Float::INFINITY - dim = DAYS_IN_MONTH_GREGORIAN[mon] - if mon == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) - dim = 29 - end - return nil if mday > dim - gy = mon <= 2 ? year - 1 : year - offset = GJD_MONTH_OFFSET[mon] - gjd_base = (1461 * (gy + 4716)) / 4 + offset + mday - a = gy / 100 - gjd = gjd_base - 1524 + 2 - a + a / 4 - jd = gjd >= sg ? gjd : gjd_base - 1524 - else - jd = internal_valid_civil?(year, mon, mday, sg) - return nil unless jd - end + jd = internal_valid_civil?(year, mon, mday, sg) + return nil unless jd new_from_jd(jd, sg) end @@ -622,23 +592,8 @@ def internalinternal_strptime_abdy_to_date(str, sg) return nil if mday < 1 || mday > 31 year = m[6].to_i - # Inline civil validation + JD computation - if sg != Float::INFINITY - dim = DAYS_IN_MONTH_GREGORIAN[mon] - if mon == 2 && ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) - dim = 29 - end - return nil if mday > dim - gy = mon <= 2 ? year - 1 : year - offset = GJD_MONTH_OFFSET[mon] - gjd_base = (1461 * (gy + 4716)) / 4 + offset + mday - a = gy / 100 - gjd = gjd_base - 1524 + 2 - a + a / 4 - jd = gjd >= sg ? gjd : gjd_base - 1524 - else - jd = internal_valid_civil?(year, mon, mday, sg) - return nil unless jd - end + jd = internal_valid_civil?(year, mon, mday, sg) + return nil unless jd new_from_jd(jd, sg) end From a9255c0a4f38ee044fa1da105f710f6e20b4f050 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 7 Mar 2026 18:53:58 +0900 Subject: [PATCH 011/144] Replace Rational() method calls with rational literals for performance Replace Rational(1, 2) with 0.5r and Rational(0) with 0r across core.rb, datetime.rb, and strftime.rb. Rational literals are resolved at compile time, avoiding method dispatch overhead on every call. Note: Rational(4800001, 2) in amjd is intentionally kept as-is because 4800001/2r is parsed as Integer#/(Rational) division at runtime, which is 2x slower than the direct Rational() constructor. Benchmark (Ruby 4.0.1 +YJIT, benchmark-ips): Date.new!: Before (Rational(1,2)): 2.812M i/s (355.58 ns/i) After (0.5r): 3.596M i/s (278.11 ns/i) Improvement: +27.9% Date#day_fraction: Before (Rational(0)): 11.230M i/s (89.05 ns/i) After (0r): 29.947M i/s (33.39 ns/i) Improvement: +166.7% Micro-benchmark (literal vs method call): 0r vs Rational(0): 34.5M vs 11.3M i/s (+3.05x) 0.5r vs Rational(1,2): 34.2M vs 8.8M i/s (+3.90x) --- lib/date/core.rb | 6 +++--- lib/date/datetime.rb | 12 ++++++------ lib/date/strftime.rb | 2 +- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 325aa20f..06bebea9 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -328,7 +328,7 @@ def _load(s) def new!(ajd = 0, of = 0, sg = DEFAULT_SG) # ajd is Astronomical Julian Day (may be Rational) # Convert to integer JD and day fraction (same as C's old_to_new) - raw_jd = ajd + Rational(1, 2) + raw_jd = ajd + 0.5r jd = raw_jd.floor df = raw_jd - jd obj = allocate @@ -875,7 +875,7 @@ def cwyear # DateTime.new(2001,2,3,12).day_fraction # => (1/2) # def day_fraction - @df || Rational(0) + @df || 0r end # call-seq: @@ -1585,7 +1585,7 @@ def marshal_load(array) when 3 # Format 1.8: [ajd, of, sg] ajd, _of, sg = array - raw_jd = ajd + Rational(1, 2) + raw_jd = ajd + 0.5r jd = raw_jd.floor df = raw_jd - jd init_from_jd(jd, sg, df == 0 ? nil : df) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index fe990943..61a69d63 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -140,7 +140,7 @@ def ajd time_r = Rational(@hour * 3600 + @min * 60 + @sec_i, 86400) + Rational(@sec_frac.numerator, @sec_frac.denominator * 86400) of_r = Rational(@of, 86400) - jd_r + time_r - of_r - Rational(1, 2) + jd_r + time_r - of_r - 0.5r end # --------------------------------------------------------------------------- @@ -440,12 +440,12 @@ def marshal_load(array) when 2 jd_like, sg_or_bool = array sg = sg_or_bool == true ? ITALY : (sg_or_bool == false ? JULIAN : sg_or_bool.to_f) - _init_datetime(jd_like.to_i, 0, 0, 0, Rational(0), 0, sg) + _init_datetime(jd_like.to_i, 0, 0, 0, 0r, 0, sg) when 3 ajd, of_r, sg = array of_sec = (of_r * 86400).to_i # Reconstruct local JD and time from AJD - local_r = ajd + Rational(1, 2) + of_r + local_r = ajd + 0.5r + of_r jd = local_r.floor rem_r = (local_r - jd) * 86400 h = rem_r.to_i / 3600 @@ -857,7 +857,7 @@ def _dt_new_by_frags(hash, sg) warn("invalid offset is ignored: #{of}", uplevel: 0) of = 0 end - sf = hash[:sec_fraction] || Rational(0) + sf = hash[:sec_fraction] || 0r _new_dt_from_jd_time(jd, h, m, s, sf, of, sg) end @@ -880,7 +880,7 @@ def _split_sec(second) s_i = s_r.floor [s_i, s_r - s_i] else - [Integer(second), Rational(0)] + [Integer(second), 0r] end end @@ -932,7 +932,7 @@ def _split_second(second) s_i = s_r.floor [s_i, s_r - s_i] else - [Integer(second), Rational(0)] + [Integer(second), 0r] end end diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 65e6444c..5d66cadf 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -523,7 +523,7 @@ def internal_sec end def sec_frac - Rational(0) + 0r end def of_seconds From 1b3b1ef634b46d71391f01138f91c1f2252dc59f Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 6 Jun 2026 23:23:50 +0900 Subject: [PATCH 012/144] Address review feedback: stricter arg checks, drop debug-only methods, fix day_fraction type, shape-friendly init Implements the first batch of fixes from jeremyevans's review of PR #155(https://github.com/ruby/date/pull/155#issuecomment-4286060068). 1. Reject non-Numeric arguments (match C's check_numeric) The C extension validates constructor arguments with check_numeric and raises TypeError for non-Numeric input, while the Ruby code used Integer(), which coerces strings such as "0xa". A private check_numeric helper is now called from Date.jd, .ordinal, .commercial, the civil fallback path, and #initialize, so non-Numeric input raises Date.new(2026, "0xa") # => TypeError (was 2026-10-01) Date.new("0x7ea") # => TypeError (was 2026-01-01) Date.jd("0x258de0") # => TypeError (was 2026-04-21) 2. Remove debug-only methods Date.weeknum, Date.nth_kday, Date.new!, Date#nth_kday?, DateTime.weeknum and DateTime.nth_kday are guarded by #ifndef NDEBUG in the C extension and therefore absent from production builds. They are removed here, together with their private helpers weeknum_to_jd and nth_kday_to_jd. The corresponding tests self-skip via respond_to? guards, so the test suite is unaffected. 3. Fix Date#day_fraction return type C returns Integer 0 (INT2FIX(0)) for a simple Date without a fraction and a Rational only when a fraction is present. The Ruby code returned Rational 0r unconditionally; it now returns Integer 0 for simple dates. 4. Shape-friendly initialization Every Date instance lazily added @year/@month/@day/@yday/@cweek/@cwyear through its accessors, giving instances divergent object shapes over their lifetime. All of these ivars are now initialized to nil up front in init_from_jd, initialize_copy and DateTime#_init_datetime, so every instance of a class shares a single shape. As a side effect this fixes the previously failing test_memsize. Performance (Ruby 4.1.0dev + YJIT vs C extension baseline bench/results/20260223_r1/4.0.1_system.tsv; ips, higher is better): method C ext ips Ruby ips Ruby/C Date.civil 4,648,499 7,012,418 151% Date.civil(sg) 4,455,620 6,620,097 149% Date.civil(-1) 4,675,053 6,554,829 140% Date.civil(neg) 4,563,715 7,185,497 157% Date.jd 4,962,000 9,284,179 187% Date.ordinal 3,023,006 7,005,965 232% Date.commercial 2,478,941 6,068,962 245% Date.today 176,947 507,147 287% Overall: 113/179 methods >= 100% of C, median 120%. The shape-friendly change adds six nil ivar assignments per construction yet construction stays well above the C extension (140-287%). --- lib/date/core.rb | 134 ++++++++++++++----------------------------- lib/date/datetime.rb | 29 +++------- 2 files changed, 52 insertions(+), 111 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 06bebea9..dd48918b 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -82,6 +82,7 @@ def valid_civil?(year, month, day, start = DEFAULT_SG) # # Related: Date.new. def jd(jd = 0, start = DEFAULT_SG) + check_numeric(jd, "jd") jd = Integer(jd) obj = allocate obj.__send__(:init_from_jd, jd, start) @@ -167,6 +168,8 @@ def ordinal(year = -4712, yday = 1, start = DEFAULT_SG) jd1 = civil_to_jd(year, 1, 1, start) return new_from_jd(jd1 + yday - 1, start) end + check_numeric(yday, "yday") + check_numeric(year, "year") year = Integer(year) yday = Integer(yday) jd = internal_valid_ordinal?(year, yday, start) @@ -240,6 +243,9 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = DEFAULT_SG) jd = commercial_to_jd(cwyear, cweek, cwday, start) return new_from_jd(jd, start) end + check_numeric(cwday, "cwday") + check_numeric(cweek, "cweek") + check_numeric(cwyear, "year") cwyear = Integer(cwyear) cweek = Integer(cweek) cwday = Integer(cwday) @@ -267,40 +273,6 @@ def valid_commercial?(year, week, day, start = DEFAULT_SG) !!internal_valid_commercial?(year, week, day, start) end - # call-seq: - # Date.weeknum(year, week, wday, wstart = 0, start = Date::ITALY) -> date - def weeknum(year = -4712, week = 0, wday = 1, wstart = 0, start = DEFAULT_SG) - year = Integer(year) - week = Integer(week) - wday = Integer(wday) - wstart = Integer(wstart) - # Validate wday range - raise Date::Error, "invalid date" unless wday >= 0 && wday <= 6 - # Validate week: reconstruct and check round-trip - jd = weeknum_to_jd(year, week, wday, wstart, start) - # Verify the resulting date is in the same year (week must be valid) - y2, = jd_to_civil(jd, start) - raise Date::Error, "invalid date" if y2 != year - new_from_jd(jd, start) - end - - # call-seq: - # Date.nth_kday(year, month, n, k, start = Date::ITALY) -> date - def nth_kday(year = -4712, month = 1, n = 1, k = 1, start = DEFAULT_SG) - year = Integer(year) - month = Integer(month) - n = Integer(n) - k = Integer(k) - raise Date::Error, "invalid date" unless month >= 1 && month <= 12 - raise Date::Error, "invalid date" unless k >= 0 && k <= 6 - raise Date::Error, "invalid date" if n == 0 - jd = nth_kday_to_jd(year, month, n, k, start) - # Verify the result is in the same month - y2, m2, = jd_to_civil(jd, start) - raise Date::Error, "invalid date" if y2 != year || m2 != month - new_from_jd(jd, start) - end - # call-seq: # Date.today(start = Date::ITALY) -> date # @@ -324,21 +296,21 @@ def _load(s) obj end - # :nodoc: - def new!(ajd = 0, of = 0, sg = DEFAULT_SG) - # ajd is Astronomical Julian Day (may be Rational) - # Convert to integer JD and day fraction (same as C's old_to_new) - raw_jd = ajd + 0.5r - jd = raw_jd.floor - df = raw_jd - jd - obj = allocate - obj.__send__(:init_from_jd, jd, sg, df == 0 ? nil : df) - obj - end - private + # Reject non-Numeric arguments, mirroring C's check_numeric. + # The C extension uses NUM2INT/check_numeric and raises TypeError for + # non-Numeric input, whereas Integer() would coerce strings like "0xa". + def check_numeric(obj, field) + unless Numeric === obj + raise TypeError, "invalid #{field} (not numeric)" + end + end + def civil_fallback(year, month, day, start) + check_numeric(day, "day") + check_numeric(month, "month") + check_numeric(year, "year") year = Integer(year) month = Integer(month) day = Integer(day) @@ -491,37 +463,6 @@ def jd_to_commercial(jd, sg = -Float::INFINITY) [y, cweek, cwday] end - # Weeknum (year, week, wday, week_start, sg) -> JD - # week_start: 0=Sun-based (%U), 1=Mon-based (%W) - def weeknum_to_jd(y, w, d, ws, sg = -Float::INFINITY) - jd_jan1 = civil_to_jd(y, 1, 1, sg) - wday_jan1 = (jd_jan1 + 1) % 7 # 0=Sun - j = jd_jan1 - wday_jan1 - j += 1 if ws == 1 - j + 7 * w + d - end - - # n-th k-day (nth occurrence of weekday k in year y, month m) -> JD - # k: 0=Sun..6=Sat, n: positive from beginning, negative from end - def nth_kday_to_jd(y, m, n, k, sg) - if n > 0 - jd_m1 = civil_to_jd(y, m, 1, sg) - wday = (jd_m1 + 1) % 7 - diff = (k - wday + 7) % 7 - jd_m1 + diff + (n - 1) * 7 - else - # Last day of month - if m == 12 - jd_last = civil_to_jd(y + 1, 1, 1, sg) - 1 - else - jd_last = civil_to_jd(y, m + 1, 1, sg) - 1 - end - wday = (jd_last + 1) % 7 - diff = (wday - k + 7) % 7 - jd_last - diff + (n + 1) * 7 - end - end - # --------------------------------------------------------------------------- # Validation helpers # --------------------------------------------------------------------------- @@ -663,6 +604,9 @@ def initialize(year = -4712, month = 1, day = 1, start = DEFAULT_SG) end raise Date::Error, "invalid date" end + self.class.__send__(:check_numeric, day, "day") + self.class.__send__(:check_numeric, month, "month") + self.class.__send__(:check_numeric, year, "year") year = Integer(year) month = Integer(month) day = Integer(day) @@ -875,7 +819,9 @@ def cwyear # DateTime.new(2001,2,3,12).day_fraction # => (1/2) # def day_fraction - @df || 0r + # C returns Integer 0 (INT2FIX(0)) for a simple Date without a fraction, + # and a Rational only when a day fraction is present. + @df || 0 end # call-seq: @@ -1023,13 +969,6 @@ def saturday? wday == 6 end - # :nodoc: - def nth_kday?(n, k) - return false if k != wday - jd_ref = self.class.__send__(:nth_kday_to_jd, year, month, n, k, @sg) - jd_ref == @jd - end - # --------------------------------------------------------------------------- # Comparison # --------------------------------------------------------------------------- @@ -1552,12 +1491,17 @@ def to_time # :nodoc: def initialize_copy(other) - @jd = other.instance_variable_get(:@jd) - @sg = other.instance_variable_get(:@sg) - @df = other.instance_variable_get(:@df) - @year = other.instance_variable_get(:@year) - @month = other.instance_variable_get(:@month) - @day = other.instance_variable_get(:@day) + # Assign every ivar in the canonical order so copies share the same shape + # as freshly constructed instances (see init_from_jd). + @jd = other.instance_variable_get(:@jd) + @sg = other.instance_variable_get(:@sg) + @df = other.instance_variable_get(:@df) + @year = other.instance_variable_get(:@year) + @month = other.instance_variable_get(:@month) + @day = other.instance_variable_get(:@day) + @yday = other.instance_variable_get(:@yday) + @cweek = other.instance_variable_get(:@cweek) + @cwyear = other.instance_variable_get(:@cwyear) end # :nodoc: @@ -1850,6 +1794,14 @@ def init_from_jd(jd, sg, df = nil) @jd = jd @sg = sg @df = df + # Initialize all lazily-computed ivars up front so every Date instance + # shares a single object shape regardless of which accessors are called. + @year = nil + @month = nil + @day = nil + @yday = nil + @cweek = nil + @cwyear = nil end def internal_civil diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 61a69d63..14af96e5 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -645,26 +645,6 @@ def now(start = Date::ITALY) _new_dt_from_jd_time(jd, t.hour, t.min, t.sec, sec_f, t.utc_offset, start) end - # call-seq: - # DateTime.weeknum(year=-4712, week=0, wday=1, wstart=0, hour=0, min=0, sec=0, offset=0, start=Date::ITALY) -> datetime - def weeknum(year = -4712, week = 0, wday = 1, wstart = 0, - hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) - jd = weeknum_to_jd(Integer(year), Integer(week), Integer(wday), Integer(wstart), start) - of_sec = _parse_of(offset) - sec_i, sec_f = _split_sec(second) - _new_dt_from_jd_time(jd, Integer(hour), Integer(minute), sec_i, sec_f, of_sec, start) - end - - # call-seq: - # DateTime.nth_kday(year=-4712, month=1, n=1, k=1, hour=0, min=0, sec=0, offset=0, start=Date::ITALY) -> datetime - def nth_kday(year = -4712, month = 1, n = 1, k = 1, - hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) - jd = nth_kday_to_jd(Integer(year), Integer(month), Integer(n), Integer(k), start) - of_sec = _parse_of(offset) - sec_i, sec_f = _split_sec(second) - _new_dt_from_jd_time(jd, Integer(hour), Integer(minute), sec_i, sec_f, of_sec, start) - end - # :nodoc: def _new_dt_from_jd_time(jd, h, m, s, sf, of, sg) jd, h, m, s = _normalize_hms(jd, h, m, s) @@ -919,11 +899,20 @@ def zone_str def _init_datetime(jd, h, m, s, sf, of, sg) @jd = jd @sg = sg + @df = nil @hour = h @min = m @sec_i = s @sec_frac = sf.is_a?(Rational) ? sf : Rational(sf) @of = of.to_i + # Initialize lazily-computed (inherited from Date) ivars up front so every + # DateTime instance shares a single object shape. + @year = nil + @month = nil + @day = nil + @yday = nil + @cweek = nil + @cwyear = nil end def _split_second(second) From fd03c6fdbd9aed2a2f776a19eabaff7c6269ae20 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 6 Jun 2026 23:40:06 +0900 Subject: [PATCH 013/144] Inline idiv helper and remove unused Date#initialize Continues addressing jeremyevans's review of PR #155. * Inline the idiv private helper idiv(a, b) was a thin wrapper around a.div(b) (floor division). Per the review it is not worth a dedicated method, so its twelve call sites in jd_to_gregorian and jd_to_julian are replaced with direct (expr).div(n) calls and the helper is removed. Integer#div performs floor division identically for negative operands, so the behavior is unchanged (verified across a wide jd range and historical boundaries such as the 1582-10-15 Gregorian reform). * Remove unused Date#initialize Date.new is overridden to delegate to Date.civil, which constructs via allocate + init_from_jd, so Date#initialize was never reached. DateTime defines its own #initialize and does not call super, and no test invokes Date#initialize directly. The dead method is removed; its Date.new call-seq documentation is moved onto the Date.new singleton method so the generated docs are unaffected. Construction now funnels solely through civil -> new_from_jd -> init_from_jd. No behavior change. Full test suite passes (the two remaining errors, test_string_argument and test_strftime__offset, are pre-existing Test::Unit helper gaps unrelated to these changes). --- lib/date/core.rb | 117 ++++++++++++++--------------------------------- 1 file changed, 35 insertions(+), 82 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index dd48918b..217a138a 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -34,6 +34,27 @@ def civil(year = -4712, month = 1, day = 1, start = DEFAULT_SG) civil_fallback(year, month, day, start) end + # call-seq: + # Date.new(year = -4712, month = 1, mday = 1, start = Date::ITALY) -> date + # + # Returns a new \Date object constructed from the given arguments: + # + # Date.new(2022).to_s # => "2022-01-01" + # Date.new(2022, 2).to_s # => "2022-02-01" + # Date.new(2022, 2, 4).to_s # => "2022-02-04" + # + # Argument +month+ should be in range (1..12) or range (-12..-1); + # when the argument is negative, counts backward from the end of the year: + # + # Date.new(2022, -11, 4).to_s # => "2022-02-04" + # + # Argument +mday+ should be in range (1..n) or range (-n..-1) + # where +n+ is the number of days in the month; + # when the argument is negative, counts backward from the end of the month. + # + # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. + # + # Related: Date.jd. def new(year = -4712, month = 1, day = 1, start = DEFAULT_SG) civil(year, month, day, start) end @@ -323,11 +344,6 @@ def civil_fallback(year, month, day, start) # Internal calendar arithmetic (pure Ruby, no C dependency) # --------------------------------------------------------------------------- - # Floor division that works correctly for negative numbers. - def idiv(a, b) - a.div(b) - end - # Gregorian leap year? def internal_gregorian_leap?(y) (y % 4 == 0 && y % 100 != 0) || y % 400 == 0 @@ -391,26 +407,26 @@ def civil_to_jd(y, m, d, sg) # Gregorian JD -> (year, month, day) def jd_to_gregorian(jd) a = jd + 32044 - b = idiv(4 * a + 3, 146097) - c = a - idiv(146097 * b, 4) - d = idiv(4 * c + 3, 1461) - e = c - idiv(1461 * d, 4) - m = idiv(5 * e + 2, 153) - day = e - idiv(153 * m + 2, 5) + 1 - mon = m + 3 - 12 * idiv(m, 10) - year = 100 * b + d - 4800 + idiv(m, 10) + b = (4 * a + 3).div(146097) + c = a - (146097 * b).div(4) + d = (4 * c + 3).div(1461) + e = c - (1461 * d).div(4) + m = (5 * e + 2).div(153) + day = e - (153 * m + 2).div(5) + 1 + mon = m + 3 - 12 * m.div(10) + year = 100 * b + d - 4800 + m.div(10) [year, mon, day] end # Julian JD -> (year, month, day) def jd_to_julian(jd) c = jd + 32082 - d = idiv(4 * c + 3, 1461) - e = c - idiv(1461 * d, 4) - m = idiv(5 * e + 2, 153) - day = e - idiv(153 * m + 2, 5) + 1 - mon = m + 3 - 12 * idiv(m, 10) - year = d - 4800 + idiv(m, 10) + d = (4 * c + 3).div(1461) + e = c - (1461 * d).div(4) + m = (5 * e + 2).div(153) + day = e - (153 * m + 2).div(5) + 1 + mon = m + 3 - 12 * m.div(10) + year = d - 4800 + m.div(10) [year, mon, day] end @@ -552,69 +568,6 @@ def offset_str_to_sec(str) end - # --------------------------------------------------------------------------- - # Initializer - # --------------------------------------------------------------------------- - - # call-seq: - # Date.new(year = -4712, month = 1, mday = 1, start = Date::ITALY) -> date - # - # Returns a new \Date object constructed from the given arguments: - # - # Date.new(2022).to_s # => "2022-01-01" - # Date.new(2022, 2).to_s # => "2022-02-01" - # Date.new(2022, 2, 4).to_s # => "2022-02-04" - # - # Argument +month+ should be in range (1..12) or range (-12..-1); - # when the argument is negative, counts backward from the end of the year: - # - # Date.new(2022, -11, 4).to_s # => "2022-02-04" - # - # Argument +mday+ should be in range (1..n) or range (-n..-1) - # where +n+ is the number of days in the month; - # when the argument is negative, counts backward from the end of the month. - # - # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - # - # Related: Date.jd. - def initialize(year = -4712, month = 1, day = 1, start = DEFAULT_SG) - if Integer === year && Integer === month && Integer === day - m = month - m += 13 if m < 0 - if m >= 1 && m <= 12 - dim = if m == 2 - if start == Float::INFINITY - year % 4 == 0 ? 29 : 28 - else - (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 29 : 28 - end - else - DAYS_IN_MONTH_GREGORIAN[m] - end - d = day - d += dim + 1 if d < 0 - if d >= 1 && d <= dim - @jd = self.class.__send__(:civil_to_jd, year, m, d, start) - @sg = start - @year = year - @month = m - @day = d - return - end - end - raise Date::Error, "invalid date" - end - self.class.__send__(:check_numeric, day, "day") - self.class.__send__(:check_numeric, month, "month") - self.class.__send__(:check_numeric, year, "year") - year = Integer(year) - month = Integer(month) - day = Integer(day) - jd = self.class.__send__(:internal_valid_civil?, year, month, day, start) - raise Date::Error, "invalid date" unless jd - init_from_jd(jd, start) - end - # --------------------------------------------------------------------------- # Instance methods - basic attributes # --------------------------------------------------------------------------- From 997de16f987a7f1a7eb24dee149db6e4c2785df3 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 7 Jun 2026 00:08:11 +0900 Subject: [PATCH 014/144] Delegate comparison to Comparable, simplify deconstruct_keys, drop yday/cweek/cwyear caching Continues addressing jeremyevans's review of PR #155. * Delegate #<, #>, #== to Comparable The C extension includes Comparable and defines only #<=> and #===, so #<, #>, #==, #<=, #>= all come from Comparable. The Ruby code additionally defined explicit #<, #>, #== whose error paths diverged from the C behavior. They are removed, leaving #<=> (and #===, #eql?, #hash) as the basis. A characterization test confirms every successful comparison and every #== result is unchanged; only the ArgumentError message for an uncomparable operand changes to Comparable's wording ("... failed: comparator returned nil"), which now matches the C extension. * Simplify Date#/DateTime#deconstruct_keys Call the accessor methods (year, month, day, wday, yday and, for DateTime, hour, min, sec, sec_fraction, zone) instead of inlining ivar reads and repeating "internal_civil unless @year". Behavior, including pattern matching and frozen instances, is unchanged. * Stop caching yday/cweek/cwyear The C extension caches only year/mon/mday in its struct and recomputes yday, cweek and cwyear on every access. The Ruby code now does the same: the @yday/@cweek/@cwyear ivars and their "unless frozen?" cache writes are removed, and compute_commercial is a pure computation. This drops the per-instance ivar count (Date 9 -> 6, DateTime 14 -> 11) while keeping a single shared object shape, and removes the frozen-instance special cases. No behavior change other than the Comparable error-message alignment noted above. Full test suite passes (the two remaining errors, test_string_argument and test_strftime__offset, are pre-existing Test::Unit helper gaps unrelated to these changes). --- lib/date/core.rb | 92 +++++++++----------------------------------- lib/date/datetime.rb | 55 +++++++++++--------------- 2 files changed, 41 insertions(+), 106 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 217a138a..56c20379 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -706,12 +706,9 @@ def ld # Date.new(2001, 2, 3).yday # => 34 # def yday - return @yday if @yday internal_civil unless @year jd_jan1 = self.class.__send__(:civil_to_jd, @year, 1, 1, @sg) - val = @jd - jd_jan1 + 1 - @yday = val unless frozen? - val + @jd - jd_jan1 + 1 end # call-seq: @@ -748,7 +745,7 @@ def cwday # Date.new(2001, 2, 3).cweek # => 5 # def cweek - @cweek || compute_commercial[1] + compute_commercial[1] end # call-seq: @@ -761,7 +758,7 @@ def cweek # Date.new(2000, 1, 1).cwyear # => 1999 # def cwyear - @cwyear || compute_commercial[0] + compute_commercial[0] end # call-seq: @@ -976,44 +973,8 @@ def <=>(other) end end - def <(other) - case other - when Date - d = @jd <=> other.jd - d != 0 ? d < 0 : day_fraction < other.day_fraction - when Numeric - r = ajd <=> other - raise ArgumentError, "comparison of #{self.class} with #{other.class} failed" if r.nil? - r < 0 - else - raise ArgumentError, "comparison of #{self.class} with #{other.class} failed" - end - end - - def >(other) - case other - when Date - d = @jd <=> other.jd - d != 0 ? d > 0 : day_fraction > other.day_fraction - when Numeric - r = ajd <=> other - raise ArgumentError, "comparison of #{self.class} with #{other.class} failed" if r.nil? - r > 0 - else - raise ArgumentError, "comparison of #{self.class} with #{other.class} failed" - end - end - - def ==(other) - case other - when Date - @jd == other.jd && day_fraction == other.day_fraction - when Numeric - ajd == other - else - false - end - end + # #<, #>, #==, #<=, #>= are all provided by Comparable via #<=>, matching + # the C extension, which includes Comparable and defines only #<=> and #===. def eql?(other) other.is_a?(Date) && @jd == other.jd && day_fraction == other.day_fraction @@ -1452,9 +1413,6 @@ def initialize_copy(other) @year = other.instance_variable_get(:@year) @month = other.instance_variable_get(:@month) @day = other.instance_variable_get(:@day) - @yday = other.instance_variable_get(:@yday) - @cweek = other.instance_variable_get(:@cweek) - @cwyear = other.instance_variable_get(:@cwyear) end # :nodoc: @@ -1536,36 +1494,28 @@ def deconstruct_keys(keys) if keys if keys.size == 1 case keys[0] - when :year - internal_civil unless @year - { year: @year } - when :month - internal_civil unless @year - { month: @month } - when :day - internal_civil unless @year - { day: @day } - when :wday then { wday: (@jd + 1) % 7 } + when :year then { year: year } + when :month then { month: month } + when :day then { day: day } + when :wday then { wday: wday } when :yday then { yday: yday } else {} end else - internal_civil unless @year h = {} keys.each do |k| case k - when :year then h[:year] = @year - when :month then h[:month] = @month - when :day then h[:day] = @day - when :wday then h[:wday] = (@jd + 1) % 7 + when :year then h[:year] = year + when :month then h[:month] = month + when :day then h[:day] = day + when :wday then h[:wday] = wday when :yday then h[:yday] = yday end end h end else - internal_civil unless @year - { year: @year, month: @month, day: @day, wday: (@jd + 1) % 7, yday: yday } + { year: year, month: month, day: day, wday: wday, yday: yday } end end @@ -1747,14 +1697,12 @@ def init_from_jd(jd, sg, df = nil) @jd = jd @sg = sg @df = df - # Initialize all lazily-computed ivars up front so every Date instance - # shares a single object shape regardless of which accessors are called. + # Initialize the lazily-computed civil ivars up front so every Date + # instance shares a single object shape regardless of which accessors + # are called. (yday/cweek/cwyear are not cached; see #yday/#cweek.) @year = nil @month = nil @day = nil - @yday = nil - @cweek = nil - @cwyear = nil end def internal_civil @@ -1779,12 +1727,10 @@ def internal_civil @year = 100 * b + d - 4800 + m / 10 end + # Compute [cwyear, cweek] from the Julian Day. Not cached, matching the + # C extension, which recomputes commercial fields on each access. def compute_commercial y, cw, = self.class.__send__(:jd_to_commercial, @jd, @sg) - unless frozen? - @cweek = cw - @cwyear = y - end [y, cw] end diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 14af96e5..5d0b2eac 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -355,47 +355,39 @@ def deconstruct_keys(keys) if keys if keys.size == 1 case keys[0] - when :year - internal_civil unless @year - { year: @year } - when :month - internal_civil unless @year - { month: @month } - when :day - internal_civil unless @year - { day: @day } - when :wday then { wday: (@jd + 1) % 7 } + when :year then { year: year } + when :month then { month: month } + when :day then { day: day } + when :wday then { wday: wday } when :yday then { yday: yday } - when :hour then { hour: @hour } - when :min then { min: @min } - when :sec then { sec: @sec_i } - when :sec_fraction then { sec_fraction: @sec_frac } - when :zone then { zone: _of2str(@of) } + when :hour then { hour: hour } + when :min then { min: min } + when :sec then { sec: sec } + when :sec_fraction then { sec_fraction: sec_fraction } + when :zone then { zone: zone } else {} end else - internal_civil unless @year h = {} keys.each do |k| case k - when :year then h[:year] = @year - when :month then h[:month] = @month - when :day then h[:day] = @day - when :wday then h[:wday] = (@jd + 1) % 7 + when :year then h[:year] = year + when :month then h[:month] = month + when :day then h[:day] = day + when :wday then h[:wday] = wday when :yday then h[:yday] = yday - when :hour then h[:hour] = @hour - when :min then h[:min] = @min - when :sec then h[:sec] = @sec_i - when :sec_fraction then h[:sec_fraction] = @sec_frac - when :zone then h[:zone] = _of2str(@of) + when :hour then h[:hour] = hour + when :min then h[:min] = min + when :sec then h[:sec] = sec + when :sec_fraction then h[:sec_fraction] = sec_fraction + when :zone then h[:zone] = zone end end h end else - internal_civil unless @year - { year: @year, month: @month, day: @day, wday: (@jd + 1) % 7, yday: yday, - hour: @hour, min: @min, sec: @sec_i, sec_fraction: @sec_frac, zone: _of2str(@of) } + { year: year, month: month, day: day, wday: wday, yday: yday, + hour: hour, min: min, sec: sec, sec_fraction: sec_fraction, zone: zone } end end @@ -905,14 +897,11 @@ def _init_datetime(jd, h, m, s, sf, of, sg) @sec_i = s @sec_frac = sf.is_a?(Rational) ? sf : Rational(sf) @of = of.to_i - # Initialize lazily-computed (inherited from Date) ivars up front so every - # DateTime instance shares a single object shape. + # Initialize lazily-computed (inherited from Date) civil ivars up front so + # every DateTime instance shares a single object shape. @year = nil @month = nil @day = nil - @yday = nil - @cweek = nil - @cwyear = nil end def _split_second(second) From e2698eabbb22e532fa38a7ae58576d5d9ad6a462 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 7 Jun 2026 00:24:58 +0900 Subject: [PATCH 015/144] Access day fraction via #day_fraction instead of @df in Date Continues addressing jeremyevans's review of PR #155. Per the review, Date logic should call #day_fraction rather than reading the @df ivar directly. The computational call sites now do so: * #ajd : `@df ? r + @df : r` -> `r + day_fraction` * #+ (Numeric) : `r + (@df || 0)` -> `r + day_fraction` * #- (Date) : `... + (@df || 0) - other.day_fraction` -> `... + day_fraction - other.day_fraction` * #- (Numeric) : `(@df || 0) - r` -> `day_fraction - r` These methods are overridden by DateTime, so they run only on plain Date instances, where #day_fraction returns `@df || 0`; the rewrite is therefore behavior-preserving. @df is kept as the storage for complex (fractional) Date instances, which the C extension also supports (Date + Rational/Float returns a fractional Date via d_complex_new_internal). The remaining @df references are all storage operations: the #day_fraction accessor itself, the df argument passed through in #+/#- , initialize_copy, marshal_dump, and init_from_jd. No behavior change: fractional Date arithmetic, #ajd, simple-date complex dates are unchanged. Full test suite passes (the two remaining errors, test_string_argument and test_strftime__offset, are pre-existing Test::Unit helper gaps unrelated to these changes). --- lib/date/core.rb | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 56c20379..6393b6bb 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -657,7 +657,7 @@ def start # DateTime.new(2001,2,2,14,5,6,'-7').ajd #=> (11769328217/4800) def ajd r = Rational(@jd * 2 - 1, 2) - @df ? r + @df : r + r + day_fraction end # call-seq: @@ -1061,7 +1061,7 @@ def +(other) when Numeric r = other.to_r raise TypeError, "#{other.class} can't be coerced into Integer" unless r.is_a?(Rational) - total = r + (@df || 0) + total = r + day_fraction days = total.floor frac = total - days self.class.__send__(:new_from_jd, @jd + days, @sg, frac == 0 ? nil : frac) @@ -1090,7 +1090,7 @@ def +(other) def -(other) case other when Date - Rational(@jd - other.jd) + (@df || 0) - other.day_fraction + Rational(@jd - other.jd) + day_fraction - other.day_fraction when Integer if instance_of?(Date) obj = Date.allocate @@ -1103,7 +1103,7 @@ def -(other) when Numeric r = other.to_r raise TypeError, "#{other.class} can't be coerced into Integer" unless r.is_a?(Rational) - total = (@df || 0) - r + total = day_fraction - r days = total.floor frac = total - days self.class.__send__(:new_from_jd, @jd + days, @sg, frac == 0 ? nil : frac) From a5391109e5d88c36afd582440da3602f75858758 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 7 Jun 2026 00:48:22 +0900 Subject: [PATCH 016/144] Rename @sg/@df ivars to @start/@day_fraction Per jeremyevans's review of PR #155, replace the C-derived abbreviated instance variable names with names matching their public accessors: * @sg -> @start (the #start method) * @df -> @day_fraction (the #day_fraction method) This is a pure rename across core.rb and datetime.rb, including the :@sg/:@df symbol forms used with instance_variable_get/set. Marshal is unaffected (it uses a positional array format, not ivar names) and no test depends on the ivar names. Assignment alignment was tidied accordingly. --- lib/date/core.rb | 88 ++++++++++++++++++++++---------------------- lib/date/datetime.rb | 38 +++++++++---------- 2 files changed, 63 insertions(+), 63 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 6393b6bb..6937d9d7 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -644,7 +644,7 @@ def jd # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # def start - @sg + @start end # call-seq: @@ -707,7 +707,7 @@ def ld # def yday internal_civil unless @year - jd_jan1 = self.class.__send__(:civil_to_jd, @year, 1, 1, @sg) + jd_jan1 = self.class.__send__(:civil_to_jd, @year, 1, 1, @start) @jd - jd_jan1 + 1 end @@ -771,7 +771,7 @@ def cwyear def day_fraction # C returns Integer 0 (INT2FIX(0)) for a simple Date without a fraction, # and a Rational only when a day fraction is present. - @df || 0 + @day_fraction || 0 end # call-seq: @@ -784,7 +784,7 @@ def day_fraction # def leap? internal_civil unless @year - if @jd < @sg # julian? + if @jd < @start # julian? @year % 4 == 0 else (@year % 4 == 0 && @year % 100 != 0) || @year % 400 == 0 @@ -801,7 +801,7 @@ def leap? # (Date.new(1582, 10, 15) - 1).gregorian? # => false # def gregorian? - jd >= @sg + jd >= @start end # call-seq: @@ -832,7 +832,7 @@ def julian? def new_start(start = DEFAULT_SG) obj = self.class.allocate obj.instance_variable_set(:@jd, @jd) - obj.instance_variable_set(:@sg, start) + obj.instance_variable_set(:@start, start) obj end @@ -981,7 +981,7 @@ def eql?(other) end def hash - [@jd, @sg].hash + [@jd, @start].hash end # call-seq: @@ -1053,10 +1053,10 @@ def +(other) if instance_of?(Date) obj = Date.allocate obj.instance_variable_set(:@jd, @jd + other) - obj.instance_variable_set(:@sg, @sg) + obj.instance_variable_set(:@start, @start) obj else - self.class.__send__(:new_from_jd, @jd + other, @sg, @df) + self.class.__send__(:new_from_jd, @jd + other, @start, @day_fraction) end when Numeric r = other.to_r @@ -1064,7 +1064,7 @@ def +(other) total = r + day_fraction days = total.floor frac = total - days - self.class.__send__(:new_from_jd, @jd + days, @sg, frac == 0 ? nil : frac) + self.class.__send__(:new_from_jd, @jd + days, @start, frac == 0 ? nil : frac) else raise TypeError, "expected numeric" end @@ -1095,10 +1095,10 @@ def -(other) if instance_of?(Date) obj = Date.allocate obj.instance_variable_set(:@jd, @jd - other) - obj.instance_variable_set(:@sg, @sg) + obj.instance_variable_set(:@start, @start) obj else - self.class.__send__(:new_from_jd, @jd - other, @sg, @df) + self.class.__send__(:new_from_jd, @jd - other, @start, @day_fraction) end when Numeric r = other.to_r @@ -1106,7 +1106,7 @@ def -(other) total = day_fraction - r days = total.floor frac = total - days - self.class.__send__(:new_from_jd, @jd + days, @sg, frac == 0 ? nil : frac) + self.class.__send__(:new_from_jd, @jd + days, @start, frac == 0 ? nil : frac) else raise TypeError, "expected numeric" end @@ -1142,14 +1142,14 @@ def >>(n) m2 = @month + n.to_i y2 = @year + (m2 - 1).div(12) m2 = (m2 - 1) % 12 + 1 - if @sg == Float::INFINITY + if @start == Float::INFINITY dim = self.class.__send__(:days_in_month_julian, y2, m2) else dim = self.class.__send__(:days_in_month_gregorian, y2, m2) end d2 = @day < dim ? @day : dim - jd2 = self.class.__send__(:civil_to_jd, y2, m2, d2, @sg) - self.class.__send__(:new_from_jd, jd2, @sg) + jd2 = self.class.__send__(:civil_to_jd, y2, m2, d2, @start) + self.class.__send__(:new_from_jd, jd2, @start) end # call-seq: @@ -1276,13 +1276,13 @@ def step(limit, step = 1) if Integer === step && instance_of?(Date) && limit.instance_of?(Date) raise ArgumentError, "step can't be 0" if step == 0 limit_jd = limit.jd - sg = @sg + sg = @start if step > 0 jd = @jd while jd <= limit_jd obj = Date.allocate obj.instance_variable_set(:@jd, jd) - obj.instance_variable_set(:@sg, sg) + obj.instance_variable_set(:@start, sg) yield obj jd += step end @@ -1291,7 +1291,7 @@ def step(limit, step = 1) while jd >= limit_jd obj = Date.allocate obj.instance_variable_set(:@jd, jd) - obj.instance_variable_set(:@sg, sg) + obj.instance_variable_set(:@start, sg) yield obj jd += step end @@ -1326,11 +1326,11 @@ def upto(max, &block) if instance_of?(Date) && max.instance_of?(Date) jd = @jd max_jd = max.jd - sg = @sg + sg = @start while jd <= max_jd obj = Date.allocate obj.instance_variable_set(:@jd, jd) - obj.instance_variable_set(:@sg, sg) + obj.instance_variable_set(:@start, sg) yield obj jd += 1 end @@ -1348,11 +1348,11 @@ def downto(min, &block) if instance_of?(Date) && min.instance_of?(Date) jd = @jd min_jd = min.jd - sg = @sg + sg = @start while jd >= min_jd obj = Date.allocate obj.instance_variable_set(:@jd, jd) - obj.instance_variable_set(:@sg, sg) + obj.instance_variable_set(:@start, sg) yield obj jd -= 1 end @@ -1381,7 +1381,7 @@ def to_date # Date.new(2001, 2, 3).to_datetime # => # # def to_datetime - DateTime.new(year, month, day, 0, 0, 0, 0, @sg) + DateTime.new(year, month, day, 0, 0, 0, 0, @start) end # call-seq: @@ -1407,25 +1407,25 @@ def to_time def initialize_copy(other) # Assign every ivar in the canonical order so copies share the same shape # as freshly constructed instances (see init_from_jd). - @jd = other.instance_variable_get(:@jd) - @sg = other.instance_variable_get(:@sg) - @df = other.instance_variable_get(:@df) - @year = other.instance_variable_get(:@year) - @month = other.instance_variable_get(:@month) - @day = other.instance_variable_get(:@day) + @jd = other.instance_variable_get(:@jd) + @start = other.instance_variable_get(:@start) + @day_fraction = other.instance_variable_get(:@day_fraction) + @year = other.instance_variable_get(:@year) + @month = other.instance_variable_get(:@month) + @day = other.instance_variable_get(:@day) end # :nodoc: def marshal_dump # 6-element format: [nth, jd, df, sf, of, sg] # df = seconds into day (Integer), sf = sub-second fraction (Rational) - if @df - total_sec = @df * 86400 + if @day_fraction + total_sec = @day_fraction * 86400 df_int = total_sec.floor sf = total_sec - df_int - [0, @jd, df_int, sf, 0, @sg] + [0, @jd, df_int, sf, 0, @start] else - [0, @jd, 0, 0, 0, @sg] + [0, @jd, 0, 0, 0, @start] end end @@ -1677,7 +1677,7 @@ def to_s # # => "#" # def inspect - sg = @sg.is_a?(Float) ? @sg.to_s : @sg + sg = @start.is_a?(Float) ? @start.to_s : @start "#".force_encoding(Encoding::US_ASCII) end @@ -1694,24 +1694,24 @@ def freeze private def init_from_jd(jd, sg, df = nil) - @jd = jd - @sg = sg - @df = df + @jd = jd + @start = sg + @day_fraction = df # Initialize the lazily-computed civil ivars up front so every Date # instance shares a single object shape regardless of which accessors # are called. (yday/cweek/cwyear are not cached; see #yday/#cweek.) - @year = nil - @month = nil - @day = nil + @year = nil + @month = nil + @day = nil end def internal_civil return if @year jd = @jd - if @sg == Float::INFINITY # always Julian + if @start == Float::INFINITY # always Julian b = 0 c = jd + 32082 - elsif jd >= @sg # Gregorian (handles -Infinity too) + elsif jd >= @start # Gregorian (handles -Infinity too) a = jd + 32044 b = (4 * a + 3) / 146097 c = a - (146097 * b) / 4 @@ -1730,7 +1730,7 @@ def internal_civil # Compute [cwyear, cweek] from the Julian Day. Not cached, matching the # C extension, which recomputes commercial fields on each access. def compute_commercial - y, cw, = self.class.__send__(:jd_to_commercial, @jd, @sg) + y, cw, = self.class.__send__(:jd_to_commercial, @jd, @start) [y, cw] end diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 5d0b2eac..50c71201 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -164,7 +164,7 @@ def ajd def +(other) case other when Integer - self.class.__send__(:_new_dt_from_jd_time,@jd + other, @hour, @min, @sec_i, @sec_frac, @of, @sg) + self.class.__send__(:_new_dt_from_jd_time,@jd + other, @hour, @min, @sec_i, @sec_frac, @of, @start) when Rational, Float # other is days (may be fractional) — add as seconds extra_sec = other.to_r * 86400 @@ -203,7 +203,7 @@ def -(other) when Date ajd - other.ajd when Integer - self.class.__send__(:_new_dt_from_jd_time,@jd - other, @hour, @min, @sec_i, @sec_frac, @of, @sg) + self.class.__send__(:_new_dt_from_jd_time,@jd - other, @hour, @min, @sec_i, @sec_frac, @of, @start) when Rational, Float self + (-other) when Numeric @@ -240,7 +240,7 @@ def new_start(start = Date::ITALY) # d.new_offset('+09:00') #=> # def new_offset(of = 0) of_sec = _str_offset_to_sec(of) - self.class.__send__(:_new_dt_from_jd_time,@jd, @hour, @min, @sec_i, @sec_frac, of_sec, @sg) + self.class.__send__(:_new_dt_from_jd_time,@jd, @hour, @min, @sec_i, @sec_frac, of_sec, @start) end # --------------------------------------------------------------------------- @@ -408,9 +408,9 @@ def to_s def hash if @hour == 0 && @min == 0 && @sec_i == 0 - [@jd, @sg].hash + [@jd, @start].hash else - [@jd, @hour, @min, @sec_i, @sg].hash + [@jd, @hour, @min, @sec_i, @start].hash end end @@ -423,7 +423,7 @@ def marshal_dump # 6-element format: [nth, jd, df, sf, of, sg] df = @hour * 3600 + @min * 60 + @sec_i sf = (@sec_frac * 1_000_000_000).to_r # nanoseconds as Rational - [0, @jd, df, sf, @of, @sg] + [0, @jd, df, sf, @of, @start] end # :nodoc: @@ -468,7 +468,7 @@ def marshal_load(array) # # Returns a Date object which denotes self. def to_date - Date.__send__(:new_from_jd, @jd, @sg) + Date.__send__(:new_from_jd, @jd, @start) end # call-seq: @@ -889,19 +889,19 @@ def zone_str end def _init_datetime(jd, h, m, s, sf, of, sg) - @jd = jd - @sg = sg - @df = nil - @hour = h - @min = m - @sec_i = s - @sec_frac = sf.is_a?(Rational) ? sf : Rational(sf) - @of = of.to_i + @jd = jd + @start = sg + @day_fraction = nil + @hour = h + @min = m + @sec_i = s + @sec_frac = sf.is_a?(Rational) ? sf : Rational(sf) + @of = of.to_i # Initialize lazily-computed (inherited from Date) civil ivars up front so # every DateTime instance shares a single object shape. - @year = nil - @month = nil - @day = nil + @year = nil + @month = nil + @day = nil end def _split_second(second) @@ -946,7 +946,7 @@ def _from_total_sec_r(total_r) s_r = rem - m * 60 s_i = s_r.floor s_f = s_r - s_i - self.class.__send__(:_new_dt_from_jd_time,jd, h, m, s_i, s_f, @of, @sg) + self.class.__send__(:_new_dt_from_jd_time,jd, h, m, s_i, s_f, @of, @start) end end From c21130765acd38e03d4e32f6656fc0653b067041 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 7 Jun 2026 00:49:17 +0900 Subject: [PATCH 017/144] Fix Date#+/#- Integer path to preserve shape and day fraction The Integer fast path in Date#+ and Date#- built the result with Date.allocate plus instance_variable_set for only @jd and @start. This had two problems: * It produced a 2-ivar object whose shape diverged from the canonical 6-ivar shape established by init_from_jd, defeating the shape-friendly initialization. * It dropped @day_fraction, so adding or subtracting an Integer to a fractional Date silently lost the fraction: (Date.new(2024,1,1) + Rational(1,2) + 1).day_fraction returned 0 instead of 1/2. The C extension preserves the fraction here. Both branches now route through new_from_jd(@jd +/- other, @start, @day_fraction), which goes through init_from_jd (full canonical shape) and carries the day fraction, matching the C extension. --- lib/date/core.rb | 18 ++---------------- 1 file changed, 2 insertions(+), 16 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 6937d9d7..820b3bbf 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1050,14 +1050,7 @@ def ===(other) def +(other) case other when Integer - if instance_of?(Date) - obj = Date.allocate - obj.instance_variable_set(:@jd, @jd + other) - obj.instance_variable_set(:@start, @start) - obj - else - self.class.__send__(:new_from_jd, @jd + other, @start, @day_fraction) - end + self.class.__send__(:new_from_jd, @jd + other, @start, @day_fraction) when Numeric r = other.to_r raise TypeError, "#{other.class} can't be coerced into Integer" unless r.is_a?(Rational) @@ -1092,14 +1085,7 @@ def -(other) when Date Rational(@jd - other.jd) + day_fraction - other.day_fraction when Integer - if instance_of?(Date) - obj = Date.allocate - obj.instance_variable_set(:@jd, @jd - other) - obj.instance_variable_set(:@start, @start) - obj - else - self.class.__send__(:new_from_jd, @jd - other, @start, @day_fraction) - end + self.class.__send__(:new_from_jd, @jd - other, @start, @day_fraction) when Numeric r = other.to_r raise TypeError, "#{other.class} can't be coerced into Integer" unless r.is_a?(Rational) From e67f19639f02dd580ed706a2fcc36d93f075e046 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 7 Jun 2026 01:29:35 +0900 Subject: [PATCH 018/144] Normalize Date::Infinity start to Float in marshal_load Old marshal formats (1.8 and 1.9.2) store the start value (sg) as a Date::Infinity object. marshal_load kept it as-is, so Date#start returned a Date::Infinity instance instead of a Float. On MRI this slipped through because Float#== falls back to the right operand's #== (so Date::GREGORIAN == d.start happened to be true), but on TruffleRuby Float#== does not fall back and the comparison returned false, failing test_marshal18 and test_marshal192 on CI. The C extension stores start as a double and Date#start returns a Float, so the loaded value should be a Float too. A normalize_start helper converts a Date::Infinity start to its Float equivalent (+/-Float::INFINITY) in both Date#marshal_load and DateTime#marshal_load (formats 1.8 and current); Integer starts such as Date::ITALY are left untouched. --- lib/date/core.rb | 9 +++++++++ lib/date/datetime.rb | 2 ++ 2 files changed, 11 insertions(+) diff --git a/lib/date/core.rb b/lib/date/core.rb index 820b3bbf..b937920c 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1426,6 +1426,7 @@ def marshal_load(array) when 3 # Format 1.8: [ajd, of, sg] ajd, _of, sg = array + sg = normalize_start(sg) raw_jd = ajd + 0.5r jd = raw_jd.floor df = raw_jd - jd @@ -1433,6 +1434,7 @@ def marshal_load(array) when 6 # Current format: [nth, jd, df, sf, of, sg] _nth, jd, df, sf, _of, sg = array + sg = normalize_start(sg) if df != 0 || sf != 0 day_frac = (Rational(df) + sf) / 86400 init_from_jd(jd, sg, day_frac) @@ -1679,6 +1681,13 @@ def freeze private + # Normalize a start value coming from old marshal formats: a Date::Infinity + # object becomes the equivalent Float (start is stored as a Float/Integer + # internally, like the C extension's double). + def normalize_start(sg) + sg.is_a?(Infinity) ? sg.to_f : sg + end + def init_from_jd(jd, sg, df = nil) @jd = jd @start = sg diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 50c71201..641490ad 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -435,6 +435,7 @@ def marshal_load(array) _init_datetime(jd_like.to_i, 0, 0, 0, 0r, 0, sg) when 3 ajd, of_r, sg = array + sg = normalize_start(sg) of_sec = (of_r * 86400).to_i # Reconstruct local JD and time from AJD local_r = ajd + 0.5r + of_r @@ -448,6 +449,7 @@ def marshal_load(array) _init_datetime(jd, h, m, s_i, s_f, of_sec, sg) when 6 _nth, jd, df, sf, of, sg = array + sg = normalize_start(sg) h = df / 3600 df -= h * 3600 m = df / 60 From 5bcb504049b916b7d5dd7cfe844a4aced69b74c8 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 16 Jun 2026 22:39:05 +0900 Subject: [PATCH 019/144] Remove unnecessary `strip!` on offset expression in zonetab generator The `offset_expr` value is only consumed by `eval(offset_expr)`, and `eval` ignores leading/trailing whitespace when parsing its argument as Ruby source. Stripping it beforehand has no effect, so drop the call. The `abbr.strip!` above is kept because `abbr` is used as a hash key, where surrounding whitespace would be significant. Verified by regenerating lib/date/zonetab.rb (316 entries) before and after the change: the output is byte-for-byte identical. Per review by @nobu: https://github.com/ruby/date/pull/155#discussion_r2872514519 --- ext/date/generate-zonetab-rb | 1 - 1 file changed, 1 deletion(-) diff --git a/ext/date/generate-zonetab-rb b/ext/date/generate-zonetab-rb index 64b72c7e..c86a27d9 100755 --- a/ext/date/generate-zonetab-rb +++ b/ext/date/generate-zonetab-rb @@ -28,7 +28,6 @@ File.foreach(list_path) do |line| next unless offset_expr abbr.strip! - offset_expr.strip! # Evaluate offset expression (e.g., "0*3600", "-5*3600", "-(1*3600+1800)", "16200") offset = eval(offset_expr) From d80a88b7f3564cbc37e914a79bdb3ca5fb2126ef Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 16 Jun 2026 22:48:56 +0900 Subject: [PATCH 020/144] Simplify zonetab sort to Hash#sort Replace `entries.sort_by { |k, _| k }` with `entries.sort`. Hash#sort compares `[key, value]` pairs, but since hash keys are unique the value is never reached as a tiebreaker, so the result is identical to sorting by key alone. Verified by regenerating lib/date/zonetab.rb (316 entries) before and after the change: the output is byte-for-byte identical. Per review by @nobu: https://github.com/ruby/date/pull/155#discussion_r2872582236 --- ext/date/generate-zonetab-rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/ext/date/generate-zonetab-rb b/ext/date/generate-zonetab-rb index c86a27d9..80753df6 100755 --- a/ext/date/generate-zonetab-rb +++ b/ext/date/generate-zonetab-rb @@ -35,7 +35,7 @@ File.foreach(list_path) do |line| entries[abbr] = offset end -sorted = entries.sort_by { |k, _| k } +sorted = entries.sort max_key_len = sorted.map { |k, _| k.length }.max From 382bb9a4e725fc818ea19b69b1bca38ad41f599e Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 17 Jun 2026 20:43:55 +0900 Subject: [PATCH 021/144] Use printf with %p in zonetab generator key formatting The previous ternary `abbr.include?(' ') ? %Q("#{abbr}") : %Q("#{abbr}")` had identical branches, so the condition was dead code. Replace the whole block with a single `f.printf "%-*p"` call: `%p` inspects the key(adding the surrounding quotes) and `*` takes the field width argument, removing the redundant ternary and the intermediate `key` variable. Using inspect via `%p` is also more robust than interpolating quotes by hand, since it would properly escape special characters if a key ever contained them. Verified by regenerating lib/date/zonetab.rb (316 entries) before and after the change: the output is byte-for-byte identical. Per review by @nobu: https://github.com/ruby/date/pull/155#discussion_r2872605073 --- ext/date/generate-zonetab-rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ext/date/generate-zonetab-rb b/ext/date/generate-zonetab-rb index 80753df6..3ef168af 100755 --- a/ext/date/generate-zonetab-rb +++ b/ext/date/generate-zonetab-rb @@ -48,8 +48,7 @@ File.open(output_path, 'w') do |f| f.puts 'class Date' f.puts ' ZONE_TABLE = {' sorted.each do |abbr, offset| - key = abbr.include?(' ') ? %Q("#{abbr}") : %Q("#{abbr}") - f.puts " %-#{max_key_len + 3}s => %d," % [key, offset] + f.printf " %-*p => %d,\n", max_key_len + 3, abbr, offset end f.puts ' }.freeze' f.puts 'end' From a6abfc18ab7a66a8cb065893a48a8dbb84bf0403 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 17 Jun 2026 20:52:27 +0900 Subject: [PATCH 022/144] Use File.foreach chomp option in zonetab generator Pass `chomp: true` to `File.foreach` so each line is yielded already chomped, removing the explicit `line.chomp!` call inside the block. zonetab.list uses LF-only line endings, so this is equivalent to the previous `chomp!` here. Verified by regenerating lib/date/zonetab.rb (316 entries) before and after the change: the output is byte-for-byte identical. Per review by @nobu: https://github.com/ruby/date/pull/155#discussion_r2872652609 --- ext/date/generate-zonetab-rb | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/ext/date/generate-zonetab-rb b/ext/date/generate-zonetab-rb index 3ef168af..64f87766 100755 --- a/ext/date/generate-zonetab-rb +++ b/ext/date/generate-zonetab-rb @@ -12,8 +12,7 @@ output_path = File.join(__dir__, '..', '..', 'lib', 'date', 'zonetab.rb') entries = {} in_entries = false -File.foreach(list_path) do |line| - line.chomp! +File.foreach(list_path, chomp: true) do |line| if line == '%%' if in_entries break From 7c04350255bba373a02647b5d38f74b035ce5ad5 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 17 Jun 2026 21:06:39 +0900 Subject: [PATCH 023/144] Simplify section tracking in zonetab generator Replace the `in_entries` boolean and its nested `if`/`else` block with a `sections` counter. `break if line == '%%' and (sections += 1) > 1` stops at the second `%%` (end of the entries section), and `next if sections < 1` skips the declarations before the first `%%`. The first `%%` line passes that guard but is then dropped by the existing `next unless offset_expr`, since it has no comma. The `line.chomp!` from the original suggestion is omitted here because `File.foreach` is already called with `chomp: true`. Verified by regenerating lib/date/zonetab.rb (316 entries) before and after the change: the output is byte-for-byte identical. Per review by @nobu: https://github.com/ruby/date/pull/155#discussion_r2872724920 --- ext/date/generate-zonetab-rb | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) diff --git a/ext/date/generate-zonetab-rb b/ext/date/generate-zonetab-rb index 64f87766..99602dec 100755 --- a/ext/date/generate-zonetab-rb +++ b/ext/date/generate-zonetab-rb @@ -10,18 +10,11 @@ list_path = File.join(__dir__, 'zonetab.list') output_path = File.join(__dir__, '..', '..', 'lib', 'date', 'zonetab.rb') entries = {} -in_entries = false +sections = 0 File.foreach(list_path, chomp: true) do |line| - if line == '%%' - if in_entries - break - else - in_entries = true - next - end - end - next unless in_entries + break if line == '%%' and (sections += 1) > 1 + next if sections < 1 abbr, offset_expr = line.split(',', 2) next unless offset_expr From 9e9d45aebca40790612c2f96edf9779454e19ac9 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 17 Jun 2026 21:58:59 +0900 Subject: [PATCH 024/144] Accept input/output paths as arguments in zonetab generator Take the list and output paths from ARGV instead of hardcoding them relative to __dir__: ``` list_path, output_path = ARGV ``` This makes the generator path-agnostic so the caller controls where it reads from and writes to. The Usage comment and the auto-generated header line are updated accordingly, the latter now interpolating the actual list_path: ``` # Auto-generated from #{list_path} by ext/date/generate-zonetab-rb. ``` The only caller, the `update-zonetab` target in ext/date/prereq.mk, is updated to pass the paths. It now runs from $(top_srcdir) and passes the repo-relative paths, so list_path resolves to exactly "ext/date/zonetab.list" and the generated header stays unchanged: ``` $(RUBY) -C $(top_srcdir) ext/date/generate-zonetab-rb \ ext/date/zonetab.list lib/date/zonetab.rb ``` Verified by regenerating lib/date/zonetab.rb (316 entries) through the updated invocation: the output, including the header comment, is byte-for-byte identical. Per reviews by @nobu: https://github.com/ruby/date/pull/155#discussion_r2872754276 https://github.com/ruby/date/pull/155#discussion_r2872760067 https://github.com/ruby/date/pull/155#discussion_r2872774360 --- ext/date/generate-zonetab-rb | 7 +++---- ext/date/prereq.mk | 2 +- 2 files changed, 4 insertions(+), 5 deletions(-) diff --git a/ext/date/generate-zonetab-rb b/ext/date/generate-zonetab-rb index 99602dec..41c45a1e 100755 --- a/ext/date/generate-zonetab-rb +++ b/ext/date/generate-zonetab-rb @@ -1,13 +1,12 @@ # -*- mode: ruby -*- # Generate lib/date/zonetab.rb from ext/date/zonetab.list # -# Usage: ruby -C ext/date generate-zonetab-rb +# Usage: ruby ext/date/generate-zonetab-rb ext/date/zonetab.list lib/date/zonetab.rb # # This script reads zonetab.list (the same source used to generate zonetab.h # via gperf) and produces the equivalent Ruby hash table. -list_path = File.join(__dir__, 'zonetab.list') -output_path = File.join(__dir__, '..', '..', 'lib', 'date', 'zonetab.rb') +list_path, output_path = ARGV entries = {} sections = 0 @@ -35,7 +34,7 @@ File.open(output_path, 'w') do |f| f.puts '# frozen_string_literal: true' f.puts f.puts '# Timezone name => UTC offset (seconds) mapping table.' - f.puts '# Auto-generated from ext/date/zonetab.list by ext/date/generate-zonetab-rb.' + f.puts "# Auto-generated from #{list_path} by ext/date/generate-zonetab-rb." f.puts '# Do not edit manually.' f.puts 'class Date' f.puts ' ZONE_TABLE = {' diff --git a/ext/date/prereq.mk b/ext/date/prereq.mk index 7f8e0bbf..79ea525a 100644 --- a/ext/date/prereq.mk +++ b/ext/date/prereq.mk @@ -10,7 +10,7 @@ zonetab.h: zonetab.list .PHONY: update-zonetab update-zonetab: $(RUBY) -C $(srcdir) update-abbr - $(RUBY) -C $(srcdir) generate-zonetab-rb + $(RUBY) -C $(top_srcdir) ext/date/generate-zonetab-rb ext/date/zonetab.list lib/date/zonetab.rb .PHONY: update-nothing update-nothing: From e8806201750a9d9b63230ca392ff79944544dfe8 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 17 Jun 2026 22:30:15 +0900 Subject: [PATCH 025/144] Build abbr 3-key tables with shared compute_3key helper The ABBR_DAY_3KEY / ABBR_MONTH_3KEY tables in constants.rb open-coded the 3-byte key computation that is already factored into the shared Date.compute_3key helper. Use the helper instead, so the table keys and the runtime lookups in parse.rb / strptime.rb are produced by a single function and cannot drift apart. To make the helper available while the tables are built at load time, require date/shared before date/constants (shared.rb references no constants, so the reorder is safe). The helper is a private class method, so it is called without an explicit receiver; its `| 0x20` case-folding also makes the previous `.downcase` unnecessary. This runs only at load time, so there is no runtime performance impact. Verified that ABBR_DAY_3KEY (7 entries) and ABBR_MONTH_3KEY (12 entries) are identical to the previous inline result, and the date test suite shows no new failures (0 failures; only the 3 pre-existing environment-related errors remain). Per review by @nobu: https://github.com/ruby/date/pull/155#discussion_r3413654926 --- lib/date.rb | 2 +- lib/date/constants.rb | 6 ++---- 2 files changed, 3 insertions(+), 5 deletions(-) diff --git a/lib/date.rb b/lib/date.rb index d5869a61..55bdb526 100644 --- a/lib/date.rb +++ b/lib/date.rb @@ -6,8 +6,8 @@ if RUBY_VERSION >= "3.3" require_relative "date/version" - require_relative "date/constants" require_relative "date/shared" + require_relative "date/constants" require_relative "date/core" require_relative "date/strftime" require_relative "date/parse" diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 707018ed..c3f7ade3 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -22,13 +22,11 @@ class Date # Key = (byte0_lower << 16) | (byte1_lower << 8) | byte2_lower # Value = [index, full_name_length] ABBR_DAY_3KEY = ABBR_DAYNAMES.each_with_index.to_h { |n, i| - b = n.downcase.bytes - [(b[0] << 16) | (b[1] << 8) | b[2], [i, DAYNAMES[i].length].freeze] + [compute_3key(n), [i, DAYNAMES[i].length].freeze] }.freeze ABBR_MONTH_3KEY = ABBR_MONTHNAMES.each_with_index.each_with_object({}) { |(n, i), h| next if n.nil? - b = n.downcase.bytes - h[(b[0] << 16) | (b[1] << 8) | b[2]] = [i, MONTHNAMES[i].length].freeze + h[compute_3key(n)] = [i, MONTHNAMES[i].length].freeze }.freeze private_constant :ABBR_DAY_3KEY, :ABBR_MONTH_3KEY From 20198e3204c487cbef4ee53bd575335362c480db Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 17 Jun 2026 22:38:09 +0900 Subject: [PATCH 026/144] Remove unused lib/date/patterns.rb This file defined 40 regex constants (TIME_PAT, PARSE_*, ISO8601_*, etc.) but was never required from anywhere (lib/test/ext), and none of its constants were referenced by any other file. The parsing code in parse.rb uses its own patterns (the runtime parse regexes live in constants.rb), so the file was dead code left over from an earlier stage of the port. Confirmed unused before removal: - no `require`/`autoload` of date/patterns anywhere - all 40 constants have zero references outside the file - after `require "date"`, Date::TIME_PAT and friends are undefined - Date.parse / Date._parse / Date.rfc3339 all work without it The date test suite is unchanged by the removal: 144 tests, 162568 assertions, 0 failures (only the 3 pre-existing environment-related errors remain). Per review by @nobu: https://github.com/ruby/date/pull/155#discussion_r3413918904 --- lib/date/patterns.rb | 403 ------------------------------------------- 1 file changed, 403 deletions(-) delete mode 100644 lib/date/patterns.rb diff --git a/lib/date/patterns.rb b/lib/date/patterns.rb deleted file mode 100644 index b8437b25..00000000 --- a/lib/date/patterns.rb +++ /dev/null @@ -1,403 +0,0 @@ -# frozen_string_literal: true - -class Date - # TIME_PAT - # Regular expression pattern for C's parse_time. - # $1: entire time portion - # $2: time zone portion (optional) - # - # In the zone portion, [A-Za-z] is used for case-sensitive alphabetic characters. - TIME_PAT = / - ( # $1: whole time - \d+\s* # hour (required) - (?: - (?: # Branch A: colon-separated - :\s*\d+ # :min - (?: - \s*:\s*\d+(?:[,.]\d*)? # :sec[.frac] - )? - | # Branch B: h m s separated - h(?:\s*\d+m? - (?:\s*\d+s?)? - )? - ) - (?: # AM PM suffix (optional) - \s*[ap](?:m\b|\.m\.) - )? - | # Branch C: Only AM PM - [ap](?:m\b|\.m\.) - ) - ) - (?: # Time Zone (optional) - \s* - ( # $2: time zone - (?:gmt|utc?)?[-+]\d+ - (?:[,.:]\d+(?::\d+)?)? - | - [[:alpha:].\s]+ - (?:standard|daylight)\stime\b - | - [[:alpha:]]+(?:\sdst)?\b - ) - )? - /xi - private_constant :TIME_PAT - - # TIME_DETAIL_PAT - # Pattern for detailed parsing of time portion - TIME_DETAIL_PAT = / - \A(\d+)\s* # $1 hour - (?: - :\s*(\d+) # $2 min (colon) - (?:\s*:\s*(\d+)([,.]\d*)?)? # $3 sec, $4 frac (colon) - | - h(?:\s*(\d+)m? # $5 min (h) - (?:\s*(\d+)s?)? # $6 sec (h) - )? - )? - (?:\s*([ap])(?:m\b|\.m\.))? # $7 am pm - /xi - private_constant :TIME_DETAIL_PAT - - # PARSE_DAY_PAT - # Non-TIGHT pattern for parse_day. - # Matches abbreviated day name and consumes trailing characters - # (e.g., "urday" in "Saturday") so they get replaced by subx. - PARSE_DAY_PAT = /\b(sun|mon|tue|wed|thu|fri|sat)[^-\/\d\s]*/i - private_constant :PARSE_DAY_PAT - - # ERA1_PAT - # Pattern for AD, A.D. - ERA1_PAT = /\b(a(?:d\b|\.d\.))(?!(? Date: Wed, 17 Jun 2026 22:52:49 +0900 Subject: [PATCH 027/144] Move file-local flag constants out of constants.rb The FL_* (strftime flag bits) and HAVE_* (parse character-class bits) constants were defined in the shared constants.rb but are each used in only one file: FL_* by strftime.rb (across internal_strftime, fmt_year, pad_num, fmt_str, fmt_z) and HAVE_* by parse.rb (solely within _parse). Move each group next to its sole user: - FL_* -> lib/date/strftime.rb - HAVE_* -> lib/date/parse.rb They stay as private constants on Date. HAVE_* is placed directly under `class Date` (outside `class << self`) so the singleton _parse method still resolves the bare names and they remain Date::HAVE_*. Visibility and lookup paths are unchanged. Verified: - Date::FL_LEFT / Date::HAVE_ALPHA etc. still raise "private constant ... referenced" when referenced via scope resolution - strftime (all flag paths) and _parse / parse behave identically - no -w warnings - date test suite unchanged: 144 tests, 162568 assertions, 0 failures (only the 3 pre-existing environment-related errors remain) Per review by @nobu: https://github.com/ruby/date/pull/155#discussion_r3414113087 --- lib/date/constants.rb | 17 ----------------- lib/date/parse.rb | 9 +++++++++ lib/date/strftime.rb | 7 +++++++ 3 files changed, 16 insertions(+), 17 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index c3f7ade3..5a097279 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -128,14 +128,6 @@ class Date MONTH_FULL_SPACE = STRFTIME_MONTHS_FULL.map { |m| m ? "#{m} ".freeze : nil }.freeze private_constant :DAY_FULL_COMMA, :MONTH_FULL_SPACE - # Bitmask flag constants for strftime parsing - FL_LEFT = 0x01 # '-' flag - FL_SPACE = 0x02 # '_' flag - FL_ZERO = 0x04 # '0' flag - FL_UPPER = 0x08 # '^' flag - FL_CHCASE = 0x10 # '#' flag - private_constant :FL_LEFT, :FL_SPACE, :FL_ZERO, :FL_UPPER, :FL_CHCASE - # Pre-computed 2-digit zero-padded strings for 0..99 PAD2 = (0..99).map { |n| format('%02d', n).freeze }.freeze private_constant :PAD2 @@ -233,15 +225,6 @@ class Date JISX0301_RE = /\A\s*([mtshr])?(\d{2})\.(\d{2})\.(\d{2})(?:t(?:(\d{2}):(\d{2})(?::(\d{2})(?:[,.](\d*))?)?(z|[-+]\d{2}(?::?\d{2})?)?)?)?\s*\z/i private_constant :JISX0301_ERA, :JISX0301_RE - # Character class flags - HAVE_ALPHA = 1 - HAVE_DIGIT = 2 - HAVE_DASH = 4 - HAVE_DOT = 8 - HAVE_SLASH = 16 - HAVE_COLON = 32 - private_constant :HAVE_ALPHA, :HAVE_DIGIT, :HAVE_DASH, :HAVE_DOT, :HAVE_SLASH, :HAVE_COLON - PARSE_DAYS_RE = /\b(sun|mon|tue|wed|thu|fri|sat)[^-\/\d\s]*/i PARSE_MON_RE = /\b(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\S*/i PARSE_MDAY_RE = /(? string From c9b2175b6416c6889eb07669f5bf29d205d0854d Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 17 Jun 2026 23:27:15 +0900 Subject: [PATCH 028/144] Drop the C extension; pure Ruby implementation only (Ruby >= 3.3) Following the discussion on #155, remove the C extension and ship date as a pure Ruby library. Maintaining both a C and a Ruby implementation that must stay behaviorally identical is a real maintenance burden; the Ruby implementation is now the single source of truth. Performance- sensitive users can enable YJIT, which is significantly faster on the supported Ruby versions. Changes: - lib/date.rb: drop the `RUBY_VERSION >= "3.3"` gate and the `else require 'date_core'` fallback; require the pure Ruby files unconditionally. - date.gemspec: bump required_ruby_version to ">= 3.3.0", drop s.extensions, and remove the C sources from the files list. - Remove the C extension assets: date_core.c, date_parse.c, date_strftime.c, date_strptime.c, date_tmx.h, extconf.rb, and the gperf-generated zonetab.h. Keep zonetab.list, generate-zonetab-rb, update-abbr, and a trimmed prereq.mk, which still regenerate lib/date/zonetab.rb. - Rakefile: drop the version gate and the Rake::ExtensionTask / zonetab.h branch; keep the pure Ruby test task (compile is a no-op). - .github/workflows/test.yml: min_version 2.6 -> 3.3, drop the gperf install, and run `rake test` (compile is no longer needed). - .github/workflows/update.yml: drop gperf and the `make zonetab.h` step; zonetab.rb regeneration is unchanged. - strptime.rb: reword two comments that referenced the now-deleted ext/date/*.c files, keeping the original C function names as provenance. required_ruby_version was chosen empirically: the suite passes on 3.0 and 3.1, the library smoke-loads on 3.2, but breaks on 2.7/2.6 (a frozen-string incompatibility in strftime). 3.3 is kept as the floor to match the prior gate, align with the YJIT performance rationale, and avoid already-EOL versions. Verified with `rake test`: 144 tests, 162595 assertions, 0 failures, 0 errors, 100% passed; no -w warnings; gemspec loads with required_ruby_version ">= 3.3.0" and no extensions. --- .github/workflows/test.yml | 6 +- .github/workflows/update.yml | 3 +- Rakefile | 49 +- date.gemspec | 4 +- ext/date/date_core.c | 10258 --------------------------------- ext/date/date_parse.c | 3086 ---------- ext/date/date_strftime.c | 638 -- ext/date/date_strptime.c | 704 --- ext/date/date_tmx.h | 56 - ext/date/extconf.rb | 16 - ext/date/prereq.mk | 9 - ext/date/zonetab.h | 1564 ----- lib/date.rb | 22 +- lib/date/strptime.rb | 4 +- 14 files changed, 23 insertions(+), 16396 deletions(-) delete mode 100644 ext/date/date_core.c delete mode 100644 ext/date/date_parse.c delete mode 100644 ext/date/date_strftime.c delete mode 100644 ext/date/date_strptime.c delete mode 100644 ext/date/date_tmx.h delete mode 100644 ext/date/extconf.rb delete mode 100644 ext/date/zonetab.h diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index f55c34ce..a94af6b2 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -11,7 +11,7 @@ jobs: uses: ruby/actions/.github/workflows/ruby_versions.yml@master with: engine: cruby - min_version: 2.6 + min_version: 3.3 build: if: ${{ startsWith(github.repository, 'ruby/') || github.event_name != 'schedule' }} @@ -40,7 +40,5 @@ jobs: with: ruby-version: ${{ matrix.ruby }} bundler-cache: true # 'bundle install' and cache - - run: choco install gperf - if: ${{ matrix.ruby == 'mswin' }} - name: Run test - run: bundle exec rake compile test + run: bundle exec rake test diff --git a/.github/workflows/update.yml b/.github/workflows/update.yml index 540a9967..a428e12b 100644 --- a/.github/workflows/update.yml +++ b/.github/workflows/update.yml @@ -12,14 +12,13 @@ jobs: steps: - uses: actions/checkout@v6 - name: Set up Ruby - run: sudo apt-get --no-install-recommends -q -y install ruby-dev gperf + run: sudo apt-get --no-install-recommends -q -y install ruby-dev - name: Install dependencies run: sudo gem install --no-document nokogiri - name: Update zonetab working-directory: ext/date run: | make -f prereq.mk update-zonetab - make -f prereq.mk zonetab.h env: top_srcdir: ../.. srcdir: . diff --git a/Rakefile b/Rakefile index 06175d09..20d08f72 100644 --- a/Rakefile +++ b/Rakefile @@ -1,47 +1,14 @@ require "bundler/gem_tasks" require "rake/testtask" -if RUBY_VERSION >= "3.3" - # Pure Ruby — no compilation needed - Rake::TestTask.new(:test) do |t| - t.libs << "lib" - t.libs << "test/lib" - t.ruby_opts << "-rhelper" - t.test_files = FileList['test/**/test_*.rb'] - end - - task :compile # no-op - -else - # C extension for Ruby < 3.3 - require "shellwords" - require "rake/extensiontask" - - extask = Rake::ExtensionTask.new("date") do |ext| - ext.name = "date_core" - ext.lib_dir.sub!(%r[(?=/|\z)], "/#{RUBY_VERSION}/#{ext.platform}") - end - - Rake::TestTask.new(:test) do |t| - t.libs << extask.lib_dir - t.libs << "test/lib" - t.ruby_opts << "-rhelper" - t.test_files = FileList['test/**/test_*.rb'] - end - - task test: :compile - - task compile: "ext/date/zonetab.h" - file "ext/date/zonetab.h" => "ext/date/zonetab.list" do |t| - dir, hdr = File.split(t.name) - make_program_name = - ENV['MAKE'] || ENV['make'] || - RbConfig::CONFIG['configure_args'][/with-make-prog\=\K\w+/] || - (/mswin/ =~ RUBY_PLATFORM ? 'nmake' : 'make') - make_program = Shellwords.split(make_program_name) - sh(*make_program, "-f", "prereq.mk", "top_srcdir=.."+"/.."*dir.count("/"), - hdr, chdir: dir) - end +# Pure Ruby — no compilation needed +Rake::TestTask.new(:test) do |t| + t.libs << "lib" + t.libs << "test/lib" + t.ruby_opts << "-rhelper" + t.test_files = FileList['test/**/test_*.rb'] end +task :compile # no-op, kept for compatibility + task :default => [:compile, :test] diff --git a/date.gemspec b/date.gemspec index d8da6dd2..d9fed315 100644 --- a/date.gemspec +++ b/date.gemspec @@ -11,11 +11,9 @@ Gem::Specification.new do |s| s.require_path = %w{lib} s.files = Dir["README.md", "COPYING", "BSDL", "lib/**/*.rb", - "ext/date/*.c", "ext/date/*.h", "ext/date/extconf.rb", "ext/date/prereq.mk", "ext/date/zonetab.list"] - s.extensions = ["ext/date/extconf.rb"] - s.required_ruby_version = ">= 2.6.0" + s.required_ruby_version = ">= 3.3.0" s.authors = ["Tadayoshi Funaba"] s.email = [nil] diff --git a/ext/date/date_core.c b/ext/date/date_core.c deleted file mode 100644 index 72d697c8..00000000 --- a/ext/date/date_core.c +++ /dev/null @@ -1,10258 +0,0 @@ -/* - date_core.c: Coded by Tadayoshi Funaba 2010-2014 -*/ - -#include "ruby.h" -#include "ruby/encoding.h" -#include "ruby/util.h" -#include -#include -#if defined(HAVE_SYS_TIME_H) -#include -#endif - -#undef NDEBUG -#define NDEBUG -#include - -#ifdef RUBY_EXTCONF_H -#include RUBY_EXTCONF_H -#endif - -#define USE_PACK - -static ID id_cmp, id_le_p, id_ge_p, id_eqeq_p; -static VALUE cDate, cDateTime; -static VALUE eDateError; -static VALUE half_days_in_day, day_in_nanoseconds; -static double positive_inf, negative_inf; - -/* used by deconstruct_keys */ -static VALUE sym_year, sym_month, sym_day, sym_yday, sym_wday; -static VALUE sym_hour, sym_min, sym_sec, sym_sec_fraction, sym_zone; - -#define f_boolcast(x) ((x) ? Qtrue : Qfalse) - -#define f_abs(x) rb_funcall(x, rb_intern("abs"), 0) -#define f_negate(x) rb_funcall(x, rb_intern("-@"), 0) -#define f_add(x,y) rb_funcall(x, '+', 1, y) -#define f_sub(x,y) rb_funcall(x, '-', 1, y) -#define f_mul(x,y) rb_funcall(x, '*', 1, y) -#define f_div(x,y) rb_funcall(x, '/', 1, y) -#define f_quo(x,y) rb_funcall(x, rb_intern("quo"), 1, y) -#define f_idiv(x,y) rb_funcall(x, rb_intern("div"), 1, y) -#define f_mod(x,y) rb_funcall(x, '%', 1, y) -#define f_remainder(x,y) rb_funcall(x, rb_intern("remainder"), 1, y) -#define f_expt(x,y) rb_funcall(x, rb_intern("**"), 1, y) -#define f_floor(x) rb_funcall(x, rb_intern("floor"), 0) -#define f_ceil(x) rb_funcall(x, rb_intern("ceil"), 0) -#define f_truncate(x) rb_funcall(x, rb_intern("truncate"), 0) -#define f_round(x) rb_funcall(x, rb_intern("round"), 0) - -#define f_to_i(x) rb_funcall(x, rb_intern("to_i"), 0) -#define f_to_r(x) rb_funcall(x, rb_intern("to_r"), 0) -#define f_to_s(x) rb_funcall(x, rb_intern("to_s"), 0) -#define f_inspect(x) rb_funcall(x, rb_intern("inspect"), 0) - -#define f_add3(x,y,z) f_add(f_add(x, y), z) -#define f_sub3(x,y,z) f_sub(f_sub(x, y), z) - -#define f_frozen_ary(...) rb_ary_freeze(rb_ary_new3(__VA_ARGS__)) - -static VALUE date_initialize(int argc, VALUE *argv, VALUE self); -static VALUE datetime_initialize(int argc, VALUE *argv, VALUE self); - -#define RETURN_FALSE_UNLESS_NUMERIC(obj) if(!RTEST(rb_obj_is_kind_of((obj), rb_cNumeric))) return Qfalse -inline static void -check_numeric(VALUE obj, const char* field) -{ - if(!RTEST(rb_obj_is_kind_of(obj, rb_cNumeric))) { - rb_raise(rb_eTypeError, "invalid %s (not numeric)", field); - } -} - -inline static int -f_cmp(VALUE x, VALUE y) -{ - if (FIXNUM_P(x) && FIXNUM_P(y)) { - long c = FIX2LONG(x) - FIX2LONG(y); - if (c > 0) - return 1; - else if (c < 0) - return -1; - return 0; - } - return rb_cmpint(rb_funcallv(x, id_cmp, 1, &y), x, y); -} - -inline static VALUE -f_lt_p(VALUE x, VALUE y) -{ - if (FIXNUM_P(x) && FIXNUM_P(y)) - return f_boolcast(FIX2LONG(x) < FIX2LONG(y)); - return rb_funcall(x, '<', 1, y); -} - -inline static VALUE -f_gt_p(VALUE x, VALUE y) -{ - if (FIXNUM_P(x) && FIXNUM_P(y)) - return f_boolcast(FIX2LONG(x) > FIX2LONG(y)); - return rb_funcall(x, '>', 1, y); -} - -inline static VALUE -f_le_p(VALUE x, VALUE y) -{ - if (FIXNUM_P(x) && FIXNUM_P(y)) - return f_boolcast(FIX2LONG(x) <= FIX2LONG(y)); - return rb_funcall(x, id_le_p, 1, y); -} - -inline static VALUE -f_ge_p(VALUE x, VALUE y) -{ - if (FIXNUM_P(x) && FIXNUM_P(y)) - return f_boolcast(FIX2LONG(x) >= FIX2LONG(y)); - return rb_funcall(x, id_ge_p, 1, y); -} - -inline static VALUE -f_eqeq_p(VALUE x, VALUE y) -{ - if (FIXNUM_P(x) && FIXNUM_P(y)) - return f_boolcast(FIX2LONG(x) == FIX2LONG(y)); - return rb_funcall(x, id_eqeq_p, 1, y); -} - -inline static VALUE -f_zero_p(VALUE x) -{ - switch (TYPE(x)) { - case T_FIXNUM: - return f_boolcast(FIX2LONG(x) == 0); - case T_BIGNUM: - return Qfalse; - case T_RATIONAL: - { - VALUE num = rb_rational_num(x); - return f_boolcast(FIXNUM_P(num) && FIX2LONG(num) == 0); - } - } - return rb_funcall(x, id_eqeq_p, 1, INT2FIX(0)); -} - -#define f_nonzero_p(x) (!f_zero_p(x)) - -inline static VALUE -f_negative_p(VALUE x) -{ - if (FIXNUM_P(x)) - return f_boolcast(FIX2LONG(x) < 0); - return rb_funcall(x, '<', 1, INT2FIX(0)); -} - -#define f_positive_p(x) (!f_negative_p(x)) - -#define f_ajd(x) rb_funcall(x, rb_intern("ajd"), 0) -#define f_jd(x) rb_funcall(x, rb_intern("jd"), 0) -#define f_year(x) rb_funcall(x, rb_intern("year"), 0) -#define f_mon(x) rb_funcall(x, rb_intern("mon"), 0) -#define f_mday(x) rb_funcall(x, rb_intern("mday"), 0) -#define f_wday(x) rb_funcall(x, rb_intern("wday"), 0) -#define f_hour(x) rb_funcall(x, rb_intern("hour"), 0) -#define f_min(x) rb_funcall(x, rb_intern("min"), 0) -#define f_sec(x) rb_funcall(x, rb_intern("sec"), 0) - -/* copied from time.c */ -#define NDIV(x,y) (-(-((x)+1)/(y))-1) -#define NMOD(x,y) ((y)-(-((x)+1)%(y))-1) -#define DIV(n,d) ((n)<0 ? NDIV((n),(d)) : (n)/(d)) -#define MOD(n,d) ((n)<0 ? NMOD((n),(d)) : (n)%(d)) - -#define HAVE_JD (1 << 0) -#define HAVE_DF (1 << 1) -#define HAVE_CIVIL (1 << 2) -#define HAVE_TIME (1 << 3) -#define COMPLEX_DAT (1 << 7) - -#define have_jd_p(x) ((x)->flags & HAVE_JD) -#define have_df_p(x) ((x)->flags & HAVE_DF) -#define have_civil_p(x) ((x)->flags & HAVE_CIVIL) -#define have_time_p(x) ((x)->flags & HAVE_TIME) -#define complex_dat_p(x) ((x)->flags & COMPLEX_DAT) -#define simple_dat_p(x) (!complex_dat_p(x)) - -#define ITALY 2299161 /* 1582-10-15 */ -#define ENGLAND 2361222 /* 1752-09-14 */ -#define JULIAN positive_inf -#define GREGORIAN negative_inf -#define DEFAULT_SG ITALY - -#define UNIX_EPOCH_IN_CJD INT2FIX(2440588) /* 1970-01-01 */ - -#define MINUTE_IN_SECONDS 60 -#define HOUR_IN_SECONDS 3600 -#define DAY_IN_SECONDS 86400 -#define SECOND_IN_MILLISECONDS 1000 -#define SECOND_IN_NANOSECONDS 1000000000 - -#define JC_PERIOD0 1461 /* 365.25 * 4 */ -#define GC_PERIOD0 146097 /* 365.2425 * 400 */ -#define CM_PERIOD0 71149239 /* (lcm 7 1461 146097) */ -#define CM_PERIOD (0xfffffff / CM_PERIOD0 * CM_PERIOD0) -#define CM_PERIOD_JCY (CM_PERIOD / JC_PERIOD0 * 4) -#define CM_PERIOD_GCY (CM_PERIOD / GC_PERIOD0 * 400) - -#define REFORM_BEGIN_YEAR 1582 -#define REFORM_END_YEAR 1930 -#define REFORM_BEGIN_JD 2298874 /* ns 1582-01-01 */ -#define REFORM_END_JD 2426355 /* os 1930-12-31 */ - -#ifdef USE_PACK -#define SEC_WIDTH 6 -#define MIN_WIDTH 6 -#define HOUR_WIDTH 5 -#define MDAY_WIDTH 5 -#define MON_WIDTH 4 - -#define SEC_SHIFT 0 -#define MIN_SHIFT SEC_WIDTH -#define HOUR_SHIFT (MIN_WIDTH + SEC_WIDTH) -#define MDAY_SHIFT (HOUR_WIDTH + MIN_WIDTH + SEC_WIDTH) -#define MON_SHIFT (MDAY_WIDTH + HOUR_WIDTH + MIN_WIDTH + SEC_WIDTH) - -#define PK_MASK(x) ((1 << (x)) - 1) - -#define EX_SEC(x) (((x) >> SEC_SHIFT) & PK_MASK(SEC_WIDTH)) -#define EX_MIN(x) (((x) >> MIN_SHIFT) & PK_MASK(MIN_WIDTH)) -#define EX_HOUR(x) (((x) >> HOUR_SHIFT) & PK_MASK(HOUR_WIDTH)) -#define EX_MDAY(x) (((x) >> MDAY_SHIFT) & PK_MASK(MDAY_WIDTH)) -#define EX_MON(x) (((x) >> MON_SHIFT) & PK_MASK(MON_WIDTH)) - -#define PACK5(m,d,h,min,s) \ - (((m) << MON_SHIFT) | ((d) << MDAY_SHIFT) |\ - ((h) << HOUR_SHIFT) | ((min) << MIN_SHIFT) | ((s) << SEC_SHIFT)) - -#define PACK2(m,d) \ - (((m) << MON_SHIFT) | ((d) << MDAY_SHIFT)) -#endif - -#ifdef HAVE_FLOAT_H -#include -#endif - -#if defined(FLT_RADIX) && defined(FLT_MANT_DIG) && FLT_RADIX == 2 && FLT_MANT_DIG > 22 -#define date_sg_t float -#else -#define date_sg_t double -#endif - -#define JULIAN_EPOCH_DATE "-4712-01-01" -#define JULIAN_EPOCH_DATETIME JULIAN_EPOCH_DATE "T00:00:00+00:00" -#define JULIAN_EPOCH_DATETIME_RFC3339 "Mon, 1 Jan -4712 00:00:00 +0000" -#define JULIAN_EPOCH_DATETIME_HTTPDATE "Mon, 01 Jan -4712 00:00:00 GMT" - -/* A set of nth, jd, df and sf denote ajd + 1/2. Each ajd begin at - * noon of GMT (assume equal to UTC). However, this begins at - * midnight. - */ - -struct SimpleDateData -{ - unsigned flags; - int jd; /* as utc */ - VALUE nth; /* not always canonicalized */ - date_sg_t sg; /* 2298874..2426355 or -/+oo -- at most 22 bits */ - /* decoded as utc=local */ - int year; /* truncated */ -#ifndef USE_PACK - int mon; - int mday; - /* hour is zero */ - /* min is zero */ - /* sec is zero */ -#else - /* packed civil */ - unsigned pc; -#endif -}; - -struct ComplexDateData -{ - unsigned flags; - int jd; /* as utc */ - VALUE nth; /* not always canonicalized */ - date_sg_t sg; /* 2298874..2426355 or -/+oo -- at most 22 bits */ - /* decoded as local */ - int year; /* truncated */ -#ifndef USE_PACK - int mon; - int mday; - int hour; - int min; - int sec; -#else - /* packed civil */ - unsigned pc; -#endif - int df; /* as utc, in secs */ - int of; /* in secs */ - VALUE sf; /* in nano secs */ -}; - -union DateData { - unsigned flags; - struct SimpleDateData s; - struct ComplexDateData c; -}; - -#define get_d1(x)\ - union DateData *dat;\ - TypedData_Get_Struct(x, union DateData, &d_lite_type, dat); - -#define get_d1a(x)\ - union DateData *adat;\ - TypedData_Get_Struct(x, union DateData, &d_lite_type, adat); - -#define get_d1b(x)\ - union DateData *bdat;\ - TypedData_Get_Struct(x, union DateData, &d_lite_type, bdat); - -#define get_d2(x,y)\ - union DateData *adat, *bdat;\ - TypedData_Get_Struct(x, union DateData, &d_lite_type, adat);\ - TypedData_Get_Struct(y, union DateData, &d_lite_type, bdat); - -inline static VALUE -canon(VALUE x) -{ - if (RB_TYPE_P(x, T_RATIONAL)) { - VALUE den = rb_rational_den(x); - if (FIXNUM_P(den) && FIX2LONG(den) == 1) - return rb_rational_num(x); - } - return x; -} - -#ifndef USE_PACK -#define set_to_simple(obj, x, _nth, _jd ,_sg, _year, _mon, _mday, _flags) \ -do {\ - RB_OBJ_WRITE((obj), &(x)->nth, canon(_nth)); \ - (x)->jd = _jd;\ - (x)->sg = (date_sg_t)(_sg);\ - (x)->year = _year;\ - (x)->mon = _mon;\ - (x)->mday = _mday;\ - (x)->flags = (_flags) & ~COMPLEX_DAT;\ -} while (0) -#else -#define set_to_simple(obj, x, _nth, _jd ,_sg, _year, _mon, _mday, _flags) \ -do {\ - RB_OBJ_WRITE((obj), &(x)->nth, canon(_nth)); \ - (x)->jd = _jd;\ - (x)->sg = (date_sg_t)(_sg);\ - (x)->year = _year;\ - (x)->pc = PACK2(_mon, _mday);\ - (x)->flags = (_flags) & ~COMPLEX_DAT;\ -} while (0) -#endif - -#ifndef USE_PACK -#define set_to_complex(obj, x, _nth, _jd ,_df, _sf, _of, _sg,\ -_year, _mon, _mday, _hour, _min, _sec, _flags) \ -do {\ - RB_OBJ_WRITE((obj), &(x)->nth, canon(_nth));\ - (x)->jd = _jd;\ - (x)->df = _df;\ - RB_OBJ_WRITE((obj), &(x)->sf, canon(_sf));\ - (x)->of = _of;\ - (x)->sg = (date_sg_t)(_sg);\ - (x)->year = _year;\ - (x)->mon = _mon;\ - (x)->mday = _mday;\ - (x)->hour = _hour;\ - (x)->min = _min;\ - (x)->sec = _sec;\ - (x)->flags = (_flags) | COMPLEX_DAT;\ -} while (0) -#else -#define set_to_complex(obj, x, _nth, _jd ,_df, _sf, _of, _sg,\ -_year, _mon, _mday, _hour, _min, _sec, _flags) \ -do {\ - RB_OBJ_WRITE((obj), &(x)->nth, canon(_nth));\ - (x)->jd = _jd;\ - (x)->df = _df;\ - RB_OBJ_WRITE((obj), &(x)->sf, canon(_sf));\ - (x)->of = _of;\ - (x)->sg = (date_sg_t)(_sg);\ - (x)->year = _year;\ - (x)->pc = PACK5(_mon, _mday, _hour, _min, _sec);\ - (x)->flags = (_flags) | COMPLEX_DAT;\ -} while (0) -#endif - -#ifndef USE_PACK -#define copy_simple_to_complex(obj, x, y) \ -do {\ - RB_OBJ_WRITE((obj), &(x)->nth, (y)->nth);\ - (x)->jd = (y)->jd;\ - (x)->df = 0;\ - (x)->sf = INT2FIX(0);\ - (x)->of = 0;\ - (x)->sg = (date_sg_t)((y)->sg);\ - (x)->year = (y)->year;\ - (x)->mon = (y)->mon;\ - (x)->mday = (y)->mday;\ - (x)->hour = 0;\ - (x)->min = 0;\ - (x)->sec = 0;\ - (x)->flags = (y)->flags;\ -} while (0) -#else -#define copy_simple_to_complex(obj, x, y) \ -do {\ - RB_OBJ_WRITE((obj), &(x)->nth, (y)->nth);\ - (x)->jd = (y)->jd;\ - (x)->df = 0;\ - RB_OBJ_WRITE((obj), &(x)->sf, INT2FIX(0));\ - (x)->of = 0;\ - (x)->sg = (date_sg_t)((y)->sg);\ - (x)->year = (y)->year;\ - (x)->pc = PACK5(EX_MON((y)->pc), EX_MDAY((y)->pc), 0, 0, 0);\ - (x)->flags = (y)->flags;\ -} while (0) -#endif - -#ifndef USE_PACK -#define copy_complex_to_simple(obj, x, y) \ -do {\ - RB_OBJ_WRITE((obj), &(x)->nth, (y)->nth);\ - (x)->jd = (y)->jd;\ - (x)->sg = (date_sg_t)((y)->sg);\ - (x)->year = (y)->year;\ - (x)->mon = (y)->mon;\ - (x)->mday = (y)->mday;\ - (x)->flags = (y)->flags;\ -} while (0) -#else -#define copy_complex_to_simple(obj, x, y) \ -do {\ - RB_OBJ_WRITE((obj), &(x)->nth, (y)->nth);\ - (x)->jd = (y)->jd;\ - (x)->sg = (date_sg_t)((y)->sg);\ - (x)->year = (y)->year;\ - (x)->pc = PACK2(EX_MON((y)->pc), EX_MDAY((y)->pc));\ - (x)->flags = (y)->flags;\ -} while (0) -#endif - -/* base */ - -static int c_valid_civil_p(int, int, int, double, - int *, int *, int *, int *); - -/* Check if using pure Gregorian calendar (sg == -Infinity) */ -#define c_gregorian_only_p(sg) (isinf(sg) && (sg) < 0) - -/* - * Fast path macros for pure Gregorian calendar. - * Sets *rjd to the JD value, *ns to 1 (new style), and returns. - */ -#define GREGORIAN_JD_FAST_PATH_RET(sg, jd_expr, rjd, ns) \ - if (c_gregorian_only_p(sg)) { \ - *(rjd) = (jd_expr); \ - *(ns) = 1; \ - return 1; \ - } - -#define GREGORIAN_JD_FAST_PATH(sg, jd_expr, rjd, ns) \ - if (c_gregorian_only_p(sg)) { \ - *(rjd) = (jd_expr); \ - *(ns) = 1; \ - return; \ - } - -/* Forward declarations for Neri-Schneider optimized functions */ -static int c_gregorian_civil_to_jd(int y, int m, int d); -static void c_gregorian_jd_to_civil(int jd, int *ry, int *rm, int *rd); -static int c_gregorian_fdoy(int y); -static int c_gregorian_ldoy(int y); -static int c_gregorian_ldom_jd(int y, int m); -static int ns_jd_in_range(int jd); - -static int -c_find_fdoy(int y, double sg, int *rjd, int *ns) -{ - int d, rm, rd; - - GREGORIAN_JD_FAST_PATH_RET(sg, c_gregorian_fdoy(y), rjd, ns); - - /* Keep existing loop for Julian/reform period */ - for (d = 1; d < 31; d++) - if (c_valid_civil_p(y, 1, d, sg, &rm, &rd, rjd, ns)) - return 1; - return 0; -} - -static int -c_find_ldoy(int y, double sg, int *rjd, int *ns) -{ - int i, rm, rd; - - GREGORIAN_JD_FAST_PATH_RET(sg, c_gregorian_ldoy(y), rjd, ns); - - /* Keep existing loop for Julian/reform period */ - for (i = 0; i < 30; i++) - if (c_valid_civil_p(y, 12, 31 - i, sg, &rm, &rd, rjd, ns)) - return 1; - return 0; -} - -#ifndef NDEBUG -/* :nodoc: */ -static int -c_find_fdom(int y, int m, double sg, int *rjd, int *ns) -{ - int d, rm, rd; - - for (d = 1; d < 31; d++) - if (c_valid_civil_p(y, m, d, sg, &rm, &rd, rjd, ns)) - return 1; - return 0; -} -#endif - -static int -c_find_ldom(int y, int m, double sg, int *rjd, int *ns) -{ - int i, rm, rd; - - GREGORIAN_JD_FAST_PATH_RET(sg, c_gregorian_ldom_jd(y, m), rjd, ns); - - /* Keep existing loop for Julian/reform period */ - for (i = 0; i < 30; i++) - if (c_valid_civil_p(y, m, 31 - i, sg, &rm, &rd, rjd, ns)) - return 1; - return 0; -} - -static void -c_civil_to_jd(int y, int m, int d, double sg, int *rjd, int *ns) -{ - int jd; - - GREGORIAN_JD_FAST_PATH(sg, c_gregorian_civil_to_jd(y, m, d), rjd, ns); - - /* Calculate Gregorian JD using optimized algorithm */ - jd = c_gregorian_civil_to_jd(y, m, d); - - if (jd < sg) { - /* Before Gregorian switchover - use Julian calendar */ - int y2 = y, m2 = m; - if (m2 <= 2) { - y2 -= 1; - m2 += 12; - } - jd = (int)(floor(365.25 * (y2 + 4716)) + - floor(30.6001 * (m2 + 1)) + - d - 1524); - *ns = 0; - } - else { - *ns = 1; - } - - *rjd = jd; -} - -static void -c_jd_to_civil(int jd, double sg, int *ry, int *rm, int *rdom) -{ - /* Fast path: pure Gregorian or date after switchover, within safe range */ - if ((c_gregorian_only_p(sg) || jd >= sg) && ns_jd_in_range(jd)) { - c_gregorian_jd_to_civil(jd, ry, rm, rdom); - return; - } - - /* Original algorithm for Julian calendar or extreme dates */ - { - double x, a, b, c, d, e, y, m, dom; - - if (jd < sg) - a = jd; - else { - x = floor((jd - 1867216.25) / 36524.25); - a = jd + 1 + x - floor(x / 4.0); - } - b = a + 1524; - c = floor((b - 122.1) / 365.25); - d = floor(365.25 * c); - e = floor((b - d) / 30.6001); - dom = b - d - floor(30.6001 * e); - if (e <= 13) { - m = e - 1; - y = c - 4716; - } - else { - m = e - 13; - y = c - 4715; - } - - *ry = (int)y; - *rm = (int)m; - *rdom = (int)dom; - } -} - -static void -c_ordinal_to_jd(int y, int d, double sg, int *rjd, int *ns) -{ - int ns2; - - c_find_fdoy(y, sg, rjd, &ns2); - *rjd += d - 1; - *ns = (*rjd < sg) ? 0 : 1; -} - -static void -c_jd_to_ordinal(int jd, double sg, int *ry, int *rd) -{ - int rm2, rd2, rjd, ns; - - c_jd_to_civil(jd, sg, ry, &rm2, &rd2); - c_find_fdoy(*ry, sg, &rjd, &ns); - *rd = (jd - rjd) + 1; -} - -static void -c_commercial_to_jd(int y, int w, int d, double sg, int *rjd, int *ns) -{ - int rjd2, ns2; - - c_find_fdoy(y, sg, &rjd2, &ns2); - rjd2 += 3; - *rjd = - (rjd2 - MOD((rjd2 - 1) + 1, 7)) + - 7 * (w - 1) + - (d - 1); - *ns = (*rjd < sg) ? 0 : 1; -} - -static void -c_jd_to_commercial(int jd, double sg, int *ry, int *rw, int *rd) -{ - int ry2, rm2, rd2, a, rjd2, ns2; - - c_jd_to_civil(jd - 3, sg, &ry2, &rm2, &rd2); - a = ry2; - c_commercial_to_jd(a + 1, 1, 1, sg, &rjd2, &ns2); - if (jd >= rjd2) - *ry = a + 1; - else { - c_commercial_to_jd(a, 1, 1, sg, &rjd2, &ns2); - *ry = a; - } - *rw = 1 + DIV(jd - rjd2, 7); - *rd = MOD(jd + 1, 7); - if (*rd == 0) - *rd = 7; -} - -static void -c_weeknum_to_jd(int y, int w, int d, int f, double sg, int *rjd, int *ns) -{ - int rjd2, ns2; - - c_find_fdoy(y, sg, &rjd2, &ns2); - rjd2 += 6; - *rjd = (rjd2 - MOD(((rjd2 - f) + 1), 7) - 7) + 7 * w + d; - *ns = (*rjd < sg) ? 0 : 1; -} - -static void -c_jd_to_weeknum(int jd, int f, double sg, int *ry, int *rw, int *rd) -{ - int rm, rd2, rjd, ns, j; - - c_jd_to_civil(jd, sg, ry, &rm, &rd2); - c_find_fdoy(*ry, sg, &rjd, &ns); - rjd += 6; - j = jd - (rjd - MOD((rjd - f) + 1, 7)) + 7; - *rw = (int)DIV(j, 7); - *rd = (int)MOD(j, 7); -} - -#ifndef NDEBUG -/* :nodoc: */ -static void -c_nth_kday_to_jd(int y, int m, int n, int k, double sg, int *rjd, int *ns) -{ - int rjd2, ns2; - - if (n > 0) { - c_find_fdom(y, m, sg, &rjd2, &ns2); - rjd2 -= 1; - } - else { - c_find_ldom(y, m, sg, &rjd2, &ns2); - rjd2 += 7; - } - *rjd = (rjd2 - MOD((rjd2 - k) + 1, 7)) + 7 * n; - *ns = (*rjd < sg) ? 0 : 1; -} -#endif - -inline static int -c_jd_to_wday(int jd) -{ - return MOD(jd + 1, 7); -} - -#ifndef NDEBUG -/* :nodoc: */ -static void -c_jd_to_nth_kday(int jd, double sg, int *ry, int *rm, int *rn, int *rk) -{ - int rd, rjd, ns2; - - c_jd_to_civil(jd, sg, ry, rm, &rd); - c_find_fdom(*ry, *rm, sg, &rjd, &ns2); - *rn = DIV(jd - rjd, 7) + 1; - *rk = c_jd_to_wday(jd); -} -#endif - -static int -c_valid_ordinal_p(int y, int d, double sg, - int *rd, int *rjd, int *ns) -{ - int ry2, rd2; - - if (d < 0) { - int rjd2, ns2; - - if (!c_find_ldoy(y, sg, &rjd2, &ns2)) - return 0; - c_jd_to_ordinal(rjd2 + d + 1, sg, &ry2, &rd2); - if (ry2 != y) - return 0; - d = rd2; - } - c_ordinal_to_jd(y, d, sg, rjd, ns); - c_jd_to_ordinal(*rjd, sg, &ry2, &rd2); - if (ry2 != y || rd2 != d) - return 0; - return 1; -} - -static const int monthtab[2][13] = { - { 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }, - { 0, 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 } -}; - -inline static int -c_julian_leap_p(int y) -{ - return MOD(y, 4) == 0; -} - -inline static int -c_gregorian_leap_p(int y) -{ - return (MOD(y, 4) == 0 && y % 100 != 0) || MOD(y, 400) == 0; -} - -static int -c_julian_last_day_of_month(int y, int m) -{ - assert(m >= 1 && m <= 12); - return monthtab[c_julian_leap_p(y) ? 1 : 0][m]; -} - -static int -c_gregorian_last_day_of_month(int y, int m) -{ - assert(m >= 1 && m <= 12); - return monthtab[c_gregorian_leap_p(y) ? 1 : 0][m]; -} - -/* - * Neri-Schneider algorithm for optimized Gregorian date conversion. - * Reference: Neri & Schneider, "Euclidean Affine Functions and Applications - * to Calendar Algorithms", Software: Practice and Experience, 2023. - * https://arxiv.org/abs/2102.06959 - * - * This algorithm provides ~2-3x speedup over traditional floating-point - * implementations by using pure integer arithmetic with multiplication - * and bit-shifts instead of expensive division operations. - */ - -/* JDN of March 1, Year 0 in proleptic Gregorian calendar */ -#define NS_EPOCH 1721120 - -/* Days in a 4-year cycle (3 normal years + 1 leap year) */ -#define NS_DAYS_IN_4_YEARS 1461 - -/* Days in a 400-year Gregorian cycle (97 leap years in 400 years) */ -#define NS_DAYS_IN_400_YEARS 146097 - -/* Years per century */ -#define NS_YEARS_PER_CENTURY 100 - -/* - * Multiplier for extracting year within century using fixed-point arithmetic. - * This is ceil(2^32 / NS_DAYS_IN_4_YEARS) for the Euclidean affine function. - */ -#define NS_YEAR_MULTIPLIER 2939745 - -/* - * Coefficients for month calculation from day-of-year. - * Maps day-of-year to month using: month = (NS_MONTH_COEFF * doy + NS_MONTH_OFFSET) >> 16 - */ -#define NS_MONTH_COEFF 2141 -#define NS_MONTH_OFFSET 197913 - -/* - * Coefficients for civil date to JDN month contribution. - * Maps month to accumulated days: days = (NS_CIVIL_MONTH_COEFF * m - NS_CIVIL_MONTH_OFFSET) / 32 - */ -#define NS_CIVIL_MONTH_COEFF 979 -#define NS_CIVIL_MONTH_OFFSET 2919 -#define NS_CIVIL_MONTH_DIVISOR 32 - -/* Days from March 1 to December 31 (for Jan/Feb year adjustment) */ -#define NS_DAYS_BEFORE_NEW_YEAR 306 - -/* - * Safe bounds for Neri-Schneider algorithm to avoid integer overflow. - * These correspond to approximately years -1,000,000 to +1,000,000. - */ -#define NS_JD_MIN -364000000 -#define NS_JD_MAX 538000000 - -inline static int -ns_jd_in_range(int jd) -{ - return jd >= NS_JD_MIN && jd <= NS_JD_MAX; -} - -/* Optimized: Gregorian date -> Julian Day Number */ -static int -c_gregorian_civil_to_jd(int y, int m, int d) -{ - /* Shift epoch to March 1 of year 0 (Jan/Feb belong to previous year) */ - int j = (m < 3) ? 1 : 0; - int y0 = y - j; - int m0 = j ? m + 12 : m; - int d0 = d - 1; - - /* Calculate year contribution with leap year correction */ - int q1 = DIV(y0, NS_YEARS_PER_CENTURY); - int yc = DIV(NS_DAYS_IN_4_YEARS * y0, 4) - q1 + DIV(q1, 4); - - /* Calculate month contribution using integer arithmetic */ - int mc = (NS_CIVIL_MONTH_COEFF * m0 - NS_CIVIL_MONTH_OFFSET) / NS_CIVIL_MONTH_DIVISOR; - - /* Combine and add epoch offset to get JDN */ - return yc + mc + d0 + NS_EPOCH; -} - -/* Optimized: Julian Day Number -> Gregorian date */ -static void -c_gregorian_jd_to_civil(int jd, int *ry, int *rm, int *rd) -{ - int r0, n1, q1, r1, n2, q2, r2, n3, q3, r3, y0, j; - uint64_t u2; - - /* Convert JDN to rata die (March 1, Year 0 epoch) */ - r0 = jd - NS_EPOCH; - - /* Extract century and day within 400-year cycle */ - /* Use Euclidean (floor) division for negative values */ - n1 = 4 * r0 + 3; - q1 = DIV(n1, NS_DAYS_IN_400_YEARS); - r1 = MOD(n1, NS_DAYS_IN_400_YEARS) / 4; - - /* Calculate year within century and day of year */ - n2 = 4 * r1 + 3; - /* Use 64-bit arithmetic to avoid overflow */ - u2 = (uint64_t)NS_YEAR_MULTIPLIER * (uint64_t)n2; - q2 = (int)(u2 >> 32); - r2 = (int)((uint32_t)u2 / NS_YEAR_MULTIPLIER / 4); - - /* Calculate month and day using integer arithmetic */ - n3 = NS_MONTH_COEFF * r2 + NS_MONTH_OFFSET; - q3 = n3 >> 16; - r3 = (n3 & 0xFFFF) / NS_MONTH_COEFF; - - /* Combine century and year */ - y0 = NS_YEARS_PER_CENTURY * q1 + q2; - - /* Adjust for January/February (shift from fiscal year) */ - j = (r2 >= NS_DAYS_BEFORE_NEW_YEAR) ? 1 : 0; - - *ry = y0 + j; - *rm = j ? q3 - 12 : q3; - *rd = r3 + 1; -} - -/* O(1) first day of year for Gregorian calendar */ -inline static int -c_gregorian_fdoy(int y) -{ - return c_gregorian_civil_to_jd(y, 1, 1); -} - -/* O(1) last day of year for Gregorian calendar */ -inline static int -c_gregorian_ldoy(int y) -{ - return c_gregorian_civil_to_jd(y, 12, 31); -} - -/* O(1) last day of month (JDN) for Gregorian calendar */ -inline static int -c_gregorian_ldom_jd(int y, int m) -{ - return c_gregorian_civil_to_jd(y, m, c_gregorian_last_day_of_month(y, m)); -} - -static int -c_valid_julian_p(int y, int m, int d, int *rm, int *rd) -{ - int last; - - if (m < 0) - m += 13; - if (m < 1 || m > 12) - return 0; - last = c_julian_last_day_of_month(y, m); - if (d < 0) - d = last + d + 1; - if (d < 1 || d > last) - return 0; - *rm = m; - *rd = d; - return 1; -} - -static int -c_valid_gregorian_p(int y, int m, int d, int *rm, int *rd) -{ - int last; - - if (m < 0) - m += 13; - if (m < 1 || m > 12) - return 0; - last = c_gregorian_last_day_of_month(y, m); - if (d < 0) - d = last + d + 1; - if (d < 1 || d > last) - return 0; - *rm = m; - *rd = d; - return 1; -} - -static int -c_valid_civil_p(int y, int m, int d, double sg, - int *rm, int *rd, int *rjd, int *ns) -{ - int ry; - - if (m < 0) - m += 13; - if (m < 1 || m > 12) - return 0; - if (d < 0) { - if (!c_find_ldom(y, m, sg, rjd, ns)) - return 0; - c_jd_to_civil(*rjd + d + 1, sg, &ry, rm, rd); - if (ry != y || *rm != m) - return 0; - d = *rd; - } - c_civil_to_jd(y, m, d, sg, rjd, ns); - c_jd_to_civil(*rjd, sg, &ry, rm, rd); - if (ry != y || *rm != m || *rd != d) - return 0; - return 1; -} - -static int -c_valid_commercial_p(int y, int w, int d, double sg, - int *rw, int *rd, int *rjd, int *ns) -{ - int ns2, ry2, rw2, rd2; - - if (d < 0) - d += 8; - if (w < 0) { - int rjd2; - - c_commercial_to_jd(y + 1, 1, 1, sg, &rjd2, &ns2); - c_jd_to_commercial(rjd2 + w * 7, sg, &ry2, &rw2, &rd2); - if (ry2 != y) - return 0; - w = rw2; - } - c_commercial_to_jd(y, w, d, sg, rjd, ns); - c_jd_to_commercial(*rjd, sg, &ry2, rw, rd); - if (y != ry2 || w != *rw || d != *rd) - return 0; - return 1; -} - -static int -c_valid_weeknum_p(int y, int w, int d, int f, double sg, - int *rw, int *rd, int *rjd, int *ns) -{ - int ns2, ry2, rw2, rd2; - - if (d < 0) - d += 7; - if (w < 0) { - int rjd2; - - c_weeknum_to_jd(y + 1, 1, f, f, sg, &rjd2, &ns2); - c_jd_to_weeknum(rjd2 + w * 7, f, sg, &ry2, &rw2, &rd2); - if (ry2 != y) - return 0; - w = rw2; - } - c_weeknum_to_jd(y, w, d, f, sg, rjd, ns); - c_jd_to_weeknum(*rjd, f, sg, &ry2, rw, rd); - if (y != ry2 || w != *rw || d != *rd) - return 0; - return 1; -} - -#ifndef NDEBUG -/* :nodoc: */ -static int -c_valid_nth_kday_p(int y, int m, int n, int k, double sg, - int *rm, int *rn, int *rk, int *rjd, int *ns) -{ - int ns2, ry2, rm2, rn2, rk2; - - if (k < 0) - k += 7; - if (n < 0) { - int t, ny, nm, rjd2; - - t = y * 12 + m; - ny = DIV(t, 12); - nm = MOD(t, 12) + 1; - - c_nth_kday_to_jd(ny, nm, 1, k, sg, &rjd2, &ns2); - c_jd_to_nth_kday(rjd2 + n * 7, sg, &ry2, &rm2, &rn2, &rk2); - if (ry2 != y || rm2 != m) - return 0; - n = rn2; - } - c_nth_kday_to_jd(y, m, n, k, sg, rjd, ns); - c_jd_to_nth_kday(*rjd, sg, &ry2, rm, rn, rk); - if (y != ry2 || m != *rm || n != *rn || k != *rk) - return 0; - return 1; -} -#endif - -static int -c_valid_time_p(int h, int min, int s, int *rh, int *rmin, int *rs) -{ - if (h < 0) - h += 24; - if (min < 0) - min += 60; - if (s < 0) - s += 60; - *rh = h; - *rmin = min; - *rs = s; - return !(h < 0 || h > 24 || - min < 0 || min > 59 || - s < 0 || s > 59 || - (h == 24 && (min > 0 || s > 0))); -} - -inline static int -c_valid_start_p(double sg) -{ - if (isnan(sg)) - return 0; - if (isinf(sg)) - return 1; - if (sg < REFORM_BEGIN_JD || sg > REFORM_END_JD) - return 0; - return 1; -} - -inline static int -df_local_to_utc(int df, int of) -{ - df -= of; - if (df < 0) - df += DAY_IN_SECONDS; - else if (df >= DAY_IN_SECONDS) - df -= DAY_IN_SECONDS; - return df; -} - -inline static int -df_utc_to_local(int df, int of) -{ - df += of; - if (df < 0) - df += DAY_IN_SECONDS; - else if (df >= DAY_IN_SECONDS) - df -= DAY_IN_SECONDS; - return df; -} - -inline static int -jd_local_to_utc(int jd, int df, int of) -{ - df -= of; - if (df < 0) - jd -= 1; - else if (df >= DAY_IN_SECONDS) - jd += 1; - return jd; -} - -inline static int -jd_utc_to_local(int jd, int df, int of) -{ - df += of; - if (df < 0) - jd -= 1; - else if (df >= DAY_IN_SECONDS) - jd += 1; - return jd; -} - -inline static int -time_to_df(int h, int min, int s) -{ - return h * HOUR_IN_SECONDS + min * MINUTE_IN_SECONDS + s; -} - -inline static void -df_to_time(int df, int *h, int *min, int *s) -{ - *h = df / HOUR_IN_SECONDS; - df %= HOUR_IN_SECONDS; - *min = df / MINUTE_IN_SECONDS; - *s = df % MINUTE_IN_SECONDS; -} - -static VALUE -sec_to_day(VALUE s) -{ - if (FIXNUM_P(s)) - return rb_rational_new2(s, INT2FIX(DAY_IN_SECONDS)); - return f_quo(s, INT2FIX(DAY_IN_SECONDS)); -} - -inline static VALUE -isec_to_day(int s) -{ - return sec_to_day(INT2FIX(s)); -} - -static VALUE -ns_to_day(VALUE n) -{ - if (FIXNUM_P(n)) - return rb_rational_new2(n, day_in_nanoseconds); - return f_quo(n, day_in_nanoseconds); -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -ms_to_sec(VALUE m) -{ - if (FIXNUM_P(m)) - return rb_rational_new2(m, INT2FIX(SECOND_IN_MILLISECONDS)); - return f_quo(m, INT2FIX(SECOND_IN_MILLISECONDS)); -} -#endif - -static VALUE -ns_to_sec(VALUE n) -{ - if (FIXNUM_P(n)) - return rb_rational_new2(n, INT2FIX(SECOND_IN_NANOSECONDS)); - return f_quo(n, INT2FIX(SECOND_IN_NANOSECONDS)); -} - -#ifndef NDEBUG -/* :nodoc: */ -inline static VALUE -ins_to_day(int n) -{ - return ns_to_day(INT2FIX(n)); -} -#endif - -static int -safe_mul_p(VALUE x, long m) -{ - long ix; - - if (!FIXNUM_P(x)) - return 0; - ix = FIX2LONG(x); - if (ix < 0) { - if (ix <= (FIXNUM_MIN / m)) - return 0; - } - else { - if (ix >= (FIXNUM_MAX / m)) - return 0; - } - return 1; -} - -static VALUE -day_to_sec(VALUE d) -{ - if (safe_mul_p(d, DAY_IN_SECONDS)) - return LONG2FIX(FIX2LONG(d) * DAY_IN_SECONDS); - return f_mul(d, INT2FIX(DAY_IN_SECONDS)); -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -day_to_ns(VALUE d) -{ - return f_mul(d, day_in_nanoseconds); -} -#endif - -static VALUE -sec_to_ms(VALUE s) -{ - if (safe_mul_p(s, SECOND_IN_MILLISECONDS)) - return LONG2FIX(FIX2LONG(s) * SECOND_IN_MILLISECONDS); - return f_mul(s, INT2FIX(SECOND_IN_MILLISECONDS)); -} - -static VALUE -sec_to_ns(VALUE s) -{ - if (safe_mul_p(s, SECOND_IN_NANOSECONDS)) - return LONG2FIX(FIX2LONG(s) * SECOND_IN_NANOSECONDS); - return f_mul(s, INT2FIX(SECOND_IN_NANOSECONDS)); -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -isec_to_ns(int s) -{ - return sec_to_ns(INT2FIX(s)); -} -#endif - -static VALUE -div_day(VALUE d, VALUE *f) -{ - if (f) - *f = f_mod(d, INT2FIX(1)); - return f_floor(d); -} - -static VALUE -div_df(VALUE d, VALUE *f) -{ - VALUE s = day_to_sec(d); - - if (f) - *f = f_mod(s, INT2FIX(1)); - return f_floor(s); -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -div_sf(VALUE s, VALUE *f) -{ - VALUE n = sec_to_ns(s); - - if (f) - *f = f_mod(n, INT2FIX(1)); - return f_floor(n); -} -#endif - -static void -decode_day(VALUE d, VALUE *jd, VALUE *df, VALUE *sf) -{ - VALUE f; - - *jd = div_day(d, &f); - *df = div_df(f, &f); - *sf = sec_to_ns(f); -} - -inline static double -s_virtual_sg(union DateData *x) -{ - if (isinf(x->s.sg)) - return x->s.sg; - if (f_zero_p(x->s.nth)) - return x->s.sg; - else if (f_negative_p(x->s.nth)) - return positive_inf; - return negative_inf; -} - -inline static double -c_virtual_sg(union DateData *x) -{ - if (isinf(x->c.sg)) - return x->c.sg; - if (f_zero_p(x->c.nth)) - return x->c.sg; - else if (f_negative_p(x->c.nth)) - return positive_inf; - return negative_inf; -} - -inline static double -m_virtual_sg(union DateData *x) -{ - if (simple_dat_p(x)) - return s_virtual_sg(x); - else - return c_virtual_sg(x); -} - -#define canonicalize_jd(_nth, _jd) \ -do {\ - if (_jd < 0) {\ - _nth = f_sub(_nth, INT2FIX(1));\ - _jd += CM_PERIOD;\ - }\ - if (_jd >= CM_PERIOD) {\ - _nth = f_add(_nth, INT2FIX(1));\ - _jd -= CM_PERIOD;\ - }\ -} while (0) - -inline static void -canonicalize_s_jd(VALUE obj, union DateData *x) -{ - int j = x->s.jd; - VALUE nth = x->s.nth; - assert(have_jd_p(x)); - canonicalize_jd(nth, x->s.jd); - RB_OBJ_WRITE(obj, &x->s.nth, nth); - if (x->s.jd != j) - x->flags &= ~HAVE_CIVIL; -} - -inline static void -get_s_jd(union DateData *x) -{ - assert(simple_dat_p(x)); - if (!have_jd_p(x)) { - int jd, ns; - - assert(have_civil_p(x)); -#ifndef USE_PACK - c_civil_to_jd(x->s.year, x->s.mon, x->s.mday, - s_virtual_sg(x), &jd, &ns); -#else - c_civil_to_jd(x->s.year, EX_MON(x->s.pc), EX_MDAY(x->s.pc), - s_virtual_sg(x), &jd, &ns); -#endif - x->s.jd = jd; - x->s.flags |= HAVE_JD; - } -} - -inline static void -get_s_civil(union DateData *x) -{ - assert(simple_dat_p(x)); - if (!have_civil_p(x)) { - int y, m, d; - - assert(have_jd_p(x)); - c_jd_to_civil(x->s.jd, s_virtual_sg(x), &y, &m, &d); - x->s.year = y; -#ifndef USE_PACK - x->s.mon = m; - x->s.mday = d; -#else - x->s.pc = PACK2(m, d); -#endif - x->s.flags |= HAVE_CIVIL; - } -} - -inline static void -get_c_df(union DateData *x) -{ - assert(complex_dat_p(x)); - if (!have_df_p(x)) { - assert(have_time_p(x)); -#ifndef USE_PACK - x->c.df = df_local_to_utc(time_to_df(x->c.hour, x->c.min, x->c.sec), - x->c.of); -#else - x->c.df = df_local_to_utc(time_to_df(EX_HOUR(x->c.pc), - EX_MIN(x->c.pc), - EX_SEC(x->c.pc)), - x->c.of); -#endif - x->c.flags |= HAVE_DF; - } -} - -inline static void -get_c_time(union DateData *x) -{ - assert(complex_dat_p(x)); - if (!have_time_p(x)) { -#ifndef USE_PACK - int r; - assert(have_df_p(x)); - r = df_utc_to_local(x->c.df, x->c.of); - df_to_time(r, &x->c.hour, &x->c.min, &x->c.sec); - x->c.flags |= HAVE_TIME; -#else - int r, m, d, h, min, s; - - assert(have_df_p(x)); - m = EX_MON(x->c.pc); - d = EX_MDAY(x->c.pc); - r = df_utc_to_local(x->c.df, x->c.of); - df_to_time(r, &h, &min, &s); - x->c.pc = PACK5(m, d, h, min, s); - x->c.flags |= HAVE_TIME; -#endif - } -} - -inline static void -canonicalize_c_jd(VALUE obj, union DateData *x) -{ - int j = x->c.jd; - VALUE nth = x->c.nth; - assert(have_jd_p(x)); - canonicalize_jd(nth, x->c.jd); - RB_OBJ_WRITE(obj, &x->c.nth, nth); - if (x->c.jd != j) - x->flags &= ~HAVE_CIVIL; -} - -inline static void -get_c_jd(union DateData *x) -{ - assert(complex_dat_p(x)); - if (!have_jd_p(x)) { - int jd, ns; - - assert(have_civil_p(x)); -#ifndef USE_PACK - c_civil_to_jd(x->c.year, x->c.mon, x->c.mday, - c_virtual_sg(x), &jd, &ns); -#else - c_civil_to_jd(x->c.year, EX_MON(x->c.pc), EX_MDAY(x->c.pc), - c_virtual_sg(x), &jd, &ns); -#endif - - get_c_time(x); -#ifndef USE_PACK - x->c.jd = jd_local_to_utc(jd, - time_to_df(x->c.hour, x->c.min, x->c.sec), - x->c.of); -#else - x->c.jd = jd_local_to_utc(jd, - time_to_df(EX_HOUR(x->c.pc), - EX_MIN(x->c.pc), - EX_SEC(x->c.pc)), - x->c.of); -#endif - x->c.flags |= HAVE_JD; - } -} - -inline static void -get_c_civil(union DateData *x) -{ - assert(complex_dat_p(x)); - if (!have_civil_p(x)) { -#ifndef USE_PACK - int jd, y, m, d; -#else - int jd, y, m, d, h, min, s; -#endif - - assert(have_jd_p(x)); - get_c_df(x); - jd = jd_utc_to_local(x->c.jd, x->c.df, x->c.of); - c_jd_to_civil(jd, c_virtual_sg(x), &y, &m, &d); - x->c.year = y; -#ifndef USE_PACK - x->c.mon = m; - x->c.mday = d; -#else - h = EX_HOUR(x->c.pc); - min = EX_MIN(x->c.pc); - s = EX_SEC(x->c.pc); - x->c.pc = PACK5(m, d, h, min, s); -#endif - x->c.flags |= HAVE_CIVIL; - } -} - -inline static int -local_jd(union DateData *x) -{ - assert(complex_dat_p(x)); - assert(have_jd_p(x)); - assert(have_df_p(x)); - return jd_utc_to_local(x->c.jd, x->c.df, x->c.of); -} - -inline static int -local_df(union DateData *x) -{ - assert(complex_dat_p(x)); - assert(have_df_p(x)); - return df_utc_to_local(x->c.df, x->c.of); -} - -static void -decode_year(VALUE y, double style, - VALUE *nth, int *ry) -{ - int period; - VALUE t; - - period = (style < 0) ? - CM_PERIOD_GCY : - CM_PERIOD_JCY; - if (FIXNUM_P(y)) { - long iy, it, inth; - - iy = FIX2LONG(y); - if (iy >= (FIXNUM_MAX - 4712)) - goto big; - it = iy + 4712; /* shift */ - inth = DIV(it, ((long)period)); - *nth = LONG2FIX(inth); - if (inth) - it = MOD(it, ((long)period)); - *ry = (int)it - 4712; /* unshift */ - return; - } - big: - t = f_add(y, INT2FIX(4712)); /* shift */ - *nth = f_idiv(t, INT2FIX(period)); - if (f_nonzero_p(*nth)) - t = f_mod(t, INT2FIX(period)); - *ry = FIX2INT(t) - 4712; /* unshift */ -} - -static void -encode_year(VALUE nth, int y, double style, - VALUE *ry) -{ - int period; - VALUE t; - - period = (style < 0) ? - CM_PERIOD_GCY : - CM_PERIOD_JCY; - if (f_zero_p(nth)) - *ry = INT2FIX(y); - else { - t = f_mul(INT2FIX(period), nth); - t = f_add(t, INT2FIX(y)); - *ry = t; - } -} - -static void -decode_jd(VALUE jd, VALUE *nth, int *rjd) -{ - *nth = f_idiv(jd, INT2FIX(CM_PERIOD)); - if (f_zero_p(*nth)) { - *rjd = FIX2INT(jd); - return; - } - *rjd = FIX2INT(f_mod(jd, INT2FIX(CM_PERIOD))); -} - -static void -encode_jd(VALUE nth, int jd, VALUE *rjd) -{ - if (f_zero_p(nth)) { - *rjd = INT2FIX(jd); - return; - } - *rjd = f_add(f_mul(INT2FIX(CM_PERIOD), nth), INT2FIX(jd)); -} - -inline static double -guess_style(VALUE y, double sg) /* -/+oo or zero */ -{ - double style = 0; - - if (isinf(sg)) - style = sg; - else if (!FIXNUM_P(y)) - style = f_positive_p(y) ? negative_inf : positive_inf; - else { - long iy = FIX2LONG(y); - - assert(FIXNUM_P(y)); - if (iy < REFORM_BEGIN_YEAR) - style = positive_inf; - else if (iy > REFORM_END_YEAR) - style = negative_inf; - } - return style; -} - -inline static void -m_canonicalize_jd(VALUE obj, union DateData *x) -{ - if (simple_dat_p(x)) { - get_s_jd(x); - canonicalize_s_jd(obj, x); - } - else { - get_c_jd(x); - canonicalize_c_jd(obj, x); - } -} - -inline static VALUE -m_nth(union DateData *x) -{ - if (simple_dat_p(x)) - return x->s.nth; - else { - get_c_civil(x); - return x->c.nth; - } -} - -inline static int -m_jd(union DateData *x) -{ - if (simple_dat_p(x)) { - get_s_jd(x); - return x->s.jd; - } - else { - get_c_jd(x); - return x->c.jd; - } -} - -static VALUE -m_real_jd(union DateData *x) -{ - VALUE nth, rjd; - int jd; - - nth = m_nth(x); - jd = m_jd(x); - - encode_jd(nth, jd, &rjd); - return rjd; -} - -static int -m_local_jd(union DateData *x) -{ - if (simple_dat_p(x)) { - get_s_jd(x); - return x->s.jd; - } - else { - get_c_jd(x); - get_c_df(x); - return local_jd(x); - } -} - -static VALUE -m_real_local_jd(union DateData *x) -{ - VALUE nth, rjd; - int jd; - - nth = m_nth(x); - jd = m_local_jd(x); - - encode_jd(nth, jd, &rjd); - return rjd; -} - -inline static int -m_df(union DateData *x) -{ - if (simple_dat_p(x)) - return 0; - else { - get_c_df(x); - return x->c.df; - } -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -m_df_in_day(union DateData *x) -{ - return isec_to_day(m_df(x)); -} -#endif - -static int -m_local_df(union DateData *x) -{ - if (simple_dat_p(x)) - return 0; - else { - get_c_df(x); - return local_df(x); - } -} - -#ifndef NDEBUG -static VALUE -m_local_df_in_day(union DateData *x) -{ - return isec_to_day(m_local_df(x)); -} -#endif - -inline static VALUE -m_sf(union DateData *x) -{ - if (simple_dat_p(x)) - return INT2FIX(0); - else - return x->c.sf; -} - -#ifndef NDEBUG -static VALUE -m_sf_in_day(union DateData *x) -{ - return ns_to_day(m_sf(x)); -} -#endif - -static VALUE -m_sf_in_sec(union DateData *x) -{ - return ns_to_sec(m_sf(x)); -} - -static VALUE -m_fr(union DateData *x) -{ - if (simple_dat_p(x)) - return INT2FIX(0); - else { - int df; - VALUE sf, fr; - - df = m_local_df(x); - sf = m_sf(x); - fr = isec_to_day(df); - if (f_nonzero_p(sf)) - fr = f_add(fr, ns_to_day(sf)); - return fr; - } -} - -#define HALF_DAYS_IN_SECONDS (DAY_IN_SECONDS / 2) - -static VALUE -m_ajd(union DateData *x) -{ - VALUE r, sf; - int df; - - if (simple_dat_p(x)) { - r = m_real_jd(x); - if (FIXNUM_P(r) && FIX2LONG(r) <= (FIXNUM_MAX / 2) && FIX2LONG(r) >= (FIXNUM_MIN + 1) / 2) { - long ir = FIX2LONG(r); - ir = ir * 2 - 1; - return rb_rational_new2(LONG2FIX(ir), INT2FIX(2)); - } - else - return rb_rational_new2(f_sub(f_mul(r, - INT2FIX(2)), - INT2FIX(1)), - INT2FIX(2)); - } - - r = m_real_jd(x); - df = m_df(x); - df -= HALF_DAYS_IN_SECONDS; - if (df) - r = f_add(r, isec_to_day(df)); - sf = m_sf(x); - if (f_nonzero_p(sf)) - r = f_add(r, ns_to_day(sf)); - - return r; -} - -static VALUE -m_amjd(union DateData *x) -{ - VALUE r, sf; - int df; - - r = m_real_jd(x); - if (FIXNUM_P(r) && FIX2LONG(r) >= (FIXNUM_MIN + 2400001)) { - long ir = FIX2LONG(r); - ir -= 2400001; - r = rb_rational_new1(LONG2FIX(ir)); - } - else - r = rb_rational_new1(f_sub(m_real_jd(x), - INT2FIX(2400001))); - - if (simple_dat_p(x)) - return r; - - df = m_df(x); - if (df) - r = f_add(r, isec_to_day(df)); - sf = m_sf(x); - if (f_nonzero_p(sf)) - r = f_add(r, ns_to_day(sf)); - - return r; -} - -inline static int -m_of(union DateData *x) -{ - if (simple_dat_p(x)) - return 0; - else { - get_c_jd(x); - return x->c.of; - } -} - -static VALUE -m_of_in_day(union DateData *x) -{ - return isec_to_day(m_of(x)); -} - -inline static double -m_sg(union DateData *x) -{ - if (simple_dat_p(x)) - return x->s.sg; - else { - get_c_jd(x); - return x->c.sg; - } -} - -static int -m_julian_p(union DateData *x) -{ - int jd; - double sg; - - if (simple_dat_p(x)) { - get_s_jd(x); - jd = x->s.jd; - sg = s_virtual_sg(x); - } - else { - get_c_jd(x); - jd = x->c.jd; - sg = c_virtual_sg(x); - } - if (isinf(sg)) - return sg == positive_inf; - return jd < sg; -} - -inline static int -m_gregorian_p(union DateData *x) -{ - return !m_julian_p(x); -} - -inline static int -m_proleptic_julian_p(union DateData *x) -{ - double sg; - - sg = m_sg(x); - if (isinf(sg) && sg > 0) - return 1; - return 0; -} - -inline static int -m_proleptic_gregorian_p(union DateData *x) -{ - double sg; - - sg = m_sg(x); - if (isinf(sg) && sg < 0) - return 1; - return 0; -} - -inline static int -m_year(union DateData *x) -{ - if (simple_dat_p(x)) { - get_s_civil(x); - return x->s.year; - } - else { - get_c_civil(x); - return x->c.year; - } -} - -static VALUE -m_real_year(union DateData *x) -{ - VALUE nth, ry; - int year; - - nth = m_nth(x); - year = m_year(x); - - if (f_zero_p(nth)) - return INT2FIX(year); - - encode_year(nth, year, - m_gregorian_p(x) ? -1 : +1, - &ry); - return ry; -} - -inline static int -m_mon(union DateData *x) -{ - if (simple_dat_p(x)) { - get_s_civil(x); -#ifndef USE_PACK - return x->s.mon; -#else - return EX_MON(x->s.pc); -#endif - } - else { - get_c_civil(x); -#ifndef USE_PACK - return x->c.mon; -#else - return EX_MON(x->c.pc); -#endif - } -} - -inline static int -m_mday(union DateData *x) -{ - if (simple_dat_p(x)) { - get_s_civil(x); -#ifndef USE_PACK - return x->s.mday; -#else - return EX_MDAY(x->s.pc); -#endif - } - else { - get_c_civil(x); -#ifndef USE_PACK - return x->c.mday; -#else - return EX_MDAY(x->c.pc); -#endif - } -} - -static const int yeartab[2][13] = { - { 0, 0, 31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334 }, - { 0, 0, 31, 60, 91, 121, 152, 182, 213, 244, 274, 305, 335 } -}; - -static int -c_julian_to_yday(int y, int m, int d) -{ - assert(m >= 1 && m <= 12); - return yeartab[c_julian_leap_p(y) ? 1 : 0][m] + d; -} - -static int -c_gregorian_to_yday(int y, int m, int d) -{ - assert(m >= 1 && m <= 12); - return yeartab[c_gregorian_leap_p(y) ? 1 : 0][m] + d; -} - -static int -m_yday(union DateData *x) -{ - int jd, ry, rd; - double sg; - - jd = m_local_jd(x); - sg = m_virtual_sg(x); /* !=m_sg() */ - - if (m_proleptic_gregorian_p(x) || - (jd - sg) > 366) - return c_gregorian_to_yday(m_year(x), m_mon(x), m_mday(x)); - if (m_proleptic_julian_p(x)) - return c_julian_to_yday(m_year(x), m_mon(x), m_mday(x)); - c_jd_to_ordinal(jd, sg, &ry, &rd); - return rd; -} - -static int -m_wday(union DateData *x) -{ - return c_jd_to_wday(m_local_jd(x)); -} - -static int -m_cwyear(union DateData *x) -{ - int ry, rw, rd; - - c_jd_to_commercial(m_local_jd(x), m_virtual_sg(x), /* !=m_sg() */ - &ry, &rw, &rd); - return ry; -} - -static VALUE -m_real_cwyear(union DateData *x) -{ - VALUE nth, ry; - int year; - - nth = m_nth(x); - year = m_cwyear(x); - - if (f_zero_p(nth)) - return INT2FIX(year); - - encode_year(nth, year, - m_gregorian_p(x) ? -1 : +1, - &ry); - return ry; -} - -static int -m_cweek(union DateData *x) -{ - int ry, rw, rd; - - c_jd_to_commercial(m_local_jd(x), m_virtual_sg(x), /* !=m_sg() */ - &ry, &rw, &rd); - return rw; -} - -static int -m_cwday(union DateData *x) -{ - int w; - - w = m_wday(x); - if (w == 0) - w = 7; - return w; -} - -static int -m_wnumx(union DateData *x, int f) -{ - int ry, rw, rd; - - c_jd_to_weeknum(m_local_jd(x), f, m_virtual_sg(x), /* !=m_sg() */ - &ry, &rw, &rd); - return rw; -} - -static int -m_wnum0(union DateData *x) -{ - return m_wnumx(x, 0); -} - -static int -m_wnum1(union DateData *x) -{ - return m_wnumx(x, 1); -} - -inline static int -m_hour(union DateData *x) -{ - if (simple_dat_p(x)) - return 0; - else { - get_c_time(x); -#ifndef USE_PACK - return x->c.hour; -#else - return EX_HOUR(x->c.pc); -#endif - } -} - -inline static int -m_min(union DateData *x) -{ - if (simple_dat_p(x)) - return 0; - else { - get_c_time(x); -#ifndef USE_PACK - return x->c.min; -#else - return EX_MIN(x->c.pc); -#endif - } -} - -inline static int -m_sec(union DateData *x) -{ - if (simple_dat_p(x)) - return 0; - else { - get_c_time(x); -#ifndef USE_PACK - return x->c.sec; -#else - return EX_SEC(x->c.pc); -#endif - } -} - -#define decode_offset(of,s,h,m)\ -do {\ - int a;\ - s = (of < 0) ? '-' : '+';\ - a = (of < 0) ? -of : of;\ - h = a / HOUR_IN_SECONDS;\ - m = a % HOUR_IN_SECONDS / MINUTE_IN_SECONDS;\ -} while (0) - -static VALUE -of2str(int of) -{ - int s, h, m; - - decode_offset(of, s, h, m); - return rb_enc_sprintf(rb_usascii_encoding(), "%c%02d:%02d", s, h, m); -} - -static VALUE -m_zone(union DateData *x) -{ - if (simple_dat_p(x)) - return rb_usascii_str_new2("+00:00"); - return of2str(m_of(x)); -} - -inline static VALUE -f_kind_of_p(VALUE x, VALUE c) -{ - return rb_obj_is_kind_of(x, c); -} - -inline static VALUE -k_date_p(VALUE x) -{ - return f_kind_of_p(x, cDate); -} - -inline static VALUE -k_numeric_p(VALUE x) -{ - return f_kind_of_p(x, rb_cNumeric); -} - -inline static VALUE -k_rational_p(VALUE x) -{ - return f_kind_of_p(x, rb_cRational); -} - -static inline void -expect_numeric(VALUE x) -{ - if (!k_numeric_p(x)) - rb_raise(rb_eTypeError, "expected numeric"); -} - -#ifndef NDEBUG -/* :nodoc: */ -static void -civil_to_jd(VALUE y, int m, int d, double sg, - VALUE *nth, int *ry, - int *rjd, - int *ns) -{ - double style = guess_style(y, sg); - - if (style == 0) { - int jd; - - c_civil_to_jd(FIX2INT(y), m, d, sg, &jd, ns); - decode_jd(INT2FIX(jd), nth, rjd); - if (f_zero_p(*nth)) - *ry = FIX2INT(y); - else { - VALUE nth2; - decode_year(y, *ns ? -1 : +1, &nth2, ry); - } - } - else { - decode_year(y, style, nth, ry); - c_civil_to_jd(*ry, m, d, style, rjd, ns); - } -} - -static void -jd_to_civil(VALUE jd, double sg, - VALUE *nth, int *rjd, - int *ry, int *rm, int *rd) -{ - decode_jd(jd, nth, rjd); - c_jd_to_civil(*rjd, sg, ry, rm, rd); -} - -static void -ordinal_to_jd(VALUE y, int d, double sg, - VALUE *nth, int *ry, - int *rjd, - int *ns) -{ - double style = guess_style(y, sg); - - if (style == 0) { - int jd; - - c_ordinal_to_jd(FIX2INT(y), d, sg, &jd, ns); - decode_jd(INT2FIX(jd), nth, rjd); - if (f_zero_p(*nth)) - *ry = FIX2INT(y); - else { - VALUE nth2; - decode_year(y, *ns ? -1 : +1, &nth2, ry); - } - } - else { - decode_year(y, style, nth, ry); - c_ordinal_to_jd(*ry, d, style, rjd, ns); - } -} - -static void -jd_to_ordinal(VALUE jd, double sg, - VALUE *nth, int *rjd, - int *ry, int *rd) -{ - decode_jd(jd, nth, rjd); - c_jd_to_ordinal(*rjd, sg, ry, rd); -} - -static void -commercial_to_jd(VALUE y, int w, int d, double sg, - VALUE *nth, int *ry, - int *rjd, - int *ns) -{ - double style = guess_style(y, sg); - - if (style == 0) { - int jd; - - c_commercial_to_jd(FIX2INT(y), w, d, sg, &jd, ns); - decode_jd(INT2FIX(jd), nth, rjd); - if (f_zero_p(*nth)) - *ry = FIX2INT(y); - else { - VALUE nth2; - decode_year(y, *ns ? -1 : +1, &nth2, ry); - } - } - else { - decode_year(y, style, nth, ry); - c_commercial_to_jd(*ry, w, d, style, rjd, ns); - } -} - -static void -jd_to_commercial(VALUE jd, double sg, - VALUE *nth, int *rjd, - int *ry, int *rw, int *rd) -{ - decode_jd(jd, nth, rjd); - c_jd_to_commercial(*rjd, sg, ry, rw, rd); -} - -static void -weeknum_to_jd(VALUE y, int w, int d, int f, double sg, - VALUE *nth, int *ry, - int *rjd, - int *ns) -{ - double style = guess_style(y, sg); - - if (style == 0) { - int jd; - - c_weeknum_to_jd(FIX2INT(y), w, d, f, sg, &jd, ns); - decode_jd(INT2FIX(jd), nth, rjd); - if (f_zero_p(*nth)) - *ry = FIX2INT(y); - else { - VALUE nth2; - decode_year(y, *ns ? -1 : +1, &nth2, ry); - } - } - else { - decode_year(y, style, nth, ry); - c_weeknum_to_jd(*ry, w, d, f, style, rjd, ns); - } -} - -static void -jd_to_weeknum(VALUE jd, int f, double sg, - VALUE *nth, int *rjd, - int *ry, int *rw, int *rd) -{ - decode_jd(jd, nth, rjd); - c_jd_to_weeknum(*rjd, f, sg, ry, rw, rd); -} - -static void -nth_kday_to_jd(VALUE y, int m, int n, int k, double sg, - VALUE *nth, int *ry, - int *rjd, - int *ns) -{ - double style = guess_style(y, sg); - - if (style == 0) { - int jd; - - c_nth_kday_to_jd(FIX2INT(y), m, n, k, sg, &jd, ns); - decode_jd(INT2FIX(jd), nth, rjd); - if (f_zero_p(*nth)) - *ry = FIX2INT(y); - else { - VALUE nth2; - decode_year(y, *ns ? -1 : +1, &nth2, ry); - } - } - else { - decode_year(y, style, nth, ry); - c_nth_kday_to_jd(*ry, m, n, k, style, rjd, ns); - } -} - -static void -jd_to_nth_kday(VALUE jd, double sg, - VALUE *nth, int *rjd, - int *ry, int *rm, int *rn, int *rk) -{ - decode_jd(jd, nth, rjd); - c_jd_to_nth_kday(*rjd, sg, ry, rm, rn, rk); -} -#endif - -static int -valid_ordinal_p(VALUE y, int d, double sg, - VALUE *nth, int *ry, - int *rd, int *rjd, - int *ns) -{ - double style = guess_style(y, sg); - int r; - - if (style == 0) { - int jd; - - r = c_valid_ordinal_p(FIX2INT(y), d, sg, rd, &jd, ns); - if (!r) - return 0; - decode_jd(INT2FIX(jd), nth, rjd); - if (f_zero_p(*nth)) - *ry = FIX2INT(y); - else { - VALUE nth2; - decode_year(y, *ns ? -1 : +1, &nth2, ry); - } - } - else { - decode_year(y, style, nth, ry); - r = c_valid_ordinal_p(*ry, d, style, rd, rjd, ns); - } - return r; -} - -static int -valid_gregorian_p(VALUE y, int m, int d, - VALUE *nth, int *ry, - int *rm, int *rd) -{ - decode_year(y, -1, nth, ry); - return c_valid_gregorian_p(*ry, m, d, rm, rd); -} - -static int -valid_civil_p(VALUE y, int m, int d, double sg, - VALUE *nth, int *ry, - int *rm, int *rd, int *rjd, - int *ns) -{ - double style = guess_style(y, sg); - int r; - - if (style == 0) { - int jd; - - r = c_valid_civil_p(FIX2INT(y), m, d, sg, rm, rd, &jd, ns); - if (!r) - return 0; - decode_jd(INT2FIX(jd), nth, rjd); - if (f_zero_p(*nth)) - *ry = FIX2INT(y); - else { - VALUE nth2; - decode_year(y, *ns ? -1 : +1, &nth2, ry); - } - } - else { - decode_year(y, style, nth, ry); - if (style < 0) - r = c_valid_gregorian_p(*ry, m, d, rm, rd); - else - r = c_valid_julian_p(*ry, m, d, rm, rd); - if (!r) - return 0; - c_civil_to_jd(*ry, *rm, *rd, style, rjd, ns); - } - return r; -} - -static int -valid_commercial_p(VALUE y, int w, int d, double sg, - VALUE *nth, int *ry, - int *rw, int *rd, int *rjd, - int *ns) -{ - double style = guess_style(y, sg); - int r; - - if (style == 0) { - int jd; - - r = c_valid_commercial_p(FIX2INT(y), w, d, sg, rw, rd, &jd, ns); - if (!r) - return 0; - decode_jd(INT2FIX(jd), nth, rjd); - if (f_zero_p(*nth)) - *ry = FIX2INT(y); - else { - VALUE nth2; - decode_year(y, *ns ? -1 : +1, &nth2, ry); - } - } - else { - decode_year(y, style, nth, ry); - r = c_valid_commercial_p(*ry, w, d, style, rw, rd, rjd, ns); - } - return r; -} - -static int -valid_weeknum_p(VALUE y, int w, int d, int f, double sg, - VALUE *nth, int *ry, - int *rw, int *rd, int *rjd, - int *ns) -{ - double style = guess_style(y, sg); - int r; - - if (style == 0) { - int jd; - - r = c_valid_weeknum_p(FIX2INT(y), w, d, f, sg, rw, rd, &jd, ns); - if (!r) - return 0; - decode_jd(INT2FIX(jd), nth, rjd); - if (f_zero_p(*nth)) - *ry = FIX2INT(y); - else { - VALUE nth2; - decode_year(y, *ns ? -1 : +1, &nth2, ry); - } - } - else { - decode_year(y, style, nth, ry); - r = c_valid_weeknum_p(*ry, w, d, f, style, rw, rd, rjd, ns); - } - return r; -} - -#ifndef NDEBUG -/* :nodoc: */ -static int -valid_nth_kday_p(VALUE y, int m, int n, int k, double sg, - VALUE *nth, int *ry, - int *rm, int *rn, int *rk, int *rjd, - int *ns) -{ - double style = guess_style(y, sg); - int r; - - if (style == 0) { - int jd; - - r = c_valid_nth_kday_p(FIX2INT(y), m, n, k, sg, rm, rn, rk, &jd, ns); - if (!r) - return 0; - decode_jd(INT2FIX(jd), nth, rjd); - if (f_zero_p(*nth)) - *ry = FIX2INT(y); - else { - VALUE nth2; - decode_year(y, *ns ? -1 : +1, &nth2, ry); - } - } - else { - decode_year(y, style, nth, ry); - r = c_valid_nth_kday_p(*ry, m, n, k, style, rm, rn, rk, rjd, ns); - } - return r; -} -#endif - -VALUE date_zone_to_diff(VALUE); - -static int -offset_to_sec(VALUE vof, int *rof) -{ - int try_rational = 1; - - again: - switch (TYPE(vof)) { - case T_FIXNUM: - { - long n; - - n = FIX2LONG(vof); - if (n != -1 && n != 0 && n != 1) - return 0; - *rof = (int)n * DAY_IN_SECONDS; - return 1; - } - case T_FLOAT: - { - double n; - - n = RFLOAT_VALUE(vof) * DAY_IN_SECONDS; - if (n < -DAY_IN_SECONDS || n > DAY_IN_SECONDS) - return 0; - *rof = (int)round(n); - if (*rof != n) - rb_warning("fraction of offset is ignored"); - return 1; - } - default: - expect_numeric(vof); - vof = f_to_r(vof); - if (!k_rational_p(vof)) { - if (!try_rational) Check_Type(vof, T_RATIONAL); - try_rational = 0; - goto again; - } - /* fall through */ - case T_RATIONAL: - { - VALUE vs, vn, vd; - long n; - - vs = day_to_sec(vof); - - if (!k_rational_p(vs)) { - vn = vs; - goto rounded; - } - vn = rb_rational_num(vs); - vd = rb_rational_den(vs); - - if (FIXNUM_P(vn) && FIXNUM_P(vd) && (FIX2LONG(vd) == 1)) - n = FIX2LONG(vn); - else { - vn = f_round(vs); - if (!f_eqeq_p(vn, vs)) - rb_warning("fraction of offset is ignored"); - rounded: - if (!FIXNUM_P(vn)) - return 0; - n = FIX2LONG(vn); - if (n < -DAY_IN_SECONDS || n > DAY_IN_SECONDS) - return 0; - } - *rof = (int)n; - return 1; - } - case T_STRING: - { - VALUE vs = date_zone_to_diff(vof); - long n; - - if (!FIXNUM_P(vs)) - return 0; - n = FIX2LONG(vs); - if (n < -DAY_IN_SECONDS || n > DAY_IN_SECONDS) - return 0; - *rof = (int)n; - return 1; - } - } - return 0; -} - -/* date */ - -#define valid_sg(sg) \ -do {\ - if (!c_valid_start_p(sg)) {\ - sg = 0;\ - rb_warning("invalid start is ignored");\ - }\ -} while (0) - -static VALUE -valid_jd_sub(int argc, VALUE *argv, VALUE klass, int need_jd) -{ - double sg = NUM2DBL(argv[1]); - valid_sg(sg); - return argv[0]; -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -date_s__valid_jd_p(int argc, VALUE *argv, VALUE klass) -{ - VALUE vjd, vsg; - VALUE argv2[2]; - - rb_scan_args(argc, argv, "11", &vjd, &vsg); - - argv2[0] = vjd; - if (argc < 2) - argv2[1] = DBL2NUM(GREGORIAN); - else - argv2[1] = vsg; - - return valid_jd_sub(2, argv2, klass, 1); -} -#endif - -/* - * call-seq: - * Date.valid_jd?(jd, start = Date::ITALY) -> true - * - * Implemented for compatibility; - * returns +true+ unless +jd+ is invalid (i.e., not a Numeric). - * - * Date.valid_jd?(2451944) # => true - * - * See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - * Related: Date.jd. - */ -static VALUE -date_s_valid_jd_p(int argc, VALUE *argv, VALUE klass) -{ - VALUE vjd, vsg; - VALUE argv2[2]; - - rb_scan_args(argc, argv, "11", &vjd, &vsg); - - RETURN_FALSE_UNLESS_NUMERIC(vjd); - argv2[0] = vjd; - if (argc < 2) - argv2[1] = INT2FIX(DEFAULT_SG); - else - argv2[1] = vsg; - - if (NIL_P(valid_jd_sub(2, argv2, klass, 0))) - return Qfalse; - return Qtrue; -} - -static VALUE -valid_civil_sub(int argc, VALUE *argv, VALUE klass, int need_jd) -{ - VALUE nth, y; - int m, d, ry, rm, rd; - double sg; - - y = argv[0]; - m = NUM2INT(argv[1]); - d = NUM2INT(argv[2]); - sg = NUM2DBL(argv[3]); - - valid_sg(sg); - - if (!need_jd && (guess_style(y, sg) < 0)) { - if (!valid_gregorian_p(y, m, d, - &nth, &ry, - &rm, &rd)) - return Qnil; - return INT2FIX(0); /* dummy */ - } - else { - int rjd, ns; - VALUE rjd2; - - if (!valid_civil_p(y, m, d, sg, - &nth, &ry, - &rm, &rd, &rjd, - &ns)) - return Qnil; - if (!need_jd) - return INT2FIX(0); /* dummy */ - encode_jd(nth, rjd, &rjd2); - return rjd2; - } -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -date_s__valid_civil_p(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vm, vd, vsg; - VALUE argv2[4]; - - rb_scan_args(argc, argv, "31", &vy, &vm, &vd, &vsg); - - argv2[0] = vy; - argv2[1] = vm; - argv2[2] = vd; - if (argc < 4) - argv2[3] = DBL2NUM(GREGORIAN); - else - argv2[3] = vsg; - - return valid_civil_sub(4, argv2, klass, 1); -} -#endif - -/* - * call-seq: - * Date.valid_civil?(year, month, mday, start = Date::ITALY) -> true or false - * - * Returns +true+ if the arguments define a valid ordinal date, - * +false+ otherwise: - * - * Date.valid_date?(2001, 2, 3) # => true - * Date.valid_date?(2001, 2, 29) # => false - * Date.valid_date?(2001, 2, -1) # => true - * - * See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - * Related: Date.jd, Date.new. - */ -static VALUE -date_s_valid_civil_p(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vm, vd, vsg; - VALUE argv2[4]; - - rb_scan_args(argc, argv, "31", &vy, &vm, &vd, &vsg); - - RETURN_FALSE_UNLESS_NUMERIC(vy); - RETURN_FALSE_UNLESS_NUMERIC(vm); - RETURN_FALSE_UNLESS_NUMERIC(vd); - argv2[0] = vy; - argv2[1] = vm; - argv2[2] = vd; - if (argc < 4) - argv2[3] = INT2FIX(DEFAULT_SG); - else - argv2[3] = vsg; - - if (NIL_P(valid_civil_sub(4, argv2, klass, 0))) - return Qfalse; - return Qtrue; -} - -static VALUE -valid_ordinal_sub(int argc, VALUE *argv, VALUE klass, int need_jd) -{ - VALUE nth, y; - int d, ry, rd; - double sg; - - y = argv[0]; - d = NUM2INT(argv[1]); - sg = NUM2DBL(argv[2]); - - valid_sg(sg); - - { - int rjd, ns; - VALUE rjd2; - - if (!valid_ordinal_p(y, d, sg, - &nth, &ry, - &rd, &rjd, - &ns)) - return Qnil; - if (!need_jd) - return INT2FIX(0); /* dummy */ - encode_jd(nth, rjd, &rjd2); - return rjd2; - } -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -date_s__valid_ordinal_p(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vd, vsg; - VALUE argv2[3]; - - rb_scan_args(argc, argv, "21", &vy, &vd, &vsg); - - argv2[0] = vy; - argv2[1] = vd; - if (argc < 3) - argv2[2] = DBL2NUM(GREGORIAN); - else - argv2[2] = vsg; - - return valid_ordinal_sub(3, argv2, klass, 1); -} -#endif - -/* - * call-seq: - * Date.valid_ordinal?(year, yday, start = Date::ITALY) -> true or false - * - * Returns +true+ if the arguments define a valid ordinal date, - * +false+ otherwise: - * - * Date.valid_ordinal?(2001, 34) # => true - * Date.valid_ordinal?(2001, 366) # => false - * - * See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - * Related: Date.jd, Date.ordinal. - */ -static VALUE -date_s_valid_ordinal_p(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vd, vsg; - VALUE argv2[3]; - - rb_scan_args(argc, argv, "21", &vy, &vd, &vsg); - - RETURN_FALSE_UNLESS_NUMERIC(vy); - RETURN_FALSE_UNLESS_NUMERIC(vd); - argv2[0] = vy; - argv2[1] = vd; - if (argc < 3) - argv2[2] = INT2FIX(DEFAULT_SG); - else - argv2[2] = vsg; - - if (NIL_P(valid_ordinal_sub(3, argv2, klass, 0))) - return Qfalse; - return Qtrue; -} - -static VALUE -valid_commercial_sub(int argc, VALUE *argv, VALUE klass, int need_jd) -{ - VALUE nth, y; - int w, d, ry, rw, rd; - double sg; - - y = argv[0]; - w = NUM2INT(argv[1]); - d = NUM2INT(argv[2]); - sg = NUM2DBL(argv[3]); - - valid_sg(sg); - - { - int rjd, ns; - VALUE rjd2; - - if (!valid_commercial_p(y, w, d, sg, - &nth, &ry, - &rw, &rd, &rjd, - &ns)) - return Qnil; - if (!need_jd) - return INT2FIX(0); /* dummy */ - encode_jd(nth, rjd, &rjd2); - return rjd2; - } -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -date_s__valid_commercial_p(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vw, vd, vsg; - VALUE argv2[4]; - - rb_scan_args(argc, argv, "31", &vy, &vw, &vd, &vsg); - - argv2[0] = vy; - argv2[1] = vw; - argv2[2] = vd; - if (argc < 4) - argv2[3] = DBL2NUM(GREGORIAN); - else - argv2[3] = vsg; - - return valid_commercial_sub(4, argv2, klass, 1); -} -#endif - -/* - * call-seq: - * Date.valid_commercial?(cwyear, cweek, cwday, start = Date::ITALY) -> true or false - * - * Returns +true+ if the arguments define a valid commercial date, - * +false+ otherwise: - * - * Date.valid_commercial?(2001, 5, 6) # => true - * Date.valid_commercial?(2001, 5, 8) # => false - * - * See Date.commercial. - * - * See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - * Related: Date.jd, Date.commercial. - */ -static VALUE -date_s_valid_commercial_p(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vw, vd, vsg; - VALUE argv2[4]; - - rb_scan_args(argc, argv, "31", &vy, &vw, &vd, &vsg); - - RETURN_FALSE_UNLESS_NUMERIC(vy); - RETURN_FALSE_UNLESS_NUMERIC(vw); - RETURN_FALSE_UNLESS_NUMERIC(vd); - argv2[0] = vy; - argv2[1] = vw; - argv2[2] = vd; - if (argc < 4) - argv2[3] = INT2FIX(DEFAULT_SG); - else - argv2[3] = vsg; - - if (NIL_P(valid_commercial_sub(4, argv2, klass, 0))) - return Qfalse; - return Qtrue; -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -valid_weeknum_sub(int argc, VALUE *argv, VALUE klass, int need_jd) -{ - VALUE nth, y; - int w, d, f, ry, rw, rd; - double sg; - - y = argv[0]; - w = NUM2INT(argv[1]); - d = NUM2INT(argv[2]); - f = NUM2INT(argv[3]); - sg = NUM2DBL(argv[4]); - - valid_sg(sg); - - { - int rjd, ns; - VALUE rjd2; - - if (!valid_weeknum_p(y, w, d, f, sg, - &nth, &ry, - &rw, &rd, &rjd, - &ns)) - return Qnil; - if (!need_jd) - return INT2FIX(0); /* dummy */ - encode_jd(nth, rjd, &rjd2); - return rjd2; - } -} - -/* :nodoc: */ -static VALUE -date_s__valid_weeknum_p(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vw, vd, vf, vsg; - VALUE argv2[5]; - - rb_scan_args(argc, argv, "41", &vy, &vw, &vd, &vf, &vsg); - - argv2[0] = vy; - argv2[1] = vw; - argv2[2] = vd; - argv2[3] = vf; - if (argc < 5) - argv2[4] = DBL2NUM(GREGORIAN); - else - argv2[4] = vsg; - - return valid_weeknum_sub(5, argv2, klass, 1); -} - -/* :nodoc: */ -static VALUE -date_s_valid_weeknum_p(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vw, vd, vf, vsg; - VALUE argv2[5]; - - rb_scan_args(argc, argv, "41", &vy, &vw, &vd, &vf, &vsg); - - argv2[0] = vy; - argv2[1] = vw; - argv2[2] = vd; - argv2[3] = vf; - if (argc < 5) - argv2[4] = INT2FIX(DEFAULT_SG); - else - argv2[4] = vsg; - - if (NIL_P(valid_weeknum_sub(5, argv2, klass, 0))) - return Qfalse; - return Qtrue; -} - -static VALUE -valid_nth_kday_sub(int argc, VALUE *argv, VALUE klass, int need_jd) -{ - VALUE nth, y; - int m, n, k, ry, rm, rn, rk; - double sg; - - y = argv[0]; - m = NUM2INT(argv[1]); - n = NUM2INT(argv[2]); - k = NUM2INT(argv[3]); - sg = NUM2DBL(argv[4]); - - { - int rjd, ns; - VALUE rjd2; - - if (!valid_nth_kday_p(y, m, n, k, sg, - &nth, &ry, - &rm, &rn, &rk, &rjd, - &ns)) - return Qnil; - if (!need_jd) - return INT2FIX(0); /* dummy */ - encode_jd(nth, rjd, &rjd2); - return rjd2; - } -} - -/* :nodoc: */ -static VALUE -date_s__valid_nth_kday_p(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vm, vn, vk, vsg; - VALUE argv2[5]; - - rb_scan_args(argc, argv, "41", &vy, &vm, &vn, &vk, &vsg); - - argv2[0] = vy; - argv2[1] = vm; - argv2[2] = vn; - argv2[3] = vk; - if (argc < 5) - argv2[4] = DBL2NUM(GREGORIAN); - else - argv2[4] = vsg; - - return valid_nth_kday_sub(5, argv2, klass, 1); -} - -/* :nodoc: */ -static VALUE -date_s_valid_nth_kday_p(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vm, vn, vk, vsg; - VALUE argv2[5]; - - rb_scan_args(argc, argv, "41", &vy, &vm, &vn, &vk, &vsg); - - argv2[0] = vy; - argv2[1] = vm; - argv2[2] = vn; - argv2[3] = vk; - if (argc < 5) - argv2[4] = INT2FIX(DEFAULT_SG); - else - argv2[4] = vsg; - - if (NIL_P(valid_nth_kday_sub(5, argv2, klass, 0))) - return Qfalse; - return Qtrue; -} - -/* :nodoc: */ -static VALUE -date_s_zone_to_diff(VALUE klass, VALUE str) -{ - return date_zone_to_diff(str); -} -#endif - -/* - * call-seq: - * Date.julian_leap?(year) -> true or false - * - * Returns +true+ if the given year is a leap year - * in the {proleptic Julian calendar}[https://en.wikipedia.org/wiki/Proleptic_Julian_calendar], +false+ otherwise: - * - * Date.julian_leap?(1900) # => true - * Date.julian_leap?(1901) # => false - * - * Related: Date.gregorian_leap?. - */ -static VALUE -date_s_julian_leap_p(VALUE klass, VALUE y) -{ - VALUE nth; - int ry; - - check_numeric(y, "year"); - decode_year(y, +1, &nth, &ry); - return f_boolcast(c_julian_leap_p(ry)); -} - -/* - * call-seq: - * Date.gregorian_leap?(year) -> true or false - * - * Returns +true+ if the given year is a leap year - * in the {proleptic Gregorian calendar}[https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar], +false+ otherwise: - * - * Date.gregorian_leap?(2000) # => true - * Date.gregorian_leap?(2001) # => false - * - * Related: Date.julian_leap?. - */ -static VALUE -date_s_gregorian_leap_p(VALUE klass, VALUE y) -{ - VALUE nth; - int ry; - - check_numeric(y, "year"); - decode_year(y, -1, &nth, &ry); - return f_boolcast(c_gregorian_leap_p(ry)); -} - -static void -d_lite_gc_mark(void *ptr) -{ - union DateData *dat = ptr; - if (simple_dat_p(dat)) - rb_gc_mark(dat->s.nth); - else { - rb_gc_mark(dat->c.nth); - rb_gc_mark(dat->c.sf); - } -} - -static size_t -d_lite_memsize(const void *ptr) -{ - const union DateData *dat = ptr; - return complex_dat_p(dat) ? sizeof(struct ComplexDateData) : sizeof(struct SimpleDateData); -} - -#ifndef HAVE_RB_EXT_RACTOR_SAFE -# define RUBY_TYPED_FROZEN_SHAREABLE 0 -#endif - -static const rb_data_type_t d_lite_type = { - "Date", - {d_lite_gc_mark, RUBY_TYPED_DEFAULT_FREE, d_lite_memsize,}, - 0, 0, - RUBY_TYPED_FREE_IMMEDIATELY|RUBY_TYPED_WB_PROTECTED|RUBY_TYPED_FROZEN_SHAREABLE, -}; - -inline static VALUE -d_simple_new_internal(VALUE klass, - VALUE nth, int jd, - double sg, - int y, int m, int d, - unsigned flags) -{ - struct SimpleDateData *dat; - VALUE obj; - - obj = TypedData_Make_Struct(klass, struct SimpleDateData, - &d_lite_type, dat); - set_to_simple(obj, dat, nth, jd, sg, y, m, d, flags); - - assert(have_jd_p(dat) || have_civil_p(dat)); - - return obj; -} - -inline static VALUE -d_complex_new_internal(VALUE klass, - VALUE nth, int jd, - int df, VALUE sf, - int of, double sg, - int y, int m, int d, - int h, int min, int s, - unsigned flags) -{ - struct ComplexDateData *dat; - VALUE obj; - - obj = TypedData_Make_Struct(klass, struct ComplexDateData, - &d_lite_type, dat); - set_to_complex(obj, dat, nth, jd, df, sf, of, sg, - y, m, d, h, min, s, flags); - - assert(have_jd_p(dat) || have_civil_p(dat)); - assert(have_df_p(dat) || have_time_p(dat)); - - return obj; -} - -static VALUE -d_lite_s_alloc_simple(VALUE klass) -{ - return d_simple_new_internal(klass, - INT2FIX(0), 0, - DEFAULT_SG, - 0, 0, 0, - HAVE_JD); -} - -static VALUE -d_lite_s_alloc_complex(VALUE klass) -{ - return d_complex_new_internal(klass, - INT2FIX(0), 0, - 0, INT2FIX(0), - 0, DEFAULT_SG, - 0, 0, 0, - 0, 0, 0, - HAVE_JD | HAVE_DF); -} - -static VALUE -d_lite_s_alloc(VALUE klass) -{ - return d_lite_s_alloc_complex(klass); -} - -static void -old_to_new(VALUE ajd, VALUE of, VALUE sg, - VALUE *rnth, int *rjd, int *rdf, VALUE *rsf, - int *rof, double *rsg) -{ - VALUE jd, df, sf, of2, t; - - decode_day(f_add(ajd, half_days_in_day), - &jd, &df, &sf); - t = day_to_sec(of); - of2 = f_round(t); - - if (!f_eqeq_p(of2, t)) - rb_warning("fraction of offset is ignored"); - - decode_jd(jd, rnth, rjd); - - *rdf = NUM2INT(df); - *rsf = sf; - *rof = NUM2INT(of2); - *rsg = NUM2DBL(sg); - - if (*rdf < 0 || *rdf >= DAY_IN_SECONDS) - rb_raise(eDateError, "invalid day fraction"); - - if (f_lt_p(*rsf, INT2FIX(0)) || - f_ge_p(*rsf, INT2FIX(SECOND_IN_NANOSECONDS))) - - if (*rof < -DAY_IN_SECONDS || *rof > DAY_IN_SECONDS) { - *rof = 0; - rb_warning("invalid offset is ignored"); - } - - if (!c_valid_start_p(*rsg)) { - *rsg = DEFAULT_SG; - rb_warning("invalid start is ignored"); - } -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -date_s_new_bang(int argc, VALUE *argv, VALUE klass) -{ - VALUE ajd, of, sg, nth, sf; - int jd, df, rof; - double rsg; - - rb_scan_args(argc, argv, "03", &ajd, &of, &sg); - - switch (argc) { - case 0: - ajd = INT2FIX(0); - case 1: - of = INT2FIX(0); - case 2: - sg = INT2FIX(DEFAULT_SG); - } - - old_to_new(ajd, of, sg, - &nth, &jd, &df, &sf, &rof, &rsg); - - if (!df && f_zero_p(sf) && !rof) - return d_simple_new_internal(klass, - nth, jd, - rsg, - 0, 0, 0, - HAVE_JD); - else - return d_complex_new_internal(klass, - nth, jd, - df, sf, - rof, rsg, - 0, 0, 0, - 0, 0, 0, - HAVE_JD | HAVE_DF); -} -#endif - -inline static int -wholenum_p(VALUE x) -{ - if (FIXNUM_P(x)) - return 1; - switch (TYPE(x)) { - case T_BIGNUM: - return 1; - case T_FLOAT: - { - double d = RFLOAT_VALUE(x); - return round(d) == d; - } - break; - case T_RATIONAL: - { - VALUE den = rb_rational_den(x); - return FIXNUM_P(den) && FIX2LONG(den) == 1; - } - break; - } - return 0; -} - -inline static VALUE -to_integer(VALUE x) -{ - if (RB_INTEGER_TYPE_P(x)) - return x; - return f_to_i(x); -} - -inline static VALUE -d_trunc(VALUE d, VALUE *fr) -{ - VALUE rd; - - if (wholenum_p(d)) { - rd = to_integer(d); - *fr = INT2FIX(0); - } - else { - rd = f_idiv(d, INT2FIX(1)); - *fr = f_mod(d, INT2FIX(1)); - } - return rd; -} - -#define jd_trunc d_trunc -#define k_trunc d_trunc - -inline static VALUE -h_trunc(VALUE h, VALUE *fr) -{ - VALUE rh; - - if (wholenum_p(h)) { - rh = to_integer(h); - *fr = INT2FIX(0); - } - else { - rh = f_idiv(h, INT2FIX(1)); - *fr = f_mod(h, INT2FIX(1)); - *fr = f_quo(*fr, INT2FIX(24)); - } - return rh; -} - -inline static VALUE -min_trunc(VALUE min, VALUE *fr) -{ - VALUE rmin; - - if (wholenum_p(min)) { - rmin = to_integer(min); - *fr = INT2FIX(0); - } - else { - rmin = f_idiv(min, INT2FIX(1)); - *fr = f_mod(min, INT2FIX(1)); - *fr = f_quo(*fr, INT2FIX(1440)); - } - return rmin; -} - -inline static VALUE -s_trunc(VALUE s, VALUE *fr) -{ - VALUE rs; - - if (wholenum_p(s)) { - rs = to_integer(s); - *fr = INT2FIX(0); - } - else { - rs = f_idiv(s, INT2FIX(1)); - *fr = f_mod(s, INT2FIX(1)); - *fr = f_quo(*fr, INT2FIX(86400)); - } - return rs; -} - -#define num2num_with_frac(s,n) \ -do {\ - s = s##_trunc(v##s, &fr);\ - if (f_nonzero_p(fr)) {\ - if (argc > n)\ - rb_raise(eDateError, "invalid fraction");\ - fr2 = fr;\ - }\ -} while (0) - -#define num2int_with_frac(s,n) \ -do {\ - s = NUM2INT(s##_trunc(v##s, &fr));\ - if (f_nonzero_p(fr)) {\ - if (argc > n)\ - rb_raise(eDateError, "invalid fraction");\ - fr2 = fr;\ - }\ -} while (0) - -#define canon24oc() \ -do {\ - if (rh == 24) {\ - rh = 0;\ - fr2 = f_add(fr2, INT2FIX(1));\ - }\ -} while (0) - -#define add_frac() \ -do {\ - if (f_nonzero_p(fr2))\ - ret = d_lite_plus(ret, fr2);\ -} while (0) - -#define val2sg(vsg,dsg) \ -do {\ - dsg = NUM2DBL(vsg);\ - if (!c_valid_start_p(dsg)) {\ - dsg = DEFAULT_SG;\ - rb_warning("invalid start is ignored");\ - }\ -} while (0) - -static VALUE d_lite_plus(VALUE, VALUE); - -/* - * call-seq: - * Date.jd(jd = 0, start = Date::ITALY) -> date - * - * Returns a new \Date object formed from the arguments: - * - * Date.jd(2451944).to_s # => "2001-02-03" - * Date.jd(2451945).to_s # => "2001-02-04" - * Date.jd(0).to_s # => "-4712-01-01" - * - * The returned date is: - * - * - Gregorian, if the argument is greater than or equal to +start+: - * - * Date::ITALY # => 2299161 - * Date.jd(Date::ITALY).gregorian? # => true - * Date.jd(Date::ITALY + 1).gregorian? # => true - * - * - Julian, otherwise - * - * Date.jd(Date::ITALY - 1).julian? # => true - * - * See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - * Related: Date.new. - */ -static VALUE -date_s_jd(int argc, VALUE *argv, VALUE klass) -{ - VALUE vjd, vsg, jd, fr, fr2, ret; - double sg; - - rb_scan_args(argc, argv, "02", &vjd, &vsg); - - jd = INT2FIX(0); - fr2 = INT2FIX(0); - sg = DEFAULT_SG; - - switch (argc) { - case 2: - val2sg(vsg, sg); - case 1: - check_numeric(vjd, "jd"); - num2num_with_frac(jd, positive_inf); - } - - { - VALUE nth; - int rjd; - - decode_jd(jd, &nth, &rjd); - ret = d_simple_new_internal(klass, - nth, rjd, - sg, - 0, 0, 0, - HAVE_JD); - } - add_frac(); - return ret; -} - -/* - * call-seq: - * Date.ordinal(year = -4712, yday = 1, start = Date::ITALY) -> date - * - * Returns a new \Date object formed fom the arguments. - * - * With no arguments, returns the date for January 1, -4712: - * - * Date.ordinal.to_s # => "-4712-01-01" - * - * With argument +year+, returns the date for January 1 of that year: - * - * Date.ordinal(2001).to_s # => "2001-01-01" - * Date.ordinal(-2001).to_s # => "-2001-01-01" - * - * With positive argument +yday+ == +n+, - * returns the date for the +nth+ day of the given year: - * - * Date.ordinal(2001, 14).to_s # => "2001-01-14" - * - * With negative argument +yday+, counts backward from the end of the year: - * - * Date.ordinal(2001, -14).to_s # => "2001-12-18" - * - * Raises an exception if +yday+ is zero or out of range. - * - * See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - * Related: Date.jd, Date.new. - */ -static VALUE -date_s_ordinal(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vd, vsg, y, fr, fr2, ret; - int d; - double sg; - - rb_scan_args(argc, argv, "03", &vy, &vd, &vsg); - - y = INT2FIX(-4712); - d = 1; - fr2 = INT2FIX(0); - sg = DEFAULT_SG; - - switch (argc) { - case 3: - val2sg(vsg, sg); - case 2: - check_numeric(vd, "yday"); - num2int_with_frac(d, positive_inf); - case 1: - check_numeric(vy, "year"); - y = vy; - } - - { - VALUE nth; - int ry, rd, rjd, ns; - - if (!valid_ordinal_p(y, d, sg, - &nth, &ry, - &rd, &rjd, - &ns)) - rb_raise(eDateError, "invalid date"); - - ret = d_simple_new_internal(klass, - nth, rjd, - sg, - 0, 0, 0, - HAVE_JD); - } - add_frac(); - return ret; -} - -/* - * Same as Date.new. - */ -static VALUE -date_s_civil(int argc, VALUE *argv, VALUE klass) -{ - return date_initialize(argc, argv, d_lite_s_alloc_simple(klass)); -} - -/* - * call-seq: - * Date.new(year = -4712, month = 1, mday = 1, start = Date::ITALY) -> date - * - * Returns a new \Date object constructed from the given arguments: - * - * Date.new(2022).to_s # => "2022-01-01" - * Date.new(2022, 2).to_s # => "2022-02-01" - * Date.new(2022, 2, 4).to_s # => "2022-02-04" - * - * Argument +month+ should be in range (1..12) or range (-12..-1); - * when the argument is negative, counts backward from the end of the year: - * - * Date.new(2022, -11, 4).to_s # => "2022-02-04" - * - * Argument +mday+ should be in range (1..n) or range (-n..-1) - * where +n+ is the number of days in the month; - * when the argument is negative, counts backward from the end of the month. - * - * See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - * Related: Date.jd. - */ -static VALUE -date_initialize(int argc, VALUE *argv, VALUE self) -{ - VALUE vy, vm, vd, vsg, y, fr, fr2, ret; - int m, d; - double sg; - struct SimpleDateData *dat = rb_check_typeddata(self, &d_lite_type); - - if (!simple_dat_p(dat)) { - rb_raise(rb_eTypeError, "Date expected"); - } - - rb_scan_args(argc, argv, "04", &vy, &vm, &vd, &vsg); - - y = INT2FIX(-4712); - m = 1; - d = 1; - fr2 = INT2FIX(0); - sg = DEFAULT_SG; - - switch (argc) { - case 4: - val2sg(vsg, sg); - case 3: - check_numeric(vd, "day"); - num2int_with_frac(d, positive_inf); - case 2: - check_numeric(vm, "month"); - m = NUM2INT(vm); - case 1: - check_numeric(vy, "year"); - y = vy; - } - - if (guess_style(y, sg) < 0) { - VALUE nth; - int ry, rm, rd; - - if (!valid_gregorian_p(y, m, d, - &nth, &ry, - &rm, &rd)) - rb_raise(eDateError, "invalid date"); - - set_to_simple(self, dat, nth, 0, sg, ry, rm, rd, HAVE_CIVIL); - } - else { - VALUE nth; - int ry, rm, rd, rjd, ns; - - if (!valid_civil_p(y, m, d, sg, - &nth, &ry, - &rm, &rd, &rjd, - &ns)) - rb_raise(eDateError, "invalid date"); - - set_to_simple(self, dat, nth, rjd, sg, ry, rm, rd, HAVE_JD | HAVE_CIVIL); - } - ret = self; - add_frac(); - return ret; -} - -/* - * call-seq: - * Date.commercial(cwyear = -4712, cweek = 1, cwday = 1, start = Date::ITALY) -> date - * - * Returns a new \Date object constructed from the arguments. - * - * Argument +cwyear+ gives the year, and should be an integer. - * - * Argument +cweek+ gives the index of the week within the year, - * and should be in range (1..53) or (-53..-1); - * in some years, 53 or -53 will be out-of-range; - * if negative, counts backward from the end of the year: - * - * Date.commercial(2022, 1, 1).to_s # => "2022-01-03" - * Date.commercial(2022, 52, 1).to_s # => "2022-12-26" - * - * Argument +cwday+ gives the indes of the weekday within the week, - * and should be in range (1..7) or (-7..-1); - * 1 or -7 is Monday; - * if negative, counts backward from the end of the week: - * - * Date.commercial(2022, 1, 1).to_s # => "2022-01-03" - * Date.commercial(2022, 1, -7).to_s # => "2022-01-03" - * - * When +cweek+ is 1: - * - * - If January 1 is a Friday, Saturday, or Sunday, - * the first week begins in the week after: - * - * Date::ABBR_DAYNAMES[Date.new(2023, 1, 1).wday] # => "Sun" - * Date.commercial(2023, 1, 1).to_s # => "2023-01-02" - Date.commercial(2023, 1, 7).to_s # => "2023-01-08" - * - * - Otherwise, the first week is the week of January 1, - * which may mean some of the days fall on the year before: - * - * Date::ABBR_DAYNAMES[Date.new(2020, 1, 1).wday] # => "Wed" - * Date.commercial(2020, 1, 1).to_s # => "2019-12-30" - Date.commercial(2020, 1, 7).to_s # => "2020-01-05" - * - * See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - * Related: Date.jd, Date.new, Date.ordinal. - */ -static VALUE -date_s_commercial(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vw, vd, vsg, y, fr, fr2, ret; - int w, d; - double sg; - - rb_scan_args(argc, argv, "04", &vy, &vw, &vd, &vsg); - - y = INT2FIX(-4712); - w = 1; - d = 1; - fr2 = INT2FIX(0); - sg = DEFAULT_SG; - - switch (argc) { - case 4: - val2sg(vsg, sg); - case 3: - check_numeric(vd, "cwday"); - num2int_with_frac(d, positive_inf); - case 2: - check_numeric(vw, "cweek"); - w = NUM2INT(vw); - case 1: - check_numeric(vy, "year"); - y = vy; - } - - { - VALUE nth; - int ry, rw, rd, rjd, ns; - - if (!valid_commercial_p(y, w, d, sg, - &nth, &ry, - &rw, &rd, &rjd, - &ns)) - rb_raise(eDateError, "invalid date"); - - ret = d_simple_new_internal(klass, - nth, rjd, - sg, - 0, 0, 0, - HAVE_JD); - } - add_frac(); - return ret; -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -date_s_weeknum(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vw, vd, vf, vsg, y, fr, fr2, ret; - int w, d, f; - double sg; - - rb_scan_args(argc, argv, "05", &vy, &vw, &vd, &vf, &vsg); - - y = INT2FIX(-4712); - w = 0; - d = 1; - f = 0; - fr2 = INT2FIX(0); - sg = DEFAULT_SG; - - switch (argc) { - case 5: - val2sg(vsg, sg); - case 4: - f = NUM2INT(vf); - case 3: - num2int_with_frac(d, positive_inf); - case 2: - w = NUM2INT(vw); - case 1: - y = vy; - } - - { - VALUE nth; - int ry, rw, rd, rjd, ns; - - if (!valid_weeknum_p(y, w, d, f, sg, - &nth, &ry, - &rw, &rd, &rjd, - &ns)) - rb_raise(eDateError, "invalid date"); - - ret = d_simple_new_internal(klass, - nth, rjd, - sg, - 0, 0, 0, - HAVE_JD); - } - add_frac(); - return ret; -} - -/* :nodoc: */ -static VALUE -date_s_nth_kday(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vm, vn, vk, vsg, y, fr, fr2, ret; - int m, n, k; - double sg; - - rb_scan_args(argc, argv, "05", &vy, &vm, &vn, &vk, &vsg); - - y = INT2FIX(-4712); - m = 1; - n = 1; - k = 1; - fr2 = INT2FIX(0); - sg = DEFAULT_SG; - - switch (argc) { - case 5: - val2sg(vsg, sg); - case 4: - num2int_with_frac(k, positive_inf); - case 3: - n = NUM2INT(vn); - case 2: - m = NUM2INT(vm); - case 1: - y = vy; - } - - { - VALUE nth; - int ry, rm, rn, rk, rjd, ns; - - if (!valid_nth_kday_p(y, m, n, k, sg, - &nth, &ry, - &rm, &rn, &rk, &rjd, - &ns)) - rb_raise(eDateError, "invalid date"); - - ret = d_simple_new_internal(klass, - nth, rjd, - sg, - 0, 0, 0, - HAVE_JD); - } - add_frac(); - return ret; -} -#endif - -#if !defined(HAVE_GMTIME_R) -static struct tm* -gmtime_r(const time_t *t, struct tm *tm) -{ - auto struct tm *tmp = gmtime(t); - if (tmp) - *tm = *tmp; - return tmp; -} - -static struct tm* -localtime_r(const time_t *t, struct tm *tm) -{ - auto struct tm *tmp = localtime(t); - if (tmp) - *tm = *tmp; - return tmp; -} -#endif - -static void set_sg(union DateData *, double); - -/* - * call-seq: - * Date.today(start = Date::ITALY) -> date - * - * Returns a new \Date object constructed from the present date: - * - * Date.today.to_s # => "2022-07-06" - * - * See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - */ -static VALUE -date_s_today(int argc, VALUE *argv, VALUE klass) -{ - VALUE vsg, nth, ret; - double sg; - time_t t; - struct tm tm; - int y, ry, m, d; - - rb_scan_args(argc, argv, "01", &vsg); - - if (argc < 1) - sg = DEFAULT_SG; - else - val2sg(vsg, sg); - - if (time(&t) == -1) - rb_sys_fail("time"); - tzset(); - if (!localtime_r(&t, &tm)) - rb_sys_fail("localtime"); - - y = tm.tm_year + 1900; - m = tm.tm_mon + 1; - d = tm.tm_mday; - - decode_year(INT2FIX(y), -1, &nth, &ry); - - ret = d_simple_new_internal(klass, - nth, 0, - GREGORIAN, - ry, m, d, - HAVE_CIVIL); - { - get_d1(ret); - set_sg(dat, sg); - } - return ret; -} - -#define set_hash0(k,v) rb_hash_aset(hash, k, v) -#define ref_hash0(k) rb_hash_aref(hash, k) -#define del_hash0(k) rb_hash_delete(hash, k) - -#define sym(x) ID2SYM(rb_intern(x"")) - -#define set_hash(k,v) set_hash0(sym(k), v) -#define ref_hash(k) ref_hash0(sym(k)) -#define del_hash(k) del_hash0(sym(k)) - -static VALUE -rt_rewrite_frags(VALUE hash) -{ - VALUE seconds; - - seconds = del_hash("seconds"); - if (!NIL_P(seconds)) { - VALUE offset, d, h, min, s, fr; - - offset = ref_hash("offset"); - if (!NIL_P(offset)) - seconds = f_add(seconds, offset); - - d = f_idiv(seconds, INT2FIX(DAY_IN_SECONDS)); - fr = f_mod(seconds, INT2FIX(DAY_IN_SECONDS)); - - h = f_idiv(fr, INT2FIX(HOUR_IN_SECONDS)); - fr = f_mod(fr, INT2FIX(HOUR_IN_SECONDS)); - - min = f_idiv(fr, INT2FIX(MINUTE_IN_SECONDS)); - fr = f_mod(fr, INT2FIX(MINUTE_IN_SECONDS)); - - s = f_idiv(fr, INT2FIX(1)); - fr = f_mod(fr, INT2FIX(1)); - - set_hash("jd", f_add(UNIX_EPOCH_IN_CJD, d)); - set_hash("hour", h); - set_hash("min", min); - set_hash("sec", s); - set_hash("sec_fraction", fr); - } - return hash; -} - -static VALUE d_lite_year(VALUE); -static VALUE d_lite_wday(VALUE); -static VALUE d_lite_jd(VALUE); - -static VALUE -rt_complete_frags(VALUE klass, VALUE hash) -{ - static VALUE tab = Qnil; - long e; - VALUE k, a, d; - - if (NIL_P(tab)) { - tab = f_frozen_ary(11, - f_frozen_ary(2, - sym("time"), - f_frozen_ary(3, - sym("hour"), - sym("min"), - sym("sec"))), - f_frozen_ary(2, - Qnil, - f_frozen_ary(1, - sym("jd"))), - f_frozen_ary(2, - sym("ordinal"), - f_frozen_ary(5, - sym("year"), - sym("yday"), - sym("hour"), - sym("min"), - sym("sec"))), - f_frozen_ary(2, - sym("civil"), - f_frozen_ary(6, - sym("year"), - sym("mon"), - sym("mday"), - sym("hour"), - sym("min"), - sym("sec"))), - f_frozen_ary(2, - sym("commercial"), - f_frozen_ary(6, - sym("cwyear"), - sym("cweek"), - sym("cwday"), - sym("hour"), - sym("min"), - sym("sec"))), - f_frozen_ary(2, - sym("wday"), - f_frozen_ary(4, - sym("wday"), - sym("hour"), - sym("min"), - sym("sec"))), - f_frozen_ary(2, - sym("wnum0"), - f_frozen_ary(6, - sym("year"), - sym("wnum0"), - sym("wday"), - sym("hour"), - sym("min"), - sym("sec"))), - f_frozen_ary(2, - sym("wnum1"), - f_frozen_ary(6, - sym("year"), - sym("wnum1"), - sym("wday"), - sym("hour"), - sym("min"), - sym("sec"))), - f_frozen_ary(2, - Qnil, - f_frozen_ary(6, - sym("cwyear"), - sym("cweek"), - sym("wday"), - sym("hour"), - sym("min"), - sym("sec"))), - f_frozen_ary(2, - Qnil, - f_frozen_ary(6, - sym("year"), - sym("wnum0"), - sym("cwday"), - sym("hour"), - sym("min"), - sym("sec"))), - f_frozen_ary(2, - Qnil, - f_frozen_ary(6, - sym("year"), - sym("wnum1"), - sym("cwday"), - sym("hour"), - sym("min"), - sym("sec")))); - rb_gc_register_mark_object(tab); - } - - k = a = Qnil; - - { - long i, eno = 0; - VALUE t = Qnil; - - e = 0; - for (i = 0; i < RARRAY_LEN(tab); i++) { - VALUE x, a; - - x = RARRAY_AREF(tab, i); - a = RARRAY_AREF(x, 1); - - { - long j, n = 0; - - for (j = 0; j < RARRAY_LEN(a); j++) - if (!NIL_P(ref_hash0(RARRAY_AREF(a, j)))) - n++; - if (n > eno) { - eno = n; - t = x; - } - } - } - if (eno > 0) { - k = RARRAY_AREF(t, 0); - a = RARRAY_AREF(t, 1); - } - e = eno; - } - - d = Qnil; - - if (!NIL_P(k) && (RARRAY_LEN(a) > e)) { - if (k == sym("ordinal")) { - if (NIL_P(ref_hash("year"))) { - if (NIL_P(d)) - d = date_s_today(0, (VALUE *)0, cDate); - set_hash("year", d_lite_year(d)); - } - if (NIL_P(ref_hash("yday"))) - set_hash("yday", INT2FIX(1)); - } - else if (k == sym("civil")) { - long i; - - for (i = 0; i < RARRAY_LEN(a); i++) { - VALUE e = RARRAY_AREF(a, i); - - if (!NIL_P(ref_hash0(e))) - break; - if (NIL_P(d)) - d = date_s_today(0, (VALUE *)0, cDate); - set_hash0(e, rb_funcall(d, SYM2ID(e), 0)); - } - if (NIL_P(ref_hash("mon"))) - set_hash("mon", INT2FIX(1)); - if (NIL_P(ref_hash("mday"))) - set_hash("mday", INT2FIX(1)); - } - else if (k == sym("commercial")) { - long i; - - for (i = 0; i < RARRAY_LEN(a); i++) { - VALUE e = RARRAY_AREF(a, i); - - if (!NIL_P(ref_hash0(e))) - break; - if (NIL_P(d)) - d = date_s_today(0, (VALUE *)0, cDate); - set_hash0(e, rb_funcall(d, SYM2ID(e), 0)); - } - if (NIL_P(ref_hash("cweek"))) - set_hash("cweek", INT2FIX(1)); - if (NIL_P(ref_hash("cwday"))) - set_hash("cwday", INT2FIX(1)); - } - else if (k == sym("wday")) { - if (NIL_P(d)) - d = date_s_today(0, (VALUE *)0, cDate); - set_hash("jd", d_lite_jd(f_add(f_sub(d, - d_lite_wday(d)), - ref_hash("wday")))); - } - else if (k == sym("wnum0")) { - long i; - - for (i = 0; i < RARRAY_LEN(a); i++) { - VALUE e = RARRAY_AREF(a, i); - - if (!NIL_P(ref_hash0(e))) - break; - if (NIL_P(d)) - d = date_s_today(0, (VALUE *)0, cDate); - set_hash0(e, rb_funcall(d, SYM2ID(e), 0)); - } - if (NIL_P(ref_hash("wnum0"))) - set_hash("wnum0", INT2FIX(0)); - if (NIL_P(ref_hash("wday"))) - set_hash("wday", INT2FIX(0)); - } - else if (k == sym("wnum1")) { - long i; - - for (i = 0; i < RARRAY_LEN(a); i++) { - VALUE e = RARRAY_AREF(a, i); - - if (!NIL_P(ref_hash0(e))) - break; - if (NIL_P(d)) - d = date_s_today(0, (VALUE *)0, cDate); - set_hash0(e, rb_funcall(d, SYM2ID(e), 0)); - } - if (NIL_P(ref_hash("wnum1"))) - set_hash("wnum1", INT2FIX(0)); - if (NIL_P(ref_hash("wday"))) - set_hash("wday", INT2FIX(1)); - } - } - - if (k == sym("time")) { - if (f_le_p(klass, cDateTime)) { - if (NIL_P(d)) - d = date_s_today(0, (VALUE *)0, cDate); - if (NIL_P(ref_hash("jd"))) - set_hash("jd", d_lite_jd(d)); - } - } - - if (NIL_P(ref_hash("hour"))) - set_hash("hour", INT2FIX(0)); - if (NIL_P(ref_hash("min"))) - set_hash("min", INT2FIX(0)); - if (NIL_P(ref_hash("sec"))) - set_hash("sec", INT2FIX(0)); - else if (f_gt_p(ref_hash("sec"), INT2FIX(59))) - set_hash("sec", INT2FIX(59)); - - return hash; -} - -static VALUE -rt__valid_jd_p(VALUE jd, VALUE sg) -{ - return jd; -} - -static VALUE -rt__valid_ordinal_p(VALUE y, VALUE d, VALUE sg) -{ - VALUE nth, rjd2; - int ry, rd, rjd, ns; - - if (!valid_ordinal_p(y, NUM2INT(d), NUM2DBL(sg), - &nth, &ry, - &rd, &rjd, - &ns)) - return Qnil; - encode_jd(nth, rjd, &rjd2); - return rjd2; -} - -static VALUE -rt__valid_civil_p(VALUE y, VALUE m, VALUE d, VALUE sg) -{ - VALUE nth, rjd2; - int ry, rm, rd, rjd, ns; - - if (!valid_civil_p(y, NUM2INT(m), NUM2INT(d), NUM2DBL(sg), - &nth, &ry, - &rm, &rd, &rjd, - &ns)) - return Qnil; - encode_jd(nth, rjd, &rjd2); - return rjd2; -} - -static VALUE -rt__valid_commercial_p(VALUE y, VALUE w, VALUE d, VALUE sg) -{ - VALUE nth, rjd2; - int ry, rw, rd, rjd, ns; - - if (!valid_commercial_p(y, NUM2INT(w), NUM2INT(d), NUM2DBL(sg), - &nth, &ry, - &rw, &rd, &rjd, - &ns)) - return Qnil; - encode_jd(nth, rjd, &rjd2); - return rjd2; -} - -static VALUE -rt__valid_weeknum_p(VALUE y, VALUE w, VALUE d, VALUE f, VALUE sg) -{ - VALUE nth, rjd2; - int ry, rw, rd, rjd, ns; - - if (!valid_weeknum_p(y, NUM2INT(w), NUM2INT(d), NUM2INT(f), NUM2DBL(sg), - &nth, &ry, - &rw, &rd, &rjd, - &ns)) - return Qnil; - encode_jd(nth, rjd, &rjd2); - return rjd2; -} - -static VALUE -rt__valid_date_frags_p(VALUE hash, VALUE sg) -{ - { - VALUE vjd; - - if (!NIL_P(vjd = ref_hash("jd"))) { - VALUE jd = rt__valid_jd_p(vjd, sg); - if (!NIL_P(jd)) - return jd; - } - } - - { - VALUE year, yday; - - if (!NIL_P(yday = ref_hash("yday")) && - !NIL_P(year = ref_hash("year"))) { - VALUE jd = rt__valid_ordinal_p(year, yday, sg); - if (!NIL_P(jd)) - return jd; - } - } - - { - VALUE year, mon, mday; - - if (!NIL_P(mday = ref_hash("mday")) && - !NIL_P(mon = ref_hash("mon")) && - !NIL_P(year = ref_hash("year"))) { - VALUE jd = rt__valid_civil_p(year, mon, mday, sg); - if (!NIL_P(jd)) - return jd; - } - } - - { - VALUE year, week, wday; - - wday = ref_hash("cwday"); - if (NIL_P(wday)) { - wday = ref_hash("wday"); - if (!NIL_P(wday)) - if (f_zero_p(wday)) - wday = INT2FIX(7); - } - - if (!NIL_P(wday) && - !NIL_P(week = ref_hash("cweek")) && - !NIL_P(year = ref_hash("cwyear"))) { - VALUE jd = rt__valid_commercial_p(year, week, wday, sg); - if (!NIL_P(jd)) - return jd; - } - } - - { - VALUE year, week, wday; - - wday = ref_hash("wday"); - if (NIL_P(wday)) { - wday = ref_hash("cwday"); - if (!NIL_P(wday)) - if (f_eqeq_p(wday, INT2FIX(7))) - wday = INT2FIX(0); - } - - if (!NIL_P(wday) && - !NIL_P(week = ref_hash("wnum0")) && - !NIL_P(year = ref_hash("year"))) { - VALUE jd = rt__valid_weeknum_p(year, week, wday, INT2FIX(0), sg); - if (!NIL_P(jd)) - return jd; - } - } - - { - VALUE year, week, wday; - - wday = ref_hash("wday"); - if (NIL_P(wday)) - wday = ref_hash("cwday"); - if (!NIL_P(wday)) - wday = f_mod(f_sub(wday, INT2FIX(1)), - INT2FIX(7)); - - if (!NIL_P(wday) && - !NIL_P(week = ref_hash("wnum1")) && - !NIL_P(year = ref_hash("year"))) { - VALUE jd = rt__valid_weeknum_p(year, week, wday, INT2FIX(1), sg); - if (!NIL_P(jd)) - return jd; - } - } - return Qnil; -} - -static VALUE -d_new_by_frags(VALUE klass, VALUE hash, VALUE sg) -{ - VALUE jd; - - if (!c_valid_start_p(NUM2DBL(sg))) { - sg = INT2FIX(DEFAULT_SG); - rb_warning("invalid start is ignored"); - } - - if (NIL_P(hash)) - rb_raise(eDateError, "invalid date"); - - if (NIL_P(ref_hash("jd")) && - NIL_P(ref_hash("yday")) && - !NIL_P(ref_hash("year")) && - !NIL_P(ref_hash("mon")) && - !NIL_P(ref_hash("mday"))) - jd = rt__valid_civil_p(ref_hash("year"), - ref_hash("mon"), - ref_hash("mday"), sg); - else { - hash = rt_rewrite_frags(hash); - hash = rt_complete_frags(klass, hash); - jd = rt__valid_date_frags_p(hash, sg); - } - - if (NIL_P(jd)) - rb_raise(eDateError, "invalid date"); - { - VALUE nth; - int rjd; - - decode_jd(jd, &nth, &rjd); - return d_simple_new_internal(klass, - nth, rjd, - NUM2DBL(sg), - 0, 0, 0, - HAVE_JD); - } -} - -VALUE date__strptime(const char *str, size_t slen, - const char *fmt, size_t flen, VALUE hash); - -static VALUE -date_s__strptime_internal(int argc, VALUE *argv, VALUE klass, - const char *default_fmt) -{ - VALUE vstr, vfmt, hash; - const char *str, *fmt; - size_t slen, flen; - - rb_scan_args(argc, argv, "11", &vstr, &vfmt); - - StringValue(vstr); - if (argc > 1) StringValue(vfmt); - if (!rb_enc_str_asciicompat_p(vstr)) - rb_raise(rb_eArgError, - "string should have ASCII compatible encoding"); - str = RSTRING_PTR(vstr); - slen = RSTRING_LEN(vstr); - if (argc < 2) { - fmt = default_fmt; - flen = strlen(default_fmt); - } - else { - if (!rb_enc_str_asciicompat_p(vfmt)) - rb_raise(rb_eArgError, - "format should have ASCII compatible encoding"); - fmt = RSTRING_PTR(vfmt); - flen = RSTRING_LEN(vfmt); - } - hash = rb_hash_new(); - if (NIL_P(date__strptime(str, slen, fmt, flen, hash))) - return Qnil; - - { - VALUE zone = ref_hash("zone"); - VALUE left = ref_hash("leftover"); - - if (!NIL_P(zone)) { - rb_enc_copy(zone, vstr); - set_hash("zone", zone); - } - if (!NIL_P(left)) { - rb_enc_copy(left, vstr); - set_hash("leftover", left); - } - } - - return hash; -} - -/* - * call-seq: - * Date._strptime(string, format = '%F') -> hash - * - * Returns a hash of values parsed from +string+ - * according to the given +format+: - * - * Date._strptime('2001-02-03', '%Y-%m-%d') # => {:year=>2001, :mon=>2, :mday=>3} - * - * For other formats, see - * {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]. - * (Unlike Date.strftime, does not support flags and width.) - * - * See also {strptime(3)}[https://man7.org/linux/man-pages/man3/strptime.3.html]. - * - * Related: Date.strptime (returns a \Date object). - */ -static VALUE -date_s__strptime(int argc, VALUE *argv, VALUE klass) -{ - return date_s__strptime_internal(argc, argv, klass, "%F"); -} - -/* - * call-seq: - * Date.strptime(string = '-4712-01-01', format = '%F', start = Date::ITALY) -> date - * - * Returns a new \Date object with values parsed from +string+, - * according to the given +format+: - * - * Date.strptime('2001-02-03', '%Y-%m-%d') # => # - * Date.strptime('03-02-2001', '%d-%m-%Y') # => # - * Date.strptime('2001-034', '%Y-%j') # => # - * Date.strptime('2001-W05-6', '%G-W%V-%u') # => # - * Date.strptime('2001 04 6', '%Y %U %w') # => # - * Date.strptime('2001 05 6', '%Y %W %u') # => # - * Date.strptime('sat3feb01', '%a%d%b%y') # => # - * - * For other formats, see - * {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]. - * (Unlike Date.strftime, does not support flags and width.) - * - * See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - * See also {strptime(3)}[https://man7.org/linux/man-pages/man3/strptime.3.html]. - * - * Related: Date._strptime (returns a hash). - */ -static VALUE -date_s_strptime(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, fmt, sg; - - rb_scan_args(argc, argv, "03", &str, &fmt, &sg); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATE); - case 1: - fmt = rb_str_new2("%F"); - case 2: - sg = INT2FIX(DEFAULT_SG); - } - - { - VALUE argv2[2], hash; - - argv2[0] = str; - argv2[1] = fmt; - hash = date_s__strptime(2, argv2, klass); - return d_new_by_frags(klass, hash, sg); - } -} - -VALUE date__parse(VALUE str, VALUE comp); - -static size_t -get_limit(VALUE opt) -{ - if (!NIL_P(opt)) { - VALUE limit = rb_hash_aref(opt, ID2SYM(rb_intern("limit"))); - if (NIL_P(limit)) return SIZE_MAX; - return NUM2SIZET(limit); - } - return 128; -} - -#ifndef HAVE_RB_CATEGORY_WARN -#define rb_category_warn(category, fmt) rb_warn(fmt) -#endif - -static VALUE -check_limit(VALUE str, VALUE opt) -{ - size_t slen, limit; - StringValue(str); - slen = RSTRING_LEN(str); - limit = get_limit(opt); - if (slen > limit) { - rb_raise(rb_eArgError, - "string length (%"PRI_SIZE_PREFIX"u) exceeds the limit %"PRI_SIZE_PREFIX"u", slen, limit); - } - return str; -} - -static VALUE -date_s__parse_internal(int argc, VALUE *argv, VALUE klass) -{ - VALUE vstr, vcomp, hash, opt; - - argc = rb_scan_args(argc, argv, "11:", &vstr, &vcomp, &opt); - vstr = check_limit(vstr, opt); - if (!rb_enc_str_asciicompat_p(vstr)) - rb_raise(rb_eArgError, - "string should have ASCII compatible encoding"); - if (argc < 2) - vcomp = Qtrue; - - hash = date__parse(vstr, vcomp); - - return hash; -} - -/* - * call-seq: - * Date._parse(string, comp = true, limit: 128) -> hash - * - * Note: - * This method recognizes many forms in +string+, - * but it is not a validator. - * For formats, see - * {"Specialized Format Strings" in Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc@Specialized+Format+Strings] - * - * If +string+ does not specify a valid date, - * the result is unpredictable; - * consider using Date._strptime instead. - * - * Returns a hash of values parsed from +string+: - * - * Date._parse('2001-02-03') # => {:year=>2001, :mon=>2, :mday=>3} - * - * If +comp+ is +true+ and the given year is in the range (0..99), - * the current century is supplied; - * otherwise, the year is taken as given: - * - * Date._parse('01-02-03', true) # => {:year=>2001, :mon=>2, :mday=>3} - * Date._parse('01-02-03', false) # => {:year=>1, :mon=>2, :mday=>3} - * - * See argument {limit}[rdoc-ref:Date@Argument+limit]. - * - * Related: Date.parse(returns a \Date object). - */ -static VALUE -date_s__parse(int argc, VALUE *argv, VALUE klass) -{ - return date_s__parse_internal(argc, argv, klass); -} - -/* - * call-seq: - * Date.parse(string = '-4712-01-01', comp = true, start = Date::ITALY, limit: 128) -> date - * - * Note: - * This method recognizes many forms in +string+, - * but it is not a validator. - * For formats, see - * {"Specialized Format Strings" in Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc@Specialized+Format+Strings] - * If +string+ does not specify a valid date, - * the result is unpredictable; - * consider using Date._strptime instead. - * - * Returns a new \Date object with values parsed from +string+: - * - * Date.parse('2001-02-03') # => # - * Date.parse('20010203') # => # - * Date.parse('3rd Feb 2001') # => # - * - * If +comp+ is +true+ and the given year is in the range (0..99), - * the current century is supplied; - * otherwise, the year is taken as given: - * - * Date.parse('01-02-03', true) # => # - * Date.parse('01-02-03', false) # => # - * - * See: - * - * - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - Argument {limit}[rdoc-ref:Date@Argument+limit]. - * - * Related: Date._parse (returns a hash). - */ -static VALUE -date_s_parse(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, comp, sg, opt; - - argc = rb_scan_args(argc, argv, "03:", &str, &comp, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATE); - case 1: - comp = Qtrue; - case 2: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 2; - VALUE argv2[3], hash; - argv2[0] = str; - argv2[1] = comp; - if (!NIL_P(opt)) argv2[argc2++] = opt; - hash = date_s__parse(argc2, argv2, klass); - return d_new_by_frags(klass, hash, sg); - } -} - -VALUE date__iso8601(VALUE); -VALUE date__rfc3339(VALUE); -VALUE date__xmlschema(VALUE); -VALUE date__rfc2822(VALUE); -VALUE date__httpdate(VALUE); -VALUE date__jisx0301(VALUE); - -/* - * call-seq: - * Date._iso8601(string, limit: 128) -> hash - * - * Returns a hash of values parsed from +string+, which should contain - * an {ISO 8601 formatted date}[rdoc-ref:language/strftime_formatting.rdoc@ISO+8601+Format+Specifications]: - * - * d = Date.new(2001, 2, 3) - * s = d.iso8601 # => "2001-02-03" - * Date._iso8601(s) # => {:mday=>3, :year=>2001, :mon=>2} - * - * See argument {limit}[rdoc-ref:Date@Argument+limit]. - * - * Related: Date.iso8601 (returns a \Date object). - */ -static VALUE -date_s__iso8601(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, opt; - - rb_scan_args(argc, argv, "1:", &str, &opt); - if (!NIL_P(str)) str = check_limit(str, opt); - - return date__iso8601(str); -} - -/* - * call-seq: - * Date.iso8601(string = '-4712-01-01', start = Date::ITALY, limit: 128) -> date - * - * Returns a new \Date object with values parsed from +string+, - * which should contain - * an {ISO 8601 formatted date}[rdoc-ref:language/strftime_formatting.rdoc@ISO+8601+Format+Specifications]: - * - * d = Date.new(2001, 2, 3) - * s = d.iso8601 # => "2001-02-03" - * Date.iso8601(s) # => # - * - * See: - * - * - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - Argument {limit}[rdoc-ref:Date@Argument+limit]. - * - * Related: Date._iso8601 (returns a hash). - */ -static VALUE -date_s_iso8601(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, sg, opt; - - argc = rb_scan_args(argc, argv, "02:", &str, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATE); - case 1: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 1; - VALUE argv2[2], hash; - argv2[0] = str; - if (!NIL_P(opt)) argv2[argc2++] = opt; - hash = date_s__iso8601(argc2, argv2, klass); - return d_new_by_frags(klass, hash, sg); - } -} - -/* - * call-seq: - * Date._rfc3339(string, limit: 128) -> hash - * - * Returns a hash of values parsed from +string+, which should be a valid - * {RFC 3339 format}[rdoc-ref:language/strftime_formatting.rdoc@RFC+3339+Format]: - * - * d = Date.new(2001, 2, 3) - * s = d.rfc3339 # => "2001-02-03T00:00:00+00:00" - * Date._rfc3339(s) - * # => {:year=>2001, :mon=>2, :mday=>3, :hour=>0, :min=>0, :sec=>0, :zone=>"+00:00", :offset=>0} - * - * See argument {limit}[rdoc-ref:Date@Argument+limit]. - * - * Related: Date.rfc3339 (returns a \Date object). - */ -static VALUE -date_s__rfc3339(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, opt; - - rb_scan_args(argc, argv, "1:", &str, &opt); - if (!NIL_P(str)) str = check_limit(str, opt); - - return date__rfc3339(str); -} - -/* - * call-seq: - * Date.rfc3339(string = '-4712-01-01T00:00:00+00:00', start = Date::ITALY, limit: 128) -> date - * - * Returns a new \Date object with values parsed from +string+, - * which should be a valid - * {RFC 3339 format}[rdoc-ref:language/strftime_formatting.rdoc@RFC+3339+Format]: - * - * d = Date.new(2001, 2, 3) - * s = d.rfc3339 # => "2001-02-03T00:00:00+00:00" - * Date.rfc3339(s) # => # - * - * See: - * - * - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - Argument {limit}[rdoc-ref:Date@Argument+limit]. - * - * Related: Date._rfc3339 (returns a hash). - */ -static VALUE -date_s_rfc3339(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, sg, opt; - - argc = rb_scan_args(argc, argv, "02:", &str, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATETIME); - case 1: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 1; - VALUE argv2[2], hash; - argv2[0] = str; - if (!NIL_P(opt)) argv2[argc2++] = opt; - hash = date_s__rfc3339(argc2, argv2, klass); - return d_new_by_frags(klass, hash, sg); - } -} - -/* - * call-seq: - * Date._xmlschema(string, limit: 128) -> hash - * - * Returns a hash of values parsed from +string+, which should be a valid - * XML date format: - * - * d = Date.new(2001, 2, 3) - * s = d.xmlschema # => "2001-02-03" - * Date._xmlschema(s) # => {:year=>2001, :mon=>2, :mday=>3} - * - * See argument {limit}[rdoc-ref:Date@Argument+limit]. - * - * Related: Date.xmlschema (returns a \Date object). - */ -static VALUE -date_s__xmlschema(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, opt; - - rb_scan_args(argc, argv, "1:", &str, &opt); - if (!NIL_P(str)) str = check_limit(str, opt); - - return date__xmlschema(str); -} - -/* - * call-seq: - * Date.xmlschema(string = '-4712-01-01', start = Date::ITALY, limit: 128) -> date - * - * Returns a new \Date object with values parsed from +string+, - * which should be a valid XML date format: - * - * d = Date.new(2001, 2, 3) - * s = d.xmlschema # => "2001-02-03" - * Date.xmlschema(s) # => # - * - * See: - * - * - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - Argument {limit}[rdoc-ref:Date@Argument+limit]. - * - * Related: Date._xmlschema (returns a hash). - */ -static VALUE -date_s_xmlschema(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, sg, opt; - - argc = rb_scan_args(argc, argv, "02:", &str, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATE); - case 1: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 1; - VALUE argv2[2], hash; - argv2[0] = str; - if (!NIL_P(opt)) argv2[argc2++] = opt; - hash = date_s__xmlschema(argc2, argv2, klass); - return d_new_by_frags(klass, hash, sg); - } -} - -/* - * call-seq: - * Date._rfc2822(string, limit: 128) -> hash - * - * Returns a hash of values parsed from +string+, which should be a valid - * {RFC 2822 date format}[rdoc-ref:language/strftime_formatting.rdoc@RFC+2822+Format]: - * - * d = Date.new(2001, 2, 3) - * s = d.rfc2822 # => "Sat, 3 Feb 2001 00:00:00 +0000" - * Date._rfc2822(s) - * # => {:wday=>6, :mday=>3, :mon=>2, :year=>2001, :hour=>0, :min=>0, :sec=>0, :zone=>"+0000", :offset=>0} - * - * See argument {limit}[rdoc-ref:Date@Argument+limit]. - * - * Related: Date.rfc2822 (returns a \Date object). - */ -static VALUE -date_s__rfc2822(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, opt; - - rb_scan_args(argc, argv, "1:", &str, &opt); - if (!NIL_P(str)) str = check_limit(str, opt); - - return date__rfc2822(str); -} - -/* - * call-seq: - * Date.rfc2822(string = 'Mon, 1 Jan -4712 00:00:00 +0000', start = Date::ITALY, limit: 128) -> date - * - * Returns a new \Date object with values parsed from +string+, - * which should be a valid - * {RFC 2822 date format}[rdoc-ref:language/strftime_formatting.rdoc@RFC+2822+Format]: - * - * d = Date.new(2001, 2, 3) - * s = d.rfc2822 # => "Sat, 3 Feb 2001 00:00:00 +0000" - * Date.rfc2822(s) # => # - * - * See: - * - * - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - Argument {limit}[rdoc-ref:Date@Argument+limit]. - * - * Related: Date._rfc2822 (returns a hash). - */ -static VALUE -date_s_rfc2822(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, sg, opt; - - argc = rb_scan_args(argc, argv, "02:", &str, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATETIME_RFC3339); - case 1: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 1; - VALUE argv2[2], hash; - argv2[0] = str; - if (!NIL_P(opt)) argv2[argc2++] = opt; - hash = date_s__rfc2822(argc2, argv2, klass); - return d_new_by_frags(klass, hash, sg); - } -} - -/* - * call-seq: - * Date._httpdate(string, limit: 128) -> hash - * - * Returns a hash of values parsed from +string+, which should be a valid - * {HTTP date format}[rdoc-ref:language/strftime_formatting.rdoc@HTTP+Format]: - * - * d = Date.new(2001, 2, 3) - * s = d.httpdate # => "Sat, 03 Feb 2001 00:00:00 GMT" - * Date._httpdate(s) - * # => {:wday=>6, :mday=>3, :mon=>2, :year=>2001, :hour=>0, :min=>0, :sec=>0, :zone=>"GMT", :offset=>0} - * - * Related: Date.httpdate (returns a \Date object). - */ -static VALUE -date_s__httpdate(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, opt; - - rb_scan_args(argc, argv, "1:", &str, &opt); - if (!NIL_P(str)) str = check_limit(str, opt); - - return date__httpdate(str); -} - -/* - * call-seq: - * Date.httpdate(string = 'Mon, 01 Jan -4712 00:00:00 GMT', start = Date::ITALY, limit: 128) -> date - * - * Returns a new \Date object with values parsed from +string+, - * which should be a valid - * {HTTP date format}[rdoc-ref:language/strftime_formatting.rdoc@HTTP+Format]: - * - * d = Date.new(2001, 2, 3) - s = d.httpdate # => "Sat, 03 Feb 2001 00:00:00 GMT" - Date.httpdate(s) # => # - * - * See: - * - * - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - Argument {limit}[rdoc-ref:Date@Argument+limit]. - * - * Related: Date._httpdate (returns a hash). - */ -static VALUE -date_s_httpdate(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, sg, opt; - - argc = rb_scan_args(argc, argv, "02:", &str, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATETIME_HTTPDATE); - case 1: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 1; - VALUE argv2[2], hash; - argv2[0] = str; - if (!NIL_P(opt)) argv2[argc2++] = opt; - hash = date_s__httpdate(argc2, argv2, klass); - return d_new_by_frags(klass, hash, sg); - } -} - -/* - * call-seq: - * Date._jisx0301(string, limit: 128) -> hash - * - * Returns a hash of values parsed from +string+, which should be a valid - * {JIS X 0301 date format}[rdoc-ref:language/strftime_formatting.rdoc@JIS+X+0301+Format]: - * - * d = Date.new(2001, 2, 3) - * s = d.jisx0301 # => "H13.02.03" - * Date._jisx0301(s) # => {:year=>2001, :mon=>2, :mday=>3} - * - * See argument {limit}[rdoc-ref:Date@Argument+limit]. - * - * Related: Date.jisx0301 (returns a \Date object). - */ -static VALUE -date_s__jisx0301(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, opt; - - rb_scan_args(argc, argv, "1:", &str, &opt); - if (!NIL_P(str)) str = check_limit(str, opt); - - return date__jisx0301(str); -} - -/* - * call-seq: - * Date.jisx0301(string = '-4712-01-01', start = Date::ITALY, limit: 128) -> date - * - * Returns a new \Date object with values parsed from +string+, - * which should be a valid {JIS X 0301 format}[rdoc-ref:language/strftime_formatting.rdoc@JIS+X+0301+Format]: - * - * d = Date.new(2001, 2, 3) - * s = d.jisx0301 # => "H13.02.03" - * Date.jisx0301(s) # => # - * - * For no-era year, legacy format, Heisei is assumed. - * - * Date.jisx0301('13.02.03') # => # - * - * See: - * - * - Argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - Argument {limit}[rdoc-ref:Date@Argument+limit]. - * - * Related: Date._jisx0301 (returns a hash). - */ -static VALUE -date_s_jisx0301(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, sg, opt; - - argc = rb_scan_args(argc, argv, "02:", &str, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATE); - case 1: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 1; - VALUE argv2[2], hash; - argv2[0] = str; - if (!NIL_P(opt)) argv2[argc2++] = opt; - hash = date_s__jisx0301(argc2, argv2, klass); - return d_new_by_frags(klass, hash, sg); - } -} - -static VALUE -dup_obj(VALUE self) -{ - get_d1a(self); - - if (simple_dat_p(adat)) { - VALUE new = d_lite_s_alloc_simple(rb_obj_class(self)); - { - get_d1b(new); - bdat->s = adat->s; - RB_OBJ_WRITTEN(new, Qundef, bdat->s.nth); - return new; - } - } - else { - VALUE new = d_lite_s_alloc_complex(rb_obj_class(self)); - { - get_d1b(new); - bdat->c = adat->c; - RB_OBJ_WRITTEN(new, Qundef, bdat->c.nth); - RB_OBJ_WRITTEN(new, Qundef, bdat->c.sf); - return new; - } - } -} - -static VALUE -dup_obj_as_complex(VALUE self) -{ - get_d1a(self); - - if (simple_dat_p(adat)) { - VALUE new = d_lite_s_alloc_complex(rb_obj_class(self)); - { - get_d1b(new); - copy_simple_to_complex(new, &bdat->c, &adat->s); - bdat->c.flags |= HAVE_DF | COMPLEX_DAT; - return new; - } - } - else { - VALUE new = d_lite_s_alloc_complex(rb_obj_class(self)); - { - get_d1b(new); - bdat->c = adat->c; - RB_OBJ_WRITTEN(new, Qundef, bdat->c.nth); - RB_OBJ_WRITTEN(new, Qundef, bdat->c.sf); - return new; - } - } -} - -#define val2off(vof,iof) \ -do {\ - if (!offset_to_sec(vof, &iof)) {\ - iof = 0;\ - rb_warning("invalid offset is ignored");\ - }\ -} while (0) - -#if 0 -static VALUE -d_lite_initialize(int argc, VALUE *argv, VALUE self) -{ - VALUE jd, vjd, vdf, sf, vsf, vof, vsg; - int df, of; - double sg; - - rb_check_frozen(self); - - rb_scan_args(argc, argv, "05", &vjd, &vdf, &vsf, &vof, &vsg); - - jd = INT2FIX(0); - df = 0; - sf = INT2FIX(0); - of = 0; - sg = DEFAULT_SG; - - switch (argc) { - case 5: - val2sg(vsg, sg); - case 4: - val2off(vof, of); - case 3: - sf = vsf; - if (f_lt_p(sf, INT2FIX(0)) || - f_ge_p(sf, INT2FIX(SECOND_IN_NANOSECONDS))) - rb_raise(eDateError, "invalid second fraction"); - case 2: - df = NUM2INT(vdf); - if (df < 0 || df >= DAY_IN_SECONDS) - rb_raise(eDateError, "invalid day fraction"); - case 1: - jd = vjd; - } - - { - VALUE nth; - int rjd; - - get_d1(self); - - decode_jd(jd, &nth, &rjd); - if (!df && f_zero_p(sf) && !of) { - set_to_simple(self, &dat->s, nth, rjd, sg, 0, 0, 0, HAVE_JD); - } - else { - if (!complex_dat_p(dat)) - rb_raise(rb_eArgError, - "cannot load complex into simple"); - - set_to_complex(self, &dat->c, nth, rjd, df, sf, of, sg, - 0, 0, 0, 0, 0, 0, HAVE_JD | HAVE_DF); - } - } - return self; -} -#endif - -/* :nodoc: */ -static VALUE -d_lite_initialize_copy(VALUE copy, VALUE date) -{ - rb_check_frozen(copy); - - if (copy == date) - return copy; - { - get_d2(copy, date); - if (simple_dat_p(bdat)) { - if (simple_dat_p(adat)) { - adat->s = bdat->s; - } - else { - adat->c.flags = bdat->s.flags | COMPLEX_DAT; - adat->c.nth = bdat->s.nth; - adat->c.jd = bdat->s.jd; - adat->c.df = 0; - adat->c.sf = INT2FIX(0); - adat->c.of = 0; - adat->c.sg = bdat->s.sg; - adat->c.year = bdat->s.year; -#ifndef USE_PACK - adat->c.mon = bdat->s.mon; - adat->c.mday = bdat->s.mday; - adat->c.hour = bdat->s.hour; - adat->c.min = bdat->s.min; - adat->c.sec = bdat->s.sec; -#else - adat->c.pc = bdat->s.pc; -#endif - } - } - else { - if (!complex_dat_p(adat)) - rb_raise(rb_eArgError, - "cannot load complex into simple"); - - adat->c = bdat->c; - } - } - return copy; -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -d_lite_fill(VALUE self) -{ - get_d1(self); - - if (simple_dat_p(dat)) { - get_s_jd(dat); - get_s_civil(dat); - } - else { - get_c_jd(dat); - get_c_civil(dat); - get_c_df(dat); - get_c_time(dat); - } - return self; -} -#endif - -/* - * call-seq: - * d.ajd -> rational - * - * Returns the astronomical Julian day number. This is a fractional - * number, which is not adjusted by the offset. - * - * DateTime.new(2001,2,3,4,5,6,'+7').ajd #=> (11769328217/4800) - * DateTime.new(2001,2,2,14,5,6,'-7').ajd #=> (11769328217/4800) - */ -static VALUE -d_lite_ajd(VALUE self) -{ - get_d1(self); - return m_ajd(dat); -} - -/* - * call-seq: - * d.amjd -> rational - * - * Returns the astronomical modified Julian day number. This is - * a fractional number, which is not adjusted by the offset. - * - * DateTime.new(2001,2,3,4,5,6,'+7').amjd #=> (249325817/4800) - * DateTime.new(2001,2,2,14,5,6,'-7').amjd #=> (249325817/4800) - */ -static VALUE -d_lite_amjd(VALUE self) -{ - get_d1(self); - return m_amjd(dat); -} - -/* - * call-seq: - * d.jd -> integer - * - * Returns the Julian day number. This is a whole number, which is - * adjusted by the offset as the local time. - * - * DateTime.new(2001,2,3,4,5,6,'+7').jd #=> 2451944 - * DateTime.new(2001,2,3,4,5,6,'-7').jd #=> 2451944 - */ -static VALUE -d_lite_jd(VALUE self) -{ - get_d1(self); - return m_real_local_jd(dat); -} - -/* - * call-seq: - * d.mjd -> integer - * - * Returns the modified Julian day number. This is a whole number, - * which is adjusted by the offset as the local time. - * - * DateTime.new(2001,2,3,4,5,6,'+7').mjd #=> 51943 - * DateTime.new(2001,2,3,4,5,6,'-7').mjd #=> 51943 - */ -static VALUE -d_lite_mjd(VALUE self) -{ - get_d1(self); - return f_sub(m_real_local_jd(dat), INT2FIX(2400001)); -} - -/* - * call-seq: - * ld -> integer - * - * Returns the - * {Lilian day number}[https://en.wikipedia.org/wiki/Lilian_date], - * which is the number of days since the beginning of the Gregorian - * calendar, October 15, 1582. - * - * Date.new(2001, 2, 3).ld # => 152784 - * - */ -static VALUE -d_lite_ld(VALUE self) -{ - get_d1(self); - return f_sub(m_real_local_jd(dat), INT2FIX(2299160)); -} - -/* - * call-seq: - * year -> integer - * - * Returns the year: - * - * Date.new(2001, 2, 3).year # => 2001 - * (Date.new(1, 1, 1) - 1).year # => 0 - * - */ -static VALUE -d_lite_year(VALUE self) -{ - get_d1(self); - return m_real_year(dat); -} - -/* - * call-seq: - * yday -> integer - * - * Returns the day of the year, in range (1..366): - * - * Date.new(2001, 2, 3).yday # => 34 - * - */ -static VALUE -d_lite_yday(VALUE self) -{ - get_d1(self); - return INT2FIX(m_yday(dat)); -} - -/* - * call-seq: - * mon -> integer - * - * Returns the month in range (1..12): - * - * Date.new(2001, 2, 3).mon # => 2 - * - */ -static VALUE -d_lite_mon(VALUE self) -{ - get_d1(self); - return INT2FIX(m_mon(dat)); -} - -/* - * call-seq: - * mday -> integer - * - * Returns the day of the month in range (1..31): - * - * Date.new(2001, 2, 3).mday # => 3 - * - */ -static VALUE -d_lite_mday(VALUE self) -{ - get_d1(self); - return INT2FIX(m_mday(dat)); -} - -/* - * call-seq: - * day_fraction -> rational - * - * Returns the fractional part of the day in range (Rational(0, 1)...Rational(1, 1)): - * - * DateTime.new(2001,2,3,12).day_fraction # => (1/2) - * - */ -static VALUE -d_lite_day_fraction(VALUE self) -{ - get_d1(self); - if (simple_dat_p(dat)) - return INT2FIX(0); - return m_fr(dat); -} - -/* - * call-seq: - * cwyear -> integer - * - * Returns commercial-date year for +self+ - * (see Date.commercial): - * - * Date.new(2001, 2, 3).cwyear # => 2001 - * Date.new(2000, 1, 1).cwyear # => 1999 - * - */ -static VALUE -d_lite_cwyear(VALUE self) -{ - get_d1(self); - return m_real_cwyear(dat); -} - -/* - * call-seq: - * cweek -> integer - * - * Returns commercial-date week index for +self+ - * (see Date.commercial): - * - * Date.new(2001, 2, 3).cweek # => 5 - * - */ -static VALUE -d_lite_cweek(VALUE self) -{ - get_d1(self); - return INT2FIX(m_cweek(dat)); -} - -/* - * call-seq: - * cwday -> integer - * - * Returns the commercial-date weekday index for +self+ - * (see Date.commercial); - * 1 is Monday: - * - * Date.new(2001, 2, 3).cwday # => 6 - * - */ -static VALUE -d_lite_cwday(VALUE self) -{ - get_d1(self); - return INT2FIX(m_cwday(dat)); -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -d_lite_wnum0(VALUE self) -{ - get_d1(self); - return INT2FIX(m_wnum0(dat)); -} - -/* :nodoc: */ -static VALUE -d_lite_wnum1(VALUE self) -{ - get_d1(self); - return INT2FIX(m_wnum1(dat)); -} -#endif - -/* - * call-seq: - * wday -> integer - * - * Returns the day of week in range (0..6); Sunday is 0: - * - * Date.new(2001, 2, 3).wday # => 6 - * - */ -static VALUE -d_lite_wday(VALUE self) -{ - get_d1(self); - return INT2FIX(m_wday(dat)); -} - -/* - * call-seq: - * sunday? -> true or false - * - * Returns +true+ if +self+ is a Sunday, +false+ otherwise. - */ -static VALUE -d_lite_sunday_p(VALUE self) -{ - get_d1(self); - return f_boolcast(m_wday(dat) == 0); -} - -/* - * call-seq: - * monday? -> true or false - * - * Returns +true+ if +self+ is a Monday, +false+ otherwise. - */ -static VALUE -d_lite_monday_p(VALUE self) -{ - get_d1(self); - return f_boolcast(m_wday(dat) == 1); -} - -/* - * call-seq: - * tuesday? -> true or false - * - * Returns +true+ if +self+ is a Tuesday, +false+ otherwise. - */ -static VALUE -d_lite_tuesday_p(VALUE self) -{ - get_d1(self); - return f_boolcast(m_wday(dat) == 2); -} - -/* - * call-seq: - * wednesday? -> true or false - * - * Returns +true+ if +self+ is a Wednesday, +false+ otherwise. - */ -static VALUE -d_lite_wednesday_p(VALUE self) -{ - get_d1(self); - return f_boolcast(m_wday(dat) == 3); -} - -/* - * call-seq: - * thursday? -> true or false - * - * Returns +true+ if +self+ is a Thursday, +false+ otherwise. - */ -static VALUE -d_lite_thursday_p(VALUE self) -{ - get_d1(self); - return f_boolcast(m_wday(dat) == 4); -} - -/* - * call-seq: - * friday? -> true or false - * - * Returns +true+ if +self+ is a Friday, +false+ otherwise. - */ -static VALUE -d_lite_friday_p(VALUE self) -{ - get_d1(self); - return f_boolcast(m_wday(dat) == 5); -} - -/* - * call-seq: - * saturday? -> true or false - * - * Returns +true+ if +self+ is a Saturday, +false+ otherwise. - */ -static VALUE -d_lite_saturday_p(VALUE self) -{ - get_d1(self); - return f_boolcast(m_wday(dat) == 6); -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -d_lite_nth_kday_p(VALUE self, VALUE n, VALUE k) -{ - int rjd, ns; - - get_d1(self); - - if (NUM2INT(k) != m_wday(dat)) - return Qfalse; - - c_nth_kday_to_jd(m_year(dat), m_mon(dat), - NUM2INT(n), NUM2INT(k), m_virtual_sg(dat), /* !=m_sg() */ - &rjd, &ns); - if (m_local_jd(dat) != rjd) - return Qfalse; - return Qtrue; -} -#endif - -/* - * call-seq: - * hour -> integer - * - * Returns the hour in range (0..23): - * - * DateTime.new(2001, 2, 3, 4, 5, 6).hour # => 4 - * - */ -static VALUE -d_lite_hour(VALUE self) -{ - get_d1(self); - return INT2FIX(m_hour(dat)); -} - -/* - * call-seq: - * min -> integer - * - * Returns the minute in range (0..59): - * - * DateTime.new(2001, 2, 3, 4, 5, 6).min # => 5 - * - */ -static VALUE -d_lite_min(VALUE self) -{ - get_d1(self); - return INT2FIX(m_min(dat)); -} - -/* - * call-seq: - * sec -> integer - * - * Returns the second in range (0..59): - * - * DateTime.new(2001, 2, 3, 4, 5, 6).sec # => 6 - * - */ -static VALUE -d_lite_sec(VALUE self) -{ - get_d1(self); - return INT2FIX(m_sec(dat)); -} - -/* - * call-seq: - * sec_fraction -> rational - * - * Returns the fractional part of the second in range - * (Rational(0, 1)...Rational(1, 1)): - * - * DateTime.new(2001, 2, 3, 4, 5, 6.5).sec_fraction # => (1/2) - * - */ -static VALUE -d_lite_sec_fraction(VALUE self) -{ - get_d1(self); - return m_sf_in_sec(dat); -} - -/* - * call-seq: - * d.offset -> rational - * - * Returns the offset. - * - * DateTime.parse('04pm+0730').offset #=> (5/16) - */ -static VALUE -d_lite_offset(VALUE self) -{ - get_d1(self); - return m_of_in_day(dat); -} - -/* - * call-seq: - * d.zone -> string - * - * Returns the timezone. - * - * DateTime.parse('04pm+0730').zone #=> "+07:30" - */ -static VALUE -d_lite_zone(VALUE self) -{ - get_d1(self); - return m_zone(dat); -} - -/* - * call-seq: - * d.julian? -> true or false - * - * Returns +true+ if the date is before the date of calendar reform, - * +false+ otherwise: - * - * (Date.new(1582, 10, 15) - 1).julian? # => true - * Date.new(1582, 10, 15).julian? # => false - * - */ -static VALUE -d_lite_julian_p(VALUE self) -{ - get_d1(self); - return f_boolcast(m_julian_p(dat)); -} - -/* - * call-seq: - * gregorian? -> true or false - * - * Returns +true+ if the date is on or after - * the date of calendar reform, +false+ otherwise: - * - * Date.new(1582, 10, 15).gregorian? # => true - * (Date.new(1582, 10, 15) - 1).gregorian? # => false - * - */ -static VALUE -d_lite_gregorian_p(VALUE self) -{ - get_d1(self); - return f_boolcast(m_gregorian_p(dat)); -} - -/* - * call-seq: - * leap? -> true or false - * - * Returns +true+ if the year is a leap year, +false+ otherwise: - * - * Date.new(2000).leap? # => true - * Date.new(2001).leap? # => false - * - */ -static VALUE -d_lite_leap_p(VALUE self) -{ - int rjd, ns, ry, rm, rd; - - get_d1(self); - if (m_gregorian_p(dat)) - return f_boolcast(c_gregorian_leap_p(m_year(dat))); - - c_civil_to_jd(m_year(dat), 3, 1, m_virtual_sg(dat), - &rjd, &ns); - c_jd_to_civil(rjd - 1, m_virtual_sg(dat), &ry, &rm, &rd); - return f_boolcast(rd == 29); -} - -/* - * call-seq: - * start -> float - * - * Returns the Julian start date for calendar reform; - * if not an infinity, the returned value is suitable - * for passing to Date#jd: - * - * d = Date.new(2001, 2, 3, Date::ITALY) - * s = d.start # => 2299161.0 - * Date.jd(s).to_s # => "1582-10-15" - * - * d = Date.new(2001, 2, 3, Date::ENGLAND) - * s = d.start # => 2361222.0 - * Date.jd(s).to_s # => "1752-09-14" - * - * Date.new(2001, 2, 3, Date::GREGORIAN).start # => -Infinity - * Date.new(2001, 2, 3, Date::JULIAN).start # => Infinity - * - * See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - */ -static VALUE -d_lite_start(VALUE self) -{ - get_d1(self); - return DBL2NUM(m_sg(dat)); -} - -static void -clear_civil(union DateData *x) -{ - if (simple_dat_p(x)) { - x->s.year = 0; -#ifndef USE_PACK - x->s.mon = 0; - x->s.mday = 0; -#else - x->s.pc = 0; -#endif - x->s.flags &= ~HAVE_CIVIL; - } - else { - x->c.year = 0; -#ifndef USE_PACK - x->c.mon = 0; - x->c.mday = 0; - x->c.hour = 0; - x->c.min = 0; - x->c.sec = 0; -#else - x->c.pc = 0; -#endif - x->c.flags &= ~(HAVE_CIVIL | HAVE_TIME); - } -} - -static void -set_sg(union DateData *x, double sg) -{ - if (simple_dat_p(x)) { - get_s_jd(x); - clear_civil(x); - x->s.sg = (date_sg_t)sg; - } else { - get_c_jd(x); - get_c_df(x); - clear_civil(x); - x->c.sg = (date_sg_t)sg; - } -} - -static VALUE -dup_obj_with_new_start(VALUE obj, double sg) -{ - volatile VALUE dup = dup_obj(obj); - { - get_d1(dup); - set_sg(dat, sg); - } - return dup; -} - -/* - * call-seq: - * new_start(start = Date::ITALY) -> new_date - * - * Returns a copy of +self+ with the given +start+ value: - * - * d0 = Date.new(2000, 2, 3) - * d0.julian? # => false - * d1 = d0.new_start(Date::JULIAN) - * d1.julian? # => true - * - * See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. - * - */ -static VALUE -d_lite_new_start(int argc, VALUE *argv, VALUE self) -{ - VALUE vsg; - double sg; - - rb_scan_args(argc, argv, "01", &vsg); - - sg = DEFAULT_SG; - if (argc >= 1) - val2sg(vsg, sg); - - return dup_obj_with_new_start(self, sg); -} - -/* - * call-seq: - * italy -> new_date - * - * Equivalent to Date#new_start with argument Date::ITALY. - * - */ -static VALUE -d_lite_italy(VALUE self) -{ - return dup_obj_with_new_start(self, ITALY); -} - -/* - * call-seq: - * england -> new_date - * - * Equivalent to Date#new_start with argument Date::ENGLAND. - */ -static VALUE -d_lite_england(VALUE self) -{ - return dup_obj_with_new_start(self, ENGLAND); -} - -/* - * call-seq: - * julian -> new_date - * - * Equivalent to Date#new_start with argument Date::JULIAN. - */ -static VALUE -d_lite_julian(VALUE self) -{ - return dup_obj_with_new_start(self, JULIAN); -} - -/* - * call-seq: - * gregorian -> new_date - * - * Equivalent to Date#new_start with argument Date::GREGORIAN. - */ -static VALUE -d_lite_gregorian(VALUE self) -{ - return dup_obj_with_new_start(self, GREGORIAN); -} - -static void -set_of(union DateData *x, int of) -{ - assert(complex_dat_p(x)); - get_c_jd(x); - get_c_df(x); - clear_civil(x); - x->c.of = of; -} - -static VALUE -dup_obj_with_new_offset(VALUE obj, int of) -{ - volatile VALUE dup = dup_obj_as_complex(obj); - { - get_d1(dup); - set_of(dat, of); - } - return dup; -} - -/* - * call-seq: - * d.new_offset([offset=0]) -> date - * - * Duplicates self and resets its offset. - * - * d = DateTime.new(2001,2,3,4,5,6,'-02:00') - * #=> # - * d.new_offset('+09:00') #=> # - */ -static VALUE -d_lite_new_offset(int argc, VALUE *argv, VALUE self) -{ - VALUE vof; - int rof; - - rb_scan_args(argc, argv, "01", &vof); - - rof = 0; - if (argc >= 1) - val2off(vof, rof); - - return dup_obj_with_new_offset(self, rof); -} - -/* - * call-seq: - * d + other -> date - * - * Returns a date object pointing +other+ days after self. The other - * should be a numeric value. If the other is a fractional number, - * assumes its precision is at most nanosecond. - * - * Date.new(2001,2,3) + 1 #=> # - * DateTime.new(2001,2,3) + Rational(1,2) - * #=> # - * DateTime.new(2001,2,3) + Rational(-1,2) - * #=> # - * DateTime.jd(0,12) + DateTime.new(2001,2,3).ajd - * #=> # - */ -static VALUE -d_lite_plus(VALUE self, VALUE other) -{ - int try_rational = 1; - get_d1(self); - - again: - switch (TYPE(other)) { - case T_FIXNUM: - { - VALUE nth; - long t; - int jd; - - nth = m_nth(dat); - t = FIX2LONG(other); - if (DIV(t, CM_PERIOD)) { - nth = f_add(nth, INT2FIX(DIV(t, CM_PERIOD))); - t = MOD(t, CM_PERIOD); - } - - if (!t) - jd = m_jd(dat); - else { - jd = m_jd(dat) + (int)t; - canonicalize_jd(nth, jd); - } - - if (simple_dat_p(dat)) - return d_simple_new_internal(rb_obj_class(self), - nth, jd, - dat->s.sg, - 0, 0, 0, - (dat->s.flags | HAVE_JD) & - ~HAVE_CIVIL); - else - return d_complex_new_internal(rb_obj_class(self), - nth, jd, - dat->c.df, dat->c.sf, - dat->c.of, dat->c.sg, - 0, 0, 0, -#ifndef USE_PACK - dat->c.hour, - dat->c.min, - dat->c.sec, -#else - EX_HOUR(dat->c.pc), - EX_MIN(dat->c.pc), - EX_SEC(dat->c.pc), -#endif - (dat->c.flags | HAVE_JD) & - ~HAVE_CIVIL); - } - break; - case T_BIGNUM: - { - VALUE nth; - int jd, s; - - if (f_positive_p(other)) - s = +1; - else { - s = -1; - other = f_negate(other); - } - - nth = f_idiv(other, INT2FIX(CM_PERIOD)); - jd = FIX2INT(f_mod(other, INT2FIX(CM_PERIOD))); - - if (s < 0) { - nth = f_negate(nth); - jd = -jd; - } - - if (!jd) - jd = m_jd(dat); - else { - jd = m_jd(dat) + jd; - canonicalize_jd(nth, jd); - } - - if (f_zero_p(nth)) - nth = m_nth(dat); - else - nth = f_add(m_nth(dat), nth); - - if (simple_dat_p(dat)) - return d_simple_new_internal(rb_obj_class(self), - nth, jd, - dat->s.sg, - 0, 0, 0, - (dat->s.flags | HAVE_JD) & - ~HAVE_CIVIL); - else - return d_complex_new_internal(rb_obj_class(self), - nth, jd, - dat->c.df, dat->c.sf, - dat->c.of, dat->c.sg, - 0, 0, 0, -#ifndef USE_PACK - dat->c.hour, - dat->c.min, - dat->c.sec, -#else - EX_HOUR(dat->c.pc), - EX_MIN(dat->c.pc), - EX_SEC(dat->c.pc), -#endif - (dat->c.flags | HAVE_JD) & - ~HAVE_CIVIL); - } - break; - case T_FLOAT: - { - double jd, o, tmp; - int s, df; - VALUE nth, sf; - - o = RFLOAT_VALUE(other); - - if (o > 0) - s = +1; - else { - s = -1; - o = -o; - } - - o = modf(o, &tmp); - - if (!floor(tmp / CM_PERIOD)) { - nth = INT2FIX(0); - jd = (int)tmp; - } - else { - double i, f; - - f = modf(tmp / CM_PERIOD, &i); - nth = f_floor(DBL2NUM(i)); - jd = (int)(f * CM_PERIOD); - } - - o *= DAY_IN_SECONDS; - o = modf(o, &tmp); - df = (int)tmp; - o *= SECOND_IN_NANOSECONDS; - sf = INT2FIX((int)round(o)); - - if (s < 0) { - jd = -jd; - df = -df; - sf = f_negate(sf); - } - - if (f_zero_p(sf)) - sf = m_sf(dat); - else { - sf = f_add(m_sf(dat), sf); - if (f_lt_p(sf, INT2FIX(0))) { - df -= 1; - sf = f_add(sf, INT2FIX(SECOND_IN_NANOSECONDS)); - } - else if (f_ge_p(sf, INT2FIX(SECOND_IN_NANOSECONDS))) { - df += 1; - sf = f_sub(sf, INT2FIX(SECOND_IN_NANOSECONDS)); - } - } - - if (!df) - df = m_df(dat); - else { - df = m_df(dat) + df; - if (df < 0) { - jd -= 1; - df += DAY_IN_SECONDS; - } - else if (df >= DAY_IN_SECONDS) { - jd += 1; - df -= DAY_IN_SECONDS; - } - } - - if (!jd) - jd = m_jd(dat); - else { - jd = m_jd(dat) + jd; - canonicalize_jd(nth, jd); - } - - if (f_zero_p(nth)) - nth = m_nth(dat); - else - nth = f_add(m_nth(dat), nth); - - if (!df && f_zero_p(sf) && !m_of(dat)) - return d_simple_new_internal(rb_obj_class(self), - nth, (int)jd, - m_sg(dat), - 0, 0, 0, - (dat->s.flags | HAVE_JD) & - ~(HAVE_CIVIL | HAVE_TIME | - COMPLEX_DAT)); - else - return d_complex_new_internal(rb_obj_class(self), - nth, (int)jd, - df, sf, - m_of(dat), m_sg(dat), - 0, 0, 0, - 0, 0, 0, - (dat->c.flags | - HAVE_JD | HAVE_DF) & - ~(HAVE_CIVIL | HAVE_TIME)); - } - break; - default: - expect_numeric(other); - other = f_to_r(other); - if (!k_rational_p(other)) { - if (!try_rational) Check_Type(other, T_RATIONAL); - try_rational = 0; - goto again; - } - /* fall through */ - case T_RATIONAL: - { - VALUE nth, sf, t; - int jd, df, s; - - if (wholenum_p(other)) { - other = rb_rational_num(other); - goto again; - } - - if (f_positive_p(other)) - s = +1; - else { - s = -1; - other = f_negate(other); - } - - nth = f_idiv(other, INT2FIX(CM_PERIOD)); - t = f_mod(other, INT2FIX(CM_PERIOD)); - - jd = FIX2INT(f_idiv(t, INT2FIX(1))); - t = f_mod(t, INT2FIX(1)); - - t = f_mul(t, INT2FIX(DAY_IN_SECONDS)); - df = FIX2INT(f_idiv(t, INT2FIX(1))); - t = f_mod(t, INT2FIX(1)); - - sf = f_mul(t, INT2FIX(SECOND_IN_NANOSECONDS)); - - if (s < 0) { - nth = f_negate(nth); - jd = -jd; - df = -df; - sf = f_negate(sf); - } - - if (f_zero_p(sf)) - sf = m_sf(dat); - else { - sf = f_add(m_sf(dat), sf); - if (f_lt_p(sf, INT2FIX(0))) { - df -= 1; - sf = f_add(sf, INT2FIX(SECOND_IN_NANOSECONDS)); - } - else if (f_ge_p(sf, INT2FIX(SECOND_IN_NANOSECONDS))) { - df += 1; - sf = f_sub(sf, INT2FIX(SECOND_IN_NANOSECONDS)); - } - } - - if (!df) - df = m_df(dat); - else { - df = m_df(dat) + df; - if (df < 0) { - jd -= 1; - df += DAY_IN_SECONDS; - } - else if (df >= DAY_IN_SECONDS) { - jd += 1; - df -= DAY_IN_SECONDS; - } - } - - if (!jd) - jd = m_jd(dat); - else { - jd = m_jd(dat) + jd; - canonicalize_jd(nth, jd); - } - - if (f_zero_p(nth)) - nth = m_nth(dat); - else - nth = f_add(m_nth(dat), nth); - - if (!df && f_zero_p(sf) && !m_of(dat)) - return d_simple_new_internal(rb_obj_class(self), - nth, jd, - m_sg(dat), - 0, 0, 0, - (dat->s.flags | HAVE_JD) & - ~(HAVE_CIVIL | HAVE_TIME | - COMPLEX_DAT)); - else - return d_complex_new_internal(rb_obj_class(self), - nth, jd, - df, sf, - m_of(dat), m_sg(dat), - 0, 0, 0, - 0, 0, 0, - (dat->c.flags | - HAVE_JD | HAVE_DF) & - ~(HAVE_CIVIL | HAVE_TIME)); - } - break; - } -} - -static VALUE -minus_dd(VALUE self, VALUE other) -{ - get_d2(self, other); - - { - int d, df; - VALUE n, sf, r; - - n = f_sub(m_nth(adat), m_nth(bdat)); - d = m_jd(adat) - m_jd(bdat); - df = m_df(adat) - m_df(bdat); - sf = f_sub(m_sf(adat), m_sf(bdat)); - canonicalize_jd(n, d); - - if (df < 0) { - d -= 1; - df += DAY_IN_SECONDS; - } - else if (df >= DAY_IN_SECONDS) { - d += 1; - df -= DAY_IN_SECONDS; - } - - if (f_lt_p(sf, INT2FIX(0))) { - df -= 1; - sf = f_add(sf, INT2FIX(SECOND_IN_NANOSECONDS)); - } - else if (f_ge_p(sf, INT2FIX(SECOND_IN_NANOSECONDS))) { - df += 1; - sf = f_sub(sf, INT2FIX(SECOND_IN_NANOSECONDS)); - } - - if (f_zero_p(n)) - r = INT2FIX(0); - else - r = f_mul(n, INT2FIX(CM_PERIOD)); - - if (d) - r = f_add(r, rb_rational_new1(INT2FIX(d))); - if (df) - r = f_add(r, isec_to_day(df)); - if (f_nonzero_p(sf)) - r = f_add(r, ns_to_day(sf)); - - if (RB_TYPE_P(r, T_RATIONAL)) - return r; - return rb_rational_new1(r); - } -} - -/* - * call-seq: - * d - other -> date or rational - * - * If the other is a date object, returns a Rational - * whose value is the difference between the two dates in days. - * If the other is a numeric value, returns a date object - * pointing +other+ days before self. - * If the other is a fractional number, - * assumes its precision is at most nanosecond. - * - * Date.new(2001,2,3) - 1 #=> # - * DateTime.new(2001,2,3) - Rational(1,2) - * #=> # - * Date.new(2001,2,3) - Date.new(2001) - * #=> (33/1) - * DateTime.new(2001,2,3) - DateTime.new(2001,2,2,12) - * #=> (1/2) - */ -static VALUE -d_lite_minus(VALUE self, VALUE other) -{ - if (k_date_p(other)) - return minus_dd(self, other); - - switch (TYPE(other)) { - case T_FIXNUM: - return d_lite_plus(self, LONG2NUM(-FIX2LONG(other))); - case T_FLOAT: - return d_lite_plus(self, DBL2NUM(-RFLOAT_VALUE(other))); - default: - expect_numeric(other); - /* fall through */ - case T_BIGNUM: - case T_RATIONAL: - return d_lite_plus(self, f_negate(other)); - } -} - -/* - * call-seq: - * next_day(n = 1) -> new_date - * - * Equivalent to Date#+ with argument +n+. - */ -static VALUE -d_lite_next_day(int argc, VALUE *argv, VALUE self) -{ - VALUE n; - - rb_scan_args(argc, argv, "01", &n); - if (argc < 1) - n = INT2FIX(1); - return d_lite_plus(self, n); -} - -/* - * call-seq: - * prev_day(n = 1) -> new_date - * - * Equivalent to Date#- with argument +n+. - */ -static VALUE -d_lite_prev_day(int argc, VALUE *argv, VALUE self) -{ - VALUE n; - - rb_scan_args(argc, argv, "01", &n); - if (argc < 1) - n = INT2FIX(1); - return d_lite_minus(self, n); -} - -/* - * call-seq: - * d.next -> new_date - * - * Returns a new \Date object representing the following day: - * - * d = Date.new(2001, 2, 3) - * d.to_s # => "2001-02-03" - * d.next.to_s # => "2001-02-04" - * - */ -static VALUE -d_lite_next(VALUE self) -{ - return d_lite_next_day(0, (VALUE *)NULL, self); -} - -/* - * call-seq: - * d >> n -> new_date - * - * Returns a new \Date object representing the date - * +n+ months later; +n+ should be a numeric: - * - * (Date.new(2001, 2, 3) >> 1).to_s # => "2001-03-03" - * (Date.new(2001, 2, 3) >> -2).to_s # => "2000-12-03" - * - * When the same day does not exist for the new month, - * the last day of that month is used instead: - * - * (Date.new(2001, 1, 31) >> 1).to_s # => "2001-02-28" - * (Date.new(2001, 1, 31) >> -4).to_s # => "2000-09-30" - * - * This results in the following, possibly unexpected, behaviors: - * - * d0 = Date.new(2001, 1, 31) - * d1 = d0 >> 1 # => # - * d2 = d1 >> 1 # => # - * - * d0 = Date.new(2001, 1, 31) - * d1 = d0 >> 1 # => # - * d2 = d1 >> -1 # => # - * - */ -static VALUE -d_lite_rshift(VALUE self, VALUE other) -{ - VALUE t, y, nth, rjd2; - int m, d, rjd; - double sg; - - get_d1(self); - t = f_add3(f_mul(m_real_year(dat), INT2FIX(12)), - INT2FIX(m_mon(dat) - 1), - other); - if (FIXNUM_P(t)) { - long it = FIX2LONG(t); - y = LONG2NUM(DIV(it, 12)); - it = MOD(it, 12); - m = (int)it + 1; - } - else { - y = f_idiv(t, INT2FIX(12)); - t = f_mod(t, INT2FIX(12)); - m = FIX2INT(t) + 1; - } - d = m_mday(dat); - sg = m_sg(dat); - - while (1) { - int ry, rm, rd, ns; - - if (valid_civil_p(y, m, d, sg, - &nth, &ry, - &rm, &rd, &rjd, &ns)) - break; - if (--d < 1) - rb_raise(eDateError, "invalid date"); - } - encode_jd(nth, rjd, &rjd2); - return d_lite_plus(self, f_sub(rjd2, m_real_local_jd(dat))); -} - -/* - * call-seq: - * d << n -> date - * - * Returns a new \Date object representing the date - * +n+ months earlier; +n+ should be a numeric: - * - * (Date.new(2001, 2, 3) << 1).to_s # => "2001-01-03" - * (Date.new(2001, 2, 3) << -2).to_s # => "2001-04-03" - * - * When the same day does not exist for the new month, - * the last day of that month is used instead: - * - * (Date.new(2001, 3, 31) << 1).to_s # => "2001-02-28" - * (Date.new(2001, 3, 31) << -6).to_s # => "2001-09-30" - * - * This results in the following, possibly unexpected, behaviors: - * - * d0 = Date.new(2001, 3, 31) - * d0 << 2 # => # - * d0 << 1 << 1 # => # - * - * d0 = Date.new(2001, 3, 31) - * d1 = d0 << 1 # => # - * d2 = d1 << -1 # => # - * - */ -static VALUE -d_lite_lshift(VALUE self, VALUE other) -{ - expect_numeric(other); - return d_lite_rshift(self, f_negate(other)); -} - -/* - * call-seq: - * next_month(n = 1) -> new_date - * - * Equivalent to #>> with argument +n+. - */ -static VALUE -d_lite_next_month(int argc, VALUE *argv, VALUE self) -{ - VALUE n; - - rb_scan_args(argc, argv, "01", &n); - if (argc < 1) - n = INT2FIX(1); - return d_lite_rshift(self, n); -} - -/* - * call-seq: - * prev_month(n = 1) -> new_date - * - * Equivalent to #<< with argument +n+. - */ -static VALUE -d_lite_prev_month(int argc, VALUE *argv, VALUE self) -{ - VALUE n; - - rb_scan_args(argc, argv, "01", &n); - if (argc < 1) - n = INT2FIX(1); - return d_lite_lshift(self, n); -} - -/* - * call-seq: - * next_year(n = 1) -> new_date - * - * Equivalent to #>> with argument n * 12. - */ -static VALUE -d_lite_next_year(int argc, VALUE *argv, VALUE self) -{ - VALUE n; - - rb_scan_args(argc, argv, "01", &n); - if (argc < 1) - n = INT2FIX(1); - return d_lite_rshift(self, f_mul(n, INT2FIX(12))); -} - -/* - * call-seq: - * prev_year(n = 1) -> new_date - * - * Equivalent to #<< with argument n * 12. - */ -static VALUE -d_lite_prev_year(int argc, VALUE *argv, VALUE self) -{ - VALUE n; - - rb_scan_args(argc, argv, "01", &n); - if (argc < 1) - n = INT2FIX(1); - return d_lite_lshift(self, f_mul(n, INT2FIX(12))); -} - -static VALUE d_lite_cmp(VALUE, VALUE); - -/* - * call-seq: - * step(limit, step = 1){|date| ... } -> self - * - * Calls the block with specified dates; - * returns +self+. - * - * - The first +date+ is +self+. - * - Each successive +date+ is date + step, - * where +step+ is the numeric step size in days. - * - The last date is the last one that is before or equal to +limit+, - * which should be a \Date object. - * - * Example: - * - * limit = Date.new(2001, 12, 31) - * Date.new(2001).step(limit){|date| p date.to_s if date.mday == 31 } - * - * Output: - * - * "2001-01-31" - * "2001-03-31" - * "2001-05-31" - * "2001-07-31" - * "2001-08-31" - * "2001-10-31" - * "2001-12-31" - * - * Returns an Enumerator if no block is given. - */ -static VALUE -d_lite_step(int argc, VALUE *argv, VALUE self) -{ - VALUE limit, step, date; - int c; - - rb_scan_args(argc, argv, "11", &limit, &step); - - if (argc < 2) - step = INT2FIX(1); - -#if 0 - if (f_zero_p(step)) - rb_raise(rb_eArgError, "step can't be 0"); -#endif - - RETURN_ENUMERATOR(self, argc, argv); - - date = self; - c = f_cmp(step, INT2FIX(0)); - if (c < 0) { - while (FIX2INT(d_lite_cmp(date, limit)) >= 0) { - rb_yield(date); - date = d_lite_plus(date, step); - } - } - else if (c == 0) { - while (1) - rb_yield(date); - } - else /* if (c > 0) */ { - while (FIX2INT(d_lite_cmp(date, limit)) <= 0) { - rb_yield(date); - date = d_lite_plus(date, step); - } - } - return self; -} - -/* - * call-seq: - * upto(max){|date| ... } -> self - * - * Equivalent to #step with arguments +max+ and +1+. - */ -static VALUE -d_lite_upto(VALUE self, VALUE max) -{ - VALUE date; - - RETURN_ENUMERATOR(self, 1, &max); - - date = self; - while (FIX2INT(d_lite_cmp(date, max)) <= 0) { - rb_yield(date); - date = d_lite_plus(date, INT2FIX(1)); - } - return self; -} - -/* - * call-seq: - * downto(min){|date| ... } -> self - * - * Equivalent to #step with arguments +min+ and -1. - */ -static VALUE -d_lite_downto(VALUE self, VALUE min) -{ - VALUE date; - - RETURN_ENUMERATOR(self, 1, &min); - - date = self; - while (FIX2INT(d_lite_cmp(date, min)) >= 0) { - rb_yield(date); - date = d_lite_plus(date, INT2FIX(-1)); - } - return self; -} - -static VALUE -cmp_gen(VALUE self, VALUE other) -{ - get_d1(self); - - if (k_numeric_p(other)) - return INT2FIX(f_cmp(m_ajd(dat), other)); - else if (k_date_p(other)) - return INT2FIX(f_cmp(m_ajd(dat), f_ajd(other))); - return rb_num_coerce_cmp(self, other, id_cmp); -} - -static VALUE -cmp_dd(VALUE self, VALUE other) -{ - get_d2(self, other); - - { - VALUE a_nth, b_nth, - a_sf, b_sf; - int a_jd, b_jd, - a_df, b_df; - - m_canonicalize_jd(self, adat); - m_canonicalize_jd(other, bdat); - a_nth = m_nth(adat); - b_nth = m_nth(bdat); - if (f_eqeq_p(a_nth, b_nth)) { - a_jd = m_jd(adat); - b_jd = m_jd(bdat); - if (a_jd == b_jd) { - a_df = m_df(adat); - b_df = m_df(bdat); - if (a_df == b_df) { - a_sf = m_sf(adat); - b_sf = m_sf(bdat); - if (f_eqeq_p(a_sf, b_sf)) { - return INT2FIX(0); - } - else if (f_lt_p(a_sf, b_sf)) { - return INT2FIX(-1); - } - else { - return INT2FIX(1); - } - } - else if (a_df < b_df) { - return INT2FIX(-1); - } - else { - return INT2FIX(1); - } - } - else if (a_jd < b_jd) { - return INT2FIX(-1); - } - else { - return INT2FIX(1); - } - } - else if (f_lt_p(a_nth, b_nth)) { - return INT2FIX(-1); - } - else { - return INT2FIX(1); - } - } -} - -/* - * call-seq: - * self <=> other -> -1, 0, 1 or nil - * - * Compares +self+ and +other+, returning: - * - * - -1 if +other+ is larger. - * - 0 if the two are equal. - * - 1 if +other+ is smaller. - * - +nil+ if the two are incomparable. - * - * Argument +other+ may be: - * - * - Another \Date object: - * - * d = Date.new(2022, 7, 27) # => # - * prev_date = d.prev_day # => # - * next_date = d.next_day # => # - * d <=> next_date # => -1 - * d <=> d # => 0 - * d <=> prev_date # => 1 - * - * - A DateTime object: - * - * d <=> DateTime.new(2022, 7, 26) # => 1 - * d <=> DateTime.new(2022, 7, 27) # => 0 - * d <=> DateTime.new(2022, 7, 28) # => -1 - * - * - A numeric (compares self.ajd to +other+): - * - * d <=> 2459788 # => -1 - * d <=> 2459787 # => 1 - * d <=> 2459786 # => 1 - * d <=> d.ajd # => 0 - * - * - Any other object: - * - * d <=> Object.new # => nil - * - */ -static VALUE -d_lite_cmp(VALUE self, VALUE other) -{ - if (!k_date_p(other)) - return cmp_gen(self, other); - - { - get_d2(self, other); - - if (!(simple_dat_p(adat) && simple_dat_p(bdat) && - m_gregorian_p(adat) == m_gregorian_p(bdat))) - return cmp_dd(self, other); - - { - VALUE a_nth, b_nth; - int a_jd, b_jd; - - m_canonicalize_jd(self, adat); - m_canonicalize_jd(other, bdat); - a_nth = m_nth(adat); - b_nth = m_nth(bdat); - if (f_eqeq_p(a_nth, b_nth)) { - a_jd = m_jd(adat); - b_jd = m_jd(bdat); - if (a_jd == b_jd) { - return INT2FIX(0); - } - else if (a_jd < b_jd) { - return INT2FIX(-1); - } - else { - return INT2FIX(1); - } - } - else if (f_lt_p(a_nth, b_nth)) { - return INT2FIX(-1); - } - else { - return INT2FIX(1); - } - } - } -} - -static VALUE -equal_gen(VALUE self, VALUE other) -{ - get_d1(self); - - if (k_numeric_p(other)) - return f_eqeq_p(m_real_local_jd(dat), other); - else if (k_date_p(other)) - return f_eqeq_p(m_real_local_jd(dat), f_jd(other)); - return rb_num_coerce_cmp(self, other, id_eqeq_p); -} - -/* - * call-seq: - * self === other -> true, false, or nil. - * - * Returns +true+ if +self+ and +other+ represent the same date, - * +false+ if not, +nil+ if the two are not comparable. - * - * Argument +other+ may be: - * - * - Another \Date object: - * - * d = Date.new(2022, 7, 27) # => # - * prev_date = d.prev_day # => # - * next_date = d.next_day # => # - * d === prev_date # => false - * d === d # => true - * d === next_date # => false - * - * - A DateTime object: - * - * d === DateTime.new(2022, 7, 26) # => false - * d === DateTime.new(2022, 7, 27) # => true - * d === DateTime.new(2022, 7, 28) # => false - * - * - A numeric (compares self.jd to +other+): - * - * d === 2459788 # => true - * d === 2459787 # => false - * d === 2459786 # => false - * d === d.jd # => true - * - * - An object not comparable: - * - * d === Object.new # => nil - * - */ -static VALUE -d_lite_equal(VALUE self, VALUE other) -{ - if (!k_date_p(other)) - return equal_gen(self, other); - - { - get_d2(self, other); - - if (!(m_gregorian_p(adat) == m_gregorian_p(bdat))) - return equal_gen(self, other); - - { - VALUE a_nth, b_nth; - int a_jd, b_jd; - - m_canonicalize_jd(self, adat); - m_canonicalize_jd(other, bdat); - a_nth = m_nth(adat); - b_nth = m_nth(bdat); - a_jd = m_local_jd(adat); - b_jd = m_local_jd(bdat); - if (f_eqeq_p(a_nth, b_nth) && - a_jd == b_jd) - return Qtrue; - return Qfalse; - } - } -} - -/* :nodoc: */ -static VALUE -d_lite_eql_p(VALUE self, VALUE other) -{ - if (!k_date_p(other)) - return Qfalse; - return f_zero_p(d_lite_cmp(self, other)); -} - -/* :nodoc: */ -static VALUE -d_lite_hash(VALUE self) -{ - st_index_t v, h[5]; - VALUE nth; - - get_d1(self); - nth = m_nth(dat); - - if (FIXNUM_P(nth)) { - h[0] = 0; - h[1] = (st_index_t)nth; - } else { - h[0] = 1; - h[1] = (st_index_t)FIX2LONG(rb_hash(nth)); - } - - h[2] = m_jd(dat); - h[3] = m_df(dat); - h[4] = m_sf(dat); - - v = rb_memhash(h, sizeof(h)); - return ST2FIX(v); -} - -#include "date_tmx.h" -static void set_tmx(VALUE, struct tmx *); -static VALUE strftimev(const char *, VALUE, - void (*)(VALUE, struct tmx *)); - -/* - * call-seq: - * to_s -> string - * - * Returns a string representation of the date in +self+ - * in {ISO 8601 extended date format}[rdoc-ref:language/strftime_formatting.rdoc@ISO+8601+Format+Specifications] - * ('%Y-%m-%d'): - * - * Date.new(2001, 2, 3).to_s # => "2001-02-03" - * - */ -static VALUE -d_lite_to_s(VALUE self) -{ - return strftimev("%Y-%m-%d", self, set_tmx); -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -mk_inspect_raw(union DateData *x, VALUE klass) -{ - char flags[6]; - - flags[0] = (x->flags & COMPLEX_DAT) ? 'C' : 'S'; - flags[1] = (x->flags & HAVE_JD) ? 'j' : '-'; - flags[2] = (x->flags & HAVE_DF) ? 'd' : '-'; - flags[3] = (x->flags & HAVE_CIVIL) ? 'c' : '-'; - flags[4] = (x->flags & HAVE_TIME) ? 't' : '-'; - flags[5] = '\0'; - - if (simple_dat_p(x)) { - return rb_enc_sprintf(rb_usascii_encoding(), - "#<%"PRIsVALUE": " - "(%+"PRIsVALUE"th,%dj),+0s,%.0fj; " - "%dy%dm%dd; %s>", - klass, - x->s.nth, x->s.jd, x->s.sg, -#ifndef USE_PACK - x->s.year, x->s.mon, x->s.mday, -#else - x->s.year, - EX_MON(x->s.pc), EX_MDAY(x->s.pc), -#endif - flags); - } - else { - return rb_enc_sprintf(rb_usascii_encoding(), - "#<%"PRIsVALUE": " - "(%+"PRIsVALUE"th,%dj,%ds,%+"PRIsVALUE"n)," - "%+ds,%.0fj; " - "%dy%dm%dd %dh%dm%ds; %s>", - klass, - x->c.nth, x->c.jd, x->c.df, x->c.sf, - x->c.of, x->c.sg, -#ifndef USE_PACK - x->c.year, x->c.mon, x->c.mday, - x->c.hour, x->c.min, x->c.sec, -#else - x->c.year, - EX_MON(x->c.pc), EX_MDAY(x->c.pc), - EX_HOUR(x->c.pc), EX_MIN(x->c.pc), - EX_SEC(x->c.pc), -#endif - flags); - } -} - -/* :nodoc: */ -static VALUE -d_lite_inspect_raw(VALUE self) -{ - get_d1(self); - return mk_inspect_raw(dat, rb_obj_class(self)); -} -#endif - -static VALUE -mk_inspect(union DateData *x, VALUE klass, VALUE to_s) -{ - return rb_enc_sprintf(rb_usascii_encoding(), - "#<%"PRIsVALUE": %"PRIsVALUE" " - "((%+"PRIsVALUE"j,%ds,%+"PRIsVALUE"n),%+ds,%.0fj)>", - klass, to_s, - m_real_jd(x), m_df(x), m_sf(x), - m_of(x), m_sg(x)); -} - -/* - * call-seq: - * inspect -> string - * - * Returns a string representation of +self+: - * - * Date.new(2001, 2, 3).inspect - * # => "#" - * - */ -static VALUE -d_lite_inspect(VALUE self) -{ - get_d1(self); - return mk_inspect(dat, rb_obj_class(self), self); -} - -#include -#include "date_tmx.h" - -size_t date_strftime(char *s, size_t maxsize, const char *format, - const struct tmx *tmx); - -#define SMALLBUF 100 -static size_t -date_strftime_alloc(char **buf, const char *format, - struct tmx *tmx) -{ - size_t size, len, flen; - - (*buf)[0] = '\0'; - flen = strlen(format); - if (flen == 0) { - return 0; - } - errno = 0; - len = date_strftime(*buf, SMALLBUF, format, tmx); - if (len != 0 || (**buf == '\0' && errno != ERANGE)) return len; - for (size=1024; ; size*=2) { - *buf = xmalloc(size); - (*buf)[0] = '\0'; - len = date_strftime(*buf, size, format, tmx); - /* - * buflen can be zero EITHER because there's not enough - * room in the string, or because the control command - * goes to the empty string. Make a reasonable guess that - * if the buffer is 1024 times bigger than the length of the - * format string, it's not failing for lack of room. - */ - if (len > 0) break; - xfree(*buf); - if (size >= 1024 * flen) { - rb_sys_fail(format); - break; - } - } - return len; -} - -static VALUE -tmx_m_secs(union DateData *x) -{ - VALUE s; - int df; - - s = day_to_sec(f_sub(m_real_jd(x), - UNIX_EPOCH_IN_CJD)); - if (simple_dat_p(x)) - return s; - df = m_df(x); - if (df) - s = f_add(s, INT2FIX(df)); - return s; -} - -#define MILLISECOND_IN_NANOSECONDS 1000000 - -static VALUE -tmx_m_msecs(union DateData *x) -{ - VALUE s, sf; - - s = sec_to_ms(tmx_m_secs(x)); - if (simple_dat_p(x)) - return s; - sf = m_sf(x); - if (f_nonzero_p(sf)) - s = f_add(s, f_div(sf, INT2FIX(MILLISECOND_IN_NANOSECONDS))); - return s; -} - -static int -tmx_m_of(union DateData *x) -{ - return m_of(x); -} - -static char * -tmx_m_zone(union DateData *x) -{ - VALUE zone = m_zone(x); - /* TODO: fix potential dangling pointer */ - return RSTRING_PTR(zone); -} - -static const struct tmx_funcs tmx_funcs = { - (VALUE (*)(void *))m_real_year, - (int (*)(void *))m_yday, - (int (*)(void *))m_mon, - (int (*)(void *))m_mday, - (VALUE (*)(void *))m_real_cwyear, - (int (*)(void *))m_cweek, - (int (*)(void *))m_cwday, - (int (*)(void *))m_wnum0, - (int (*)(void *))m_wnum1, - (int (*)(void *))m_wday, - (int (*)(void *))m_hour, - (int (*)(void *))m_min, - (int (*)(void *))m_sec, - (VALUE (*)(void *))m_sf_in_sec, - (VALUE (*)(void *))tmx_m_secs, - (VALUE (*)(void *))tmx_m_msecs, - (int (*)(void *))tmx_m_of, - (char *(*)(void *))tmx_m_zone -}; - -static void -set_tmx(VALUE self, struct tmx *tmx) -{ - get_d1(self); - tmx->dat = (void *)dat; - tmx->funcs = &tmx_funcs; -} - -static VALUE -date_strftime_internal(int argc, VALUE *argv, VALUE self, - const char *default_fmt, - void (*func)(VALUE, struct tmx *)) -{ - VALUE vfmt; - const char *fmt; - long len; - char buffer[SMALLBUF], *buf = buffer; - struct tmx tmx; - VALUE str; - - rb_scan_args(argc, argv, "01", &vfmt); - - if (argc < 1) - vfmt = rb_usascii_str_new2(default_fmt); - else { - StringValue(vfmt); - if (!rb_enc_str_asciicompat_p(vfmt)) { - rb_raise(rb_eArgError, - "format should have ASCII compatible encoding"); - } - } - fmt = RSTRING_PTR(vfmt); - len = RSTRING_LEN(vfmt); - (*func)(self, &tmx); - if (memchr(fmt, '\0', len)) { - /* Ruby string may contain \0's. */ - const char *p = fmt, *pe = fmt + len; - - str = rb_str_new(0, 0); - while (p < pe) { - len = date_strftime_alloc(&buf, p, &tmx); - rb_str_cat(str, buf, len); - p += strlen(p); - if (buf != buffer) { - xfree(buf); - buf = buffer; - } - for (fmt = p; p < pe && !*p; ++p); - if (p > fmt) rb_str_cat(str, fmt, p - fmt); - } - rb_enc_copy(str, vfmt); - return str; - } - else - len = date_strftime_alloc(&buf, fmt, &tmx); - - str = rb_str_new(buf, len); - if (buf != buffer) xfree(buf); - rb_enc_copy(str, vfmt); - return str; -} - -/* - * call-seq: - * strftime(format = '%F') -> string - * - * Returns a string representation of the date in +self+, - * formatted according the given +format+: - * - * Date.new(2001, 2, 3).strftime # => "2001-02-03" - * - * For other formats, see - * {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]. - * - */ -static VALUE -d_lite_strftime(int argc, VALUE *argv, VALUE self) -{ - return date_strftime_internal(argc, argv, self, - "%Y-%m-%d", set_tmx); -} - -static VALUE -strftimev(const char *fmt, VALUE self, - void (*func)(VALUE, struct tmx *)) -{ - char buffer[SMALLBUF], *buf = buffer; - struct tmx tmx; - long len; - VALUE str; - - (*func)(self, &tmx); - len = date_strftime_alloc(&buf, fmt, &tmx); - RB_GC_GUARD(self); - str = rb_usascii_str_new(buf, len); - if (buf != buffer) xfree(buf); - return str; -} - -/* - * call-seq: - * asctime -> string - * - * Equivalent to #strftime with argument '%a %b %e %T %Y' - * (or its {shorthand form}[rdoc-ref:language/strftime_formatting.rdoc@Shorthand+Conversion+Specifiers] - * '%c'): - * - * Date.new(2001, 2, 3).asctime # => "Sat Feb 3 00:00:00 2001" - * - * See {asctime}[https://man7.org/linux/man-pages/man3/asctime.3p.html]. - * - */ -static VALUE -d_lite_asctime(VALUE self) -{ - return strftimev("%a %b %e %H:%M:%S %Y", self, set_tmx); -} - -/* - * call-seq: - * iso8601 -> string - * - * Equivalent to #strftime with argument '%Y-%m-%d' - * (or its {shorthand form}[rdoc-ref:language/strftime_formatting.rdoc@Shorthand+Conversion+Specifiers] - * '%F'); - * - * Date.new(2001, 2, 3).iso8601 # => "2001-02-03" - * - */ -static VALUE -d_lite_iso8601(VALUE self) -{ - return strftimev("%Y-%m-%d", self, set_tmx); -} - -/* - * call-seq: - * rfc3339 -> string - * - * Equivalent to #strftime with argument '%FT%T%:z'; - * see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: - * - * Date.new(2001, 2, 3).rfc3339 # => "2001-02-03T00:00:00+00:00" - * - */ -static VALUE -d_lite_rfc3339(VALUE self) -{ - return strftimev("%Y-%m-%dT%H:%M:%S%:z", self, set_tmx); -} - -/* - * call-seq: - * rfc2822 -> string - * - * Equivalent to #strftime with argument '%a, %-d %b %Y %T %z'; - * see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: - * - * Date.new(2001, 2, 3).rfc2822 # => "Sat, 3 Feb 2001 00:00:00 +0000" - * - */ -static VALUE -d_lite_rfc2822(VALUE self) -{ - return strftimev("%a, %-d %b %Y %T %z", self, set_tmx); -} - -/* - * call-seq: - * httpdate -> string - * - * Equivalent to #strftime with argument '%a, %d %b %Y %T GMT'; - * see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: - * - * Date.new(2001, 2, 3).httpdate # => "Sat, 03 Feb 2001 00:00:00 GMT" - * - */ -static VALUE -d_lite_httpdate(VALUE self) -{ - volatile VALUE dup = dup_obj_with_new_offset(self, 0); - return strftimev("%a, %d %b %Y %T GMT", dup, set_tmx); -} - -enum { - DECIMAL_SIZE_OF_LONG = DECIMAL_SIZE_OF_BITS(CHAR_BIT*sizeof(long)), - JISX0301_DATE_SIZE = DECIMAL_SIZE_OF_LONG+8 -}; - -static const char * -jisx0301_date_format(char *fmt, size_t size, VALUE jd, VALUE y) -{ - if (FIXNUM_P(jd)) { - long d = FIX2INT(jd); - long s; - char c; - if (d < 2405160) - return "%Y-%m-%d"; - if (d < 2419614) { - c = 'M'; - s = 1867; - } - else if (d < 2424875) { - c = 'T'; - s = 1911; - } - else if (d < 2447535) { - c = 'S'; - s = 1925; - } - else if (d < 2458605) { - c = 'H'; - s = 1988; - } - else { - c = 'R'; - s = 2018; - } - snprintf(fmt, size, "%c%02ld" ".%%m.%%d", c, FIX2INT(y) - s); - return fmt; - } - return "%Y-%m-%d"; -} - -/* - * call-seq: - * jisx0301 -> string - * - * Returns a string representation of the date in +self+ - * in JIS X 0301 format. - * - * Date.new(2001, 2, 3).jisx0301 # => "H13.02.03" - * - */ -static VALUE -d_lite_jisx0301(VALUE self) -{ - char fmtbuf[JISX0301_DATE_SIZE]; - const char *fmt; - - get_d1(self); - fmt = jisx0301_date_format(fmtbuf, sizeof(fmtbuf), - m_real_local_jd(dat), - m_real_year(dat)); - return strftimev(fmt, self, set_tmx); -} - -static VALUE -deconstruct_keys(VALUE self, VALUE keys, int is_datetime) -{ - VALUE h = rb_hash_new(); - long i; - - get_d1(self); - - if (NIL_P(keys)) { - rb_hash_aset(h, sym_year, m_real_year(dat)); - rb_hash_aset(h, sym_month, INT2FIX(m_mon(dat))); - rb_hash_aset(h, sym_day, INT2FIX(m_mday(dat))); - rb_hash_aset(h, sym_yday, INT2FIX(m_yday(dat))); - rb_hash_aset(h, sym_wday, INT2FIX(m_wday(dat))); - if (is_datetime) { - rb_hash_aset(h, sym_hour, INT2FIX(m_hour(dat))); - rb_hash_aset(h, sym_min, INT2FIX(m_min(dat))); - rb_hash_aset(h, sym_sec, INT2FIX(m_sec(dat))); - rb_hash_aset(h, sym_sec_fraction, m_sf_in_sec(dat)); - rb_hash_aset(h, sym_zone, m_zone(dat)); - } - - return h; - } - if (!RB_TYPE_P(keys, T_ARRAY)) { - rb_raise(rb_eTypeError, - "wrong argument type %"PRIsVALUE" (expected Array or nil)", - rb_obj_class(keys)); - - } - - for (i=0; i hash - * - * Returns a hash of the name/value pairs, to use in pattern matching. - * Possible keys are: :year, :month, :day, - * :wday, :yday. - * - * Possible usages: - * - * d = Date.new(2022, 10, 5) - * - * if d in wday: 3, day: ..7 # uses deconstruct_keys underneath - * puts "first Wednesday of the month" - * end - * #=> prints "first Wednesday of the month" - * - * case d - * in year: ...2022 - * puts "too old" - * in month: ..9 - * puts "quarter 1-3" - * in wday: 1..5, month: - * puts "working day in month #{month}" - * end - * #=> prints "working day in month 10" - * - * Note that deconstruction by pattern can also be combined with class check: - * - * if d in Date(wday: 3, day: ..7) - * puts "first Wednesday of the month" - * end - * - */ -static VALUE -d_lite_deconstruct_keys(VALUE self, VALUE keys) -{ - return deconstruct_keys(self, keys, /* is_datetime=false */ 0); -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -d_lite_marshal_dump_old(VALUE self) -{ - VALUE a; - - get_d1(self); - - a = rb_ary_new3(3, - m_ajd(dat), - m_of_in_day(dat), - DBL2NUM(m_sg(dat))); - - rb_copy_generic_ivar(a, self); - - return a; -} -#endif - -/* :nodoc: */ -static VALUE -d_lite_marshal_dump(VALUE self) -{ - VALUE a; - - get_d1(self); - - a = rb_ary_new3(6, - m_nth(dat), - INT2FIX(m_jd(dat)), - INT2FIX(m_df(dat)), - m_sf(dat), - INT2FIX(m_of(dat)), - DBL2NUM(m_sg(dat))); - - - rb_copy_generic_ivar(a, self); - - return a; -} - -/* :nodoc: */ -static VALUE -d_lite_marshal_load(VALUE self, VALUE a) -{ - VALUE nth, sf; - int jd, df, of; - double sg; - - get_d1(self); - - rb_check_frozen(self); - - if (!RB_TYPE_P(a, T_ARRAY)) - rb_raise(rb_eTypeError, "expected an array"); - - switch (RARRAY_LEN(a)) { - case 2: /* 1.6.x */ - case 3: /* 1.8.x, 1.9.2 */ - { - VALUE ajd, vof, vsg; - - if (RARRAY_LEN(a) == 2) { - ajd = f_sub(RARRAY_AREF(a, 0), half_days_in_day); - vof = INT2FIX(0); - vsg = RARRAY_AREF(a, 1); - if (!k_numeric_p(vsg)) - vsg = DBL2NUM(RTEST(vsg) ? GREGORIAN : JULIAN); - } - else { - ajd = RARRAY_AREF(a, 0); - vof = RARRAY_AREF(a, 1); - vsg = RARRAY_AREF(a, 2); - } - - old_to_new(ajd, vof, vsg, - &nth, &jd, &df, &sf, &of, &sg); - } - break; - case 6: - { - nth = RARRAY_AREF(a, 0); - jd = NUM2INT(RARRAY_AREF(a, 1)); - df = NUM2INT(RARRAY_AREF(a, 2)); - sf = RARRAY_AREF(a, 3); - of = NUM2INT(RARRAY_AREF(a, 4)); - sg = NUM2DBL(RARRAY_AREF(a, 5)); - } - break; - default: - rb_raise(rb_eTypeError, "invalid size"); - break; - } - - if (simple_dat_p(dat)) { - if (df || !f_zero_p(sf) || of) { - /* loading a fractional date; promote to complex */ - dat = ruby_xrealloc(dat, sizeof(struct ComplexDateData)); - RTYPEDDATA(self)->data = dat; - goto complex_data; - } - set_to_simple(self, &dat->s, nth, jd, sg, 0, 0, 0, HAVE_JD); - } else { - complex_data: - set_to_complex(self, &dat->c, nth, jd, df, sf, of, sg, - 0, 0, 0, 0, 0, 0, - HAVE_JD | HAVE_DF); - } - - rb_copy_generic_ivar(self, a); - - return self; -} - -/* :nodoc: */ -static VALUE -date_s__load(VALUE klass, VALUE s) -{ - VALUE a, obj; - - a = rb_marshal_load(s); - obj = d_lite_s_alloc(klass); - return d_lite_marshal_load(obj, a); -} - -/* datetime */ - -/* - * call-seq: - * DateTime.jd([jd=0[, hour=0[, minute=0[, second=0[, offset=0[, start=Date::ITALY]]]]]]) -> datetime - * - * Creates a DateTime object denoting the given chronological Julian - * day number. - * - * DateTime.jd(2451944) #=> # - * DateTime.jd(2451945) #=> # - * DateTime.jd(Rational('0.5')) - * #=> # - */ -static VALUE -datetime_s_jd(int argc, VALUE *argv, VALUE klass) -{ - VALUE vjd, vh, vmin, vs, vof, vsg, jd, fr, fr2, ret; - int h, min, s, rof; - double sg; - - rb_scan_args(argc, argv, "06", &vjd, &vh, &vmin, &vs, &vof, &vsg); - - jd = INT2FIX(0); - - h = min = s = 0; - fr2 = INT2FIX(0); - rof = 0; - sg = DEFAULT_SG; - - switch (argc) { - case 6: - val2sg(vsg, sg); - case 5: - val2off(vof, rof); - case 4: - check_numeric(vs, "second"); - num2int_with_frac(s, positive_inf); - case 3: - check_numeric(vmin, "minute"); - num2int_with_frac(min, 3); - case 2: - check_numeric(vh, "hour"); - num2int_with_frac(h, 2); - case 1: - check_numeric(vjd, "jd"); - num2num_with_frac(jd, 1); - } - - { - VALUE nth; - int rh, rmin, rs, rjd, rjd2; - - if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs)) - rb_raise(eDateError, "invalid date"); - canon24oc(); - - decode_jd(jd, &nth, &rjd); - rjd2 = jd_local_to_utc(rjd, - time_to_df(rh, rmin, rs), - rof); - - ret = d_complex_new_internal(klass, - nth, rjd2, - 0, INT2FIX(0), - rof, sg, - 0, 0, 0, - rh, rmin, rs, - HAVE_JD | HAVE_TIME); - } - add_frac(); - return ret; -} - -/* - * call-seq: - * DateTime.ordinal([year=-4712[, yday=1[, hour=0[, minute=0[, second=0[, offset=0[, start=Date::ITALY]]]]]]]) -> datetime - * - * Creates a DateTime object denoting the given ordinal date. - * - * DateTime.ordinal(2001,34) #=> # - * DateTime.ordinal(2001,34,4,5,6,'+7') - * #=> # - * DateTime.ordinal(2001,-332,-20,-55,-54,'+7') - * #=> # - */ -static VALUE -datetime_s_ordinal(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vd, vh, vmin, vs, vof, vsg, y, fr, fr2, ret; - int d, h, min, s, rof; - double sg; - - rb_scan_args(argc, argv, "07", &vy, &vd, &vh, &vmin, &vs, &vof, &vsg); - - y = INT2FIX(-4712); - d = 1; - - h = min = s = 0; - fr2 = INT2FIX(0); - rof = 0; - sg = DEFAULT_SG; - - switch (argc) { - case 7: - val2sg(vsg, sg); - case 6: - val2off(vof, rof); - case 5: - check_numeric(vs, "second"); - num2int_with_frac(s, positive_inf); - case 4: - check_numeric(vmin, "minute"); - num2int_with_frac(min, 4); - case 3: - check_numeric(vh, "hour"); - num2int_with_frac(h, 3); - case 2: - check_numeric(vd, "yday"); - num2int_with_frac(d, 2); - case 1: - check_numeric(vy, "year"); - y = vy; - } - - { - VALUE nth; - int ry, rd, rh, rmin, rs, rjd, rjd2, ns; - - if (!valid_ordinal_p(y, d, sg, - &nth, &ry, - &rd, &rjd, - &ns)) - rb_raise(eDateError, "invalid date"); - if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs)) - rb_raise(eDateError, "invalid date"); - canon24oc(); - - rjd2 = jd_local_to_utc(rjd, - time_to_df(rh, rmin, rs), - rof); - - ret = d_complex_new_internal(klass, - nth, rjd2, - 0, INT2FIX(0), - rof, sg, - 0, 0, 0, - rh, rmin, rs, - HAVE_JD | HAVE_TIME); - } - add_frac(); - return ret; -} - -/* - * Same as DateTime.new. - */ -static VALUE -datetime_s_civil(int argc, VALUE *argv, VALUE klass) -{ - return datetime_initialize(argc, argv, d_lite_s_alloc_complex(klass)); -} - -static VALUE -datetime_initialize(int argc, VALUE *argv, VALUE self) -{ - VALUE vy, vm, vd, vh, vmin, vs, vof, vsg, y, fr, fr2, ret; - int m, d, h, min, s, rof; - double sg; - struct ComplexDateData *dat = rb_check_typeddata(self, &d_lite_type); - - if (!complex_dat_p(dat)) { - rb_raise(rb_eTypeError, "DateTime expected"); - } - - rb_scan_args(argc, argv, "08", &vy, &vm, &vd, &vh, &vmin, &vs, &vof, &vsg); - - y = INT2FIX(-4712); - m = 1; - d = 1; - - h = min = s = 0; - fr2 = INT2FIX(0); - rof = 0; - sg = DEFAULT_SG; - - switch (argc) { - case 8: - val2sg(vsg, sg); - case 7: - val2off(vof, rof); - case 6: - check_numeric(vs, "second"); - num2int_with_frac(s, positive_inf); - case 5: - check_numeric(vmin, "minute"); - num2int_with_frac(min, 5); - case 4: - check_numeric(vh, "hour"); - num2int_with_frac(h, 4); - case 3: - check_numeric(vd, "day"); - num2int_with_frac(d, 3); - case 2: - check_numeric(vm, "month"); - m = NUM2INT(vm); - case 1: - check_numeric(vy, "year"); - y = vy; - } - - if (guess_style(y, sg) < 0) { - VALUE nth; - int ry, rm, rd, rh, rmin, rs; - - if (!valid_gregorian_p(y, m, d, - &nth, &ry, - &rm, &rd)) - rb_raise(eDateError, "invalid date"); - if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs)) - rb_raise(eDateError, "invalid date"); - canon24oc(); - - set_to_complex(self, dat, - nth, 0, - 0, INT2FIX(0), - rof, sg, - ry, rm, rd, - rh, rmin, rs, - HAVE_CIVIL | HAVE_TIME); - } - else { - VALUE nth; - int ry, rm, rd, rh, rmin, rs, rjd, rjd2, ns; - - if (!valid_civil_p(y, m, d, sg, - &nth, &ry, - &rm, &rd, &rjd, - &ns)) - rb_raise(eDateError, "invalid date"); - if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs)) - rb_raise(eDateError, "invalid date"); - canon24oc(); - - rjd2 = jd_local_to_utc(rjd, - time_to_df(rh, rmin, rs), - rof); - - set_to_complex(self, dat, - nth, rjd2, - 0, INT2FIX(0), - rof, sg, - ry, rm, rd, - rh, rmin, rs, - HAVE_JD | HAVE_CIVIL | HAVE_TIME); - } - ret = self; - add_frac(); - return ret; -} - -/* - * call-seq: - * DateTime.commercial([cwyear=-4712[, cweek=1[, cwday=1[, hour=0[, minute=0[, second=0[, offset=0[, start=Date::ITALY]]]]]]]]) -> datetime - * - * Creates a DateTime object denoting the given week date. - * - * DateTime.commercial(2001) #=> # - * DateTime.commercial(2002) #=> # - * DateTime.commercial(2001,5,6,4,5,6,'+7') - * #=> # - */ -static VALUE -datetime_s_commercial(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vw, vd, vh, vmin, vs, vof, vsg, y, fr, fr2, ret; - int w, d, h, min, s, rof; - double sg; - - rb_scan_args(argc, argv, "08", &vy, &vw, &vd, &vh, &vmin, &vs, &vof, &vsg); - - y = INT2FIX(-4712); - w = 1; - d = 1; - - h = min = s = 0; - fr2 = INT2FIX(0); - rof = 0; - sg = DEFAULT_SG; - - switch (argc) { - case 8: - val2sg(vsg, sg); - case 7: - val2off(vof, rof); - case 6: - check_numeric(vs, "second"); - num2int_with_frac(s, positive_inf); - case 5: - check_numeric(vmin, "minute"); - num2int_with_frac(min, 5); - case 4: - check_numeric(vh, "hour"); - num2int_with_frac(h, 4); - case 3: - check_numeric(vd, "cwday"); - num2int_with_frac(d, 3); - case 2: - check_numeric(vw, "cweek"); - w = NUM2INT(vw); - case 1: - check_numeric(vy, "year"); - y = vy; - } - - { - VALUE nth; - int ry, rw, rd, rh, rmin, rs, rjd, rjd2, ns; - - if (!valid_commercial_p(y, w, d, sg, - &nth, &ry, - &rw, &rd, &rjd, - &ns)) - rb_raise(eDateError, "invalid date"); - if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs)) - rb_raise(eDateError, "invalid date"); - canon24oc(); - - rjd2 = jd_local_to_utc(rjd, - time_to_df(rh, rmin, rs), - rof); - - ret = d_complex_new_internal(klass, - nth, rjd2, - 0, INT2FIX(0), - rof, sg, - 0, 0, 0, - rh, rmin, rs, - HAVE_JD | HAVE_TIME); - } - add_frac(); - return ret; -} - -#ifndef NDEBUG -/* :nodoc: */ -static VALUE -datetime_s_weeknum(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vw, vd, vf, vh, vmin, vs, vof, vsg, y, fr, fr2, ret; - int w, d, f, h, min, s, rof; - double sg; - - rb_scan_args(argc, argv, "09", &vy, &vw, &vd, &vf, - &vh, &vmin, &vs, &vof, &vsg); - - y = INT2FIX(-4712); - w = 0; - d = 1; - f = 0; - - h = min = s = 0; - fr2 = INT2FIX(0); - rof = 0; - sg = DEFAULT_SG; - - switch (argc) { - case 9: - val2sg(vsg, sg); - case 8: - val2off(vof, rof); - case 7: - num2int_with_frac(s, positive_inf); - case 6: - num2int_with_frac(min, 6); - case 5: - num2int_with_frac(h, 5); - case 4: - f = NUM2INT(vf); - case 3: - num2int_with_frac(d, 4); - case 2: - w = NUM2INT(vw); - case 1: - y = vy; - } - - { - VALUE nth; - int ry, rw, rd, rh, rmin, rs, rjd, rjd2, ns; - - if (!valid_weeknum_p(y, w, d, f, sg, - &nth, &ry, - &rw, &rd, &rjd, - &ns)) - rb_raise(eDateError, "invalid date"); - if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs)) - rb_raise(eDateError, "invalid date"); - canon24oc(); - - rjd2 = jd_local_to_utc(rjd, - time_to_df(rh, rmin, rs), - rof); - ret = d_complex_new_internal(klass, - nth, rjd2, - 0, INT2FIX(0), - rof, sg, - 0, 0, 0, - rh, rmin, rs, - HAVE_JD | HAVE_TIME); - } - add_frac(); - return ret; -} - -/* :nodoc: */ -static VALUE -datetime_s_nth_kday(int argc, VALUE *argv, VALUE klass) -{ - VALUE vy, vm, vn, vk, vh, vmin, vs, vof, vsg, y, fr, fr2, ret; - int m, n, k, h, min, s, rof; - double sg; - - rb_scan_args(argc, argv, "09", &vy, &vm, &vn, &vk, - &vh, &vmin, &vs, &vof, &vsg); - - y = INT2FIX(-4712); - m = 1; - n = 1; - k = 1; - - h = min = s = 0; - fr2 = INT2FIX(0); - rof = 0; - sg = DEFAULT_SG; - - switch (argc) { - case 9: - val2sg(vsg, sg); - case 8: - val2off(vof, rof); - case 7: - num2int_with_frac(s, positive_inf); - case 6: - num2int_with_frac(min, 6); - case 5: - num2int_with_frac(h, 5); - case 4: - num2int_with_frac(k, 4); - case 3: - n = NUM2INT(vn); - case 2: - m = NUM2INT(vm); - case 1: - y = vy; - } - - { - VALUE nth; - int ry, rm, rn, rk, rh, rmin, rs, rjd, rjd2, ns; - - if (!valid_nth_kday_p(y, m, n, k, sg, - &nth, &ry, - &rm, &rn, &rk, &rjd, - &ns)) - rb_raise(eDateError, "invalid date"); - if (!c_valid_time_p(h, min, s, &rh, &rmin, &rs)) - rb_raise(eDateError, "invalid date"); - canon24oc(); - - rjd2 = jd_local_to_utc(rjd, - time_to_df(rh, rmin, rs), - rof); - ret = d_complex_new_internal(klass, - nth, rjd2, - 0, INT2FIX(0), - rof, sg, - 0, 0, 0, - rh, rmin, rs, - HAVE_JD | HAVE_TIME); - } - add_frac(); - return ret; -} -#endif - -/* - * call-seq: - * DateTime.now([start=Date::ITALY]) -> datetime - * - * Creates a DateTime object denoting the present time. - * - * DateTime.now #=> # - */ -static VALUE -datetime_s_now(int argc, VALUE *argv, VALUE klass) -{ - VALUE vsg, nth, ret; - double sg; -#ifdef HAVE_CLOCK_GETTIME - struct timespec ts; -#else - struct timeval tv; -#endif - time_t sec; - struct tm tm; - long sf, of; - int y, ry, m, d, h, min, s; - - rb_scan_args(argc, argv, "01", &vsg); - - if (argc < 1) - sg = DEFAULT_SG; - else - sg = NUM2DBL(vsg); - -#ifdef HAVE_CLOCK_GETTIME - if (clock_gettime(CLOCK_REALTIME, &ts) == -1) - rb_sys_fail("clock_gettime"); - sec = ts.tv_sec; -#else - if (gettimeofday(&tv, NULL) == -1) - rb_sys_fail("gettimeofday"); - sec = tv.tv_sec; -#endif - tzset(); - if (!localtime_r(&sec, &tm)) - rb_sys_fail("localtime"); - - y = tm.tm_year + 1900; - m = tm.tm_mon + 1; - d = tm.tm_mday; - h = tm.tm_hour; - min = tm.tm_min; - s = tm.tm_sec; - if (s == 60) - s = 59; -#ifdef HAVE_STRUCT_TM_TM_GMTOFF - of = tm.tm_gmtoff; -#elif defined(HAVE_TIMEZONE) -#if defined(HAVE_ALTZONE) && !defined(_AIX) - of = (long)-((tm.tm_isdst > 0) ? altzone : timezone); -#else - of = (long)-timezone; - if (tm.tm_isdst) { - time_t sec2; - - tm.tm_isdst = 0; - sec2 = mktime(&tm); - of += (long)difftime(sec2, sec); - } -#endif -#elif defined(HAVE_TIMEGM) - { - time_t sec2; - - sec2 = timegm(&tm); - of = (long)difftime(sec2, sec); - } -#else - { - struct tm tm2; - time_t sec2; - - if (!gmtime_r(&sec, &tm2)) - rb_sys_fail("gmtime"); - tm2.tm_isdst = tm.tm_isdst; - sec2 = mktime(&tm2); - of = (long)difftime(sec, sec2); - } -#endif -#ifdef HAVE_CLOCK_GETTIME - sf = ts.tv_nsec; -#else - sf = tv.tv_usec * 1000; -#endif - - if (of < -DAY_IN_SECONDS || of > DAY_IN_SECONDS) { - of = 0; - rb_warning("invalid offset is ignored"); - } - - decode_year(INT2FIX(y), -1, &nth, &ry); - - ret = d_complex_new_internal(klass, - nth, 0, - 0, LONG2NUM(sf), - (int)of, GREGORIAN, - ry, m, d, - h, min, s, - HAVE_CIVIL | HAVE_TIME); - { - get_d1(ret); - set_sg(dat, sg); - } - return ret; -} - -static VALUE -dt_new_by_frags(VALUE klass, VALUE hash, VALUE sg) -{ - VALUE jd, sf, t; - int df, of; - - if (!c_valid_start_p(NUM2DBL(sg))) { - sg = INT2FIX(DEFAULT_SG); - rb_warning("invalid start is ignored"); - } - - if (NIL_P(hash)) - rb_raise(eDateError, "invalid date"); - - if (NIL_P(ref_hash("jd")) && - NIL_P(ref_hash("yday")) && - !NIL_P(ref_hash("year")) && - !NIL_P(ref_hash("mon")) && - !NIL_P(ref_hash("mday"))) { - jd = rt__valid_civil_p(ref_hash("year"), - ref_hash("mon"), - ref_hash("mday"), sg); - - if (NIL_P(ref_hash("hour"))) - set_hash("hour", INT2FIX(0)); - if (NIL_P(ref_hash("min"))) - set_hash("min", INT2FIX(0)); - if (NIL_P(ref_hash("sec"))) - set_hash("sec", INT2FIX(0)); - else if (f_eqeq_p(ref_hash("sec"), INT2FIX(60))) - set_hash("sec", INT2FIX(59)); - } - else { - hash = rt_rewrite_frags(hash); - hash = rt_complete_frags(klass, hash); - jd = rt__valid_date_frags_p(hash, sg); - } - - if (NIL_P(jd)) - rb_raise(eDateError, "invalid date"); - - { - int rh, rmin, rs; - - if (!c_valid_time_p(NUM2INT(ref_hash("hour")), - NUM2INT(ref_hash("min")), - NUM2INT(ref_hash("sec")), - &rh, &rmin, &rs)) - rb_raise(eDateError, "invalid date"); - - df = time_to_df(rh, rmin, rs); - } - - t = ref_hash("sec_fraction"); - if (NIL_P(t)) - sf = INT2FIX(0); - else - sf = sec_to_ns(t); - - t = ref_hash("offset"); - if (NIL_P(t)) - of = 0; - else { - of = NUM2INT(t); - if (of < -DAY_IN_SECONDS || of > DAY_IN_SECONDS) { - of = 0; - rb_warning("invalid offset is ignored"); - } - } - { - VALUE nth; - int rjd, rjd2; - - decode_jd(jd, &nth, &rjd); - rjd2 = jd_local_to_utc(rjd, df, of); - df = df_local_to_utc(df, of); - - return d_complex_new_internal(klass, - nth, rjd2, - df, sf, - of, NUM2DBL(sg), - 0, 0, 0, - 0, 0, 0, - HAVE_JD | HAVE_DF); - } -} - -/* - * call-seq: - * DateTime._strptime(string[, format='%FT%T%z']) -> hash - * - * Parses the given representation of date and time with the given - * template, and returns a hash of parsed elements. _strptime does - * not support specification of flags and width unlike strftime. - * - * See also strptime(3) and #strftime. - */ -static VALUE -datetime_s__strptime(int argc, VALUE *argv, VALUE klass) -{ - return date_s__strptime_internal(argc, argv, klass, "%FT%T%z"); -} - -/* - * call-seq: - * DateTime.strptime([string='-4712-01-01T00:00:00+00:00'[, format='%FT%T%z'[ ,start=Date::ITALY]]]) -> datetime - * - * Parses the given representation of date and time with the given - * template, and creates a DateTime object. strptime does not support - * specification of flags and width unlike strftime. - * - * DateTime.strptime('2001-02-03T04:05:06+07:00', '%Y-%m-%dT%H:%M:%S%z') - * #=> # - * DateTime.strptime('03-02-2001 04:05:06 PM', '%d-%m-%Y %I:%M:%S %p') - * #=> # - * DateTime.strptime('2001-W05-6T04:05:06+07:00', '%G-W%V-%uT%H:%M:%S%z') - * #=> # - * DateTime.strptime('2001 04 6 04 05 06 +7', '%Y %U %w %H %M %S %z') - * #=> # - * DateTime.strptime('2001 05 6 04 05 06 +7', '%Y %W %u %H %M %S %z') - * #=> # - * DateTime.strptime('-1', '%s') - * #=> # - * DateTime.strptime('-1000', '%Q') - * #=> # - * DateTime.strptime('sat3feb014pm+7', '%a%d%b%y%H%p%z') - * #=> # - * - * See also strptime(3) and #strftime. - */ -static VALUE -datetime_s_strptime(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, fmt, sg; - - rb_scan_args(argc, argv, "03", &str, &fmt, &sg); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATETIME); - case 1: - fmt = rb_str_new2("%FT%T%z"); - case 2: - sg = INT2FIX(DEFAULT_SG); - } - - { - VALUE argv2[2], hash; - - argv2[0] = str; - argv2[1] = fmt; - hash = date_s__strptime(2, argv2, klass); - return dt_new_by_frags(klass, hash, sg); - } -} - -/* - * call-seq: - * DateTime.parse(string='-4712-01-01T00:00:00+00:00'[, comp=true[, start=Date::ITALY]], limit: 128) -> datetime - * - * Parses the given representation of date and time, and creates a - * DateTime object. - * - * This method *does* *not* function as a validator. If the input - * string does not match valid formats strictly, you may get a cryptic - * result. Should consider to use DateTime.strptime instead of this - * method as possible. - * - * If the optional second argument is true and the detected year is in - * the range "00" to "99", makes it full. - * - * DateTime.parse('2001-02-03T04:05:06+07:00') - * #=> # - * DateTime.parse('20010203T040506+0700') - * #=> # - * DateTime.parse('3rd Feb 2001 04:05:06 PM') - * #=> # - * - * Raise an ArgumentError when the string length is longer than _limit_. - * You can stop this check by passing limit: nil, but note - * that it may take a long time to parse. - */ -static VALUE -datetime_s_parse(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, comp, sg, opt; - - argc = rb_scan_args(argc, argv, "03:", &str, &comp, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATETIME); - case 1: - comp = Qtrue; - case 2: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 2; - VALUE argv2[3], hash; - argv2[0] = str; - argv2[1] = comp; - argv2[2] = opt; - if (!NIL_P(opt)) argc2++; - hash = date_s__parse(argc2, argv2, klass); - return dt_new_by_frags(klass, hash, sg); - } -} - -/* - * call-seq: - * DateTime.iso8601(string='-4712-01-01T00:00:00+00:00'[, start=Date::ITALY], limit: 128) -> datetime - * - * Creates a new DateTime object by parsing from a string according to - * some typical ISO 8601 formats. - * - * DateTime.iso8601('2001-02-03T04:05:06+07:00') - * #=> # - * DateTime.iso8601('20010203T040506+0700') - * #=> # - * DateTime.iso8601('2001-W05-6T04:05:06+07:00') - * #=> # - * - * Raise an ArgumentError when the string length is longer than _limit_. - * You can stop this check by passing limit: nil, but note - * that it may take a long time to parse. - */ -static VALUE -datetime_s_iso8601(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, sg, opt; - - argc = rb_scan_args(argc, argv, "02:", &str, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATETIME); - case 1: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 1; - VALUE argv2[2], hash; - argv2[0] = str; - argv2[1] = opt; - if (!NIL_P(opt)) argc2++; - hash = date_s__iso8601(argc2, argv2, klass); - return dt_new_by_frags(klass, hash, sg); - } -} - -/* - * call-seq: - * DateTime.rfc3339(string='-4712-01-01T00:00:00+00:00'[, start=Date::ITALY], limit: 128) -> datetime - * - * Creates a new DateTime object by parsing from a string according to - * some typical RFC 3339 formats. - * - * DateTime.rfc3339('2001-02-03T04:05:06+07:00') - * #=> # - * - * Raise an ArgumentError when the string length is longer than _limit_. - * You can stop this check by passing limit: nil, but note - * that it may take a long time to parse. - */ -static VALUE -datetime_s_rfc3339(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, sg, opt; - - argc = rb_scan_args(argc, argv, "02:", &str, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATETIME); - case 1: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 1; - VALUE argv2[2], hash; - argv2[0] = str; - argv2[1] = opt; - if (!NIL_P(opt)) argc2++; - hash = date_s__rfc3339(argc2, argv2, klass); - return dt_new_by_frags(klass, hash, sg); - } -} - -/* - * call-seq: - * DateTime.xmlschema(string='-4712-01-01T00:00:00+00:00'[, start=Date::ITALY], limit: 128) -> datetime - * - * Creates a new DateTime object by parsing from a string according to - * some typical XML Schema formats. - * - * DateTime.xmlschema('2001-02-03T04:05:06+07:00') - * #=> # - * - * Raise an ArgumentError when the string length is longer than _limit_. - * You can stop this check by passing limit: nil, but note - * that it may take a long time to parse. - */ -static VALUE -datetime_s_xmlschema(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, sg, opt; - - argc = rb_scan_args(argc, argv, "02:", &str, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATETIME); - case 1: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 1; - VALUE argv2[2], hash; - argv2[0] = str; - argv2[1] = opt; - if (!NIL_P(opt)) argc2++; - hash = date_s__xmlschema(argc2, argv2, klass); - return dt_new_by_frags(klass, hash, sg); - } -} - -/* - * call-seq: - * DateTime.rfc2822(string='Mon, 1 Jan -4712 00:00:00 +0000'[, start=Date::ITALY], limit: 128) -> datetime - * DateTime.rfc822(string='Mon, 1 Jan -4712 00:00:00 +0000'[, start=Date::ITALY], limit: 128) -> datetime - * - * Creates a new DateTime object by parsing from a string according to - * some typical RFC 2822 formats. - * - * DateTime.rfc2822('Sat, 3 Feb 2001 04:05:06 +0700') - * #=> # - * - * Raise an ArgumentError when the string length is longer than _limit_. - * You can stop this check by passing limit: nil, but note - * that it may take a long time to parse. - */ -static VALUE -datetime_s_rfc2822(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, sg, opt; - - argc = rb_scan_args(argc, argv, "02:", &str, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATETIME_RFC3339); - case 1: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 1; - VALUE argv2[2], hash; - argv2[0] = str; - argv2[1] = opt; - if (!NIL_P(opt)) argc2++; - hash = date_s__rfc2822(argc2, argv2, klass); - return dt_new_by_frags(klass, hash, sg); - } -} - -/* - * call-seq: - * DateTime.httpdate(string='Mon, 01 Jan -4712 00:00:00 GMT'[, start=Date::ITALY]) -> datetime - * - * Creates a new DateTime object by parsing from a string according to - * some RFC 2616 format. - * - * DateTime.httpdate('Sat, 03 Feb 2001 04:05:06 GMT') - * #=> # - * - * Raise an ArgumentError when the string length is longer than _limit_. - * You can stop this check by passing limit: nil, but note - * that it may take a long time to parse. - */ -static VALUE -datetime_s_httpdate(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, sg, opt; - - argc = rb_scan_args(argc, argv, "02:", &str, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATETIME_HTTPDATE); - case 1: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 1; - VALUE argv2[2], hash; - argv2[0] = str; - argv2[1] = opt; - if (!NIL_P(opt)) argc2++; - hash = date_s__httpdate(argc2, argv2, klass); - return dt_new_by_frags(klass, hash, sg); - } -} - -/* - * call-seq: - * DateTime.jisx0301(string='-4712-01-01T00:00:00+00:00'[, start=Date::ITALY], limit: 128) -> datetime - * - * Creates a new DateTime object by parsing from a string according to - * some typical JIS X 0301 formats. - * - * DateTime.jisx0301('H13.02.03T04:05:06+07:00') - * #=> # - * - * For no-era year, legacy format, Heisei is assumed. - * - * DateTime.jisx0301('13.02.03T04:05:06+07:00') - * #=> # - * - * Raise an ArgumentError when the string length is longer than _limit_. - * You can stop this check by passing limit: nil, but note - * that it may take a long time to parse. - */ -static VALUE -datetime_s_jisx0301(int argc, VALUE *argv, VALUE klass) -{ - VALUE str, sg, opt; - - argc = rb_scan_args(argc, argv, "02:", &str, &sg, &opt); - - switch (argc) { - case 0: - str = rb_str_new2(JULIAN_EPOCH_DATETIME); - case 1: - sg = INT2FIX(DEFAULT_SG); - } - - { - int argc2 = 1; - VALUE argv2[2], hash; - argv2[0] = str; - argv2[1] = opt; - if (!NIL_P(opt)) argc2++; - hash = date_s__jisx0301(argc2, argv2, klass); - return dt_new_by_frags(klass, hash, sg); - } -} - -/* - * call-seq: - * dt.to_s -> string - * - * Returns a string in an ISO 8601 format. (This method doesn't use the - * expanded representations.) - * - * DateTime.new(2001,2,3,4,5,6,'-7').to_s - * #=> "2001-02-03T04:05:06-07:00" - */ -static VALUE -dt_lite_to_s(VALUE self) -{ - return strftimev("%Y-%m-%dT%H:%M:%S%:z", self, set_tmx); -} - -/* - * call-seq: - * strftime(format = '%FT%T%:z') -> string - * - * Returns a string representation of +self+, - * formatted according the given +format: - * - * DateTime.now.strftime # => "2022-07-01T11:03:19-05:00" - * - * For other formats, - * see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: - * - */ -static VALUE -dt_lite_strftime(int argc, VALUE *argv, VALUE self) -{ - return date_strftime_internal(argc, argv, self, - "%Y-%m-%dT%H:%M:%S%:z", set_tmx); -} - -static VALUE -iso8601_timediv(VALUE self, long n) -{ - static const char timefmt[] = "T%H:%M:%S"; - static const char zone[] = "%:z"; - char fmt[sizeof(timefmt) + sizeof(zone) + rb_strlen_lit(".%N") + - DECIMAL_SIZE_OF_LONG]; - char *p = fmt; - - memcpy(p, timefmt, sizeof(timefmt)-1); - p += sizeof(timefmt)-1; - if (n > 0) p += snprintf(p, fmt+sizeof(fmt)-p, ".%%%ldN", n); - memcpy(p, zone, sizeof(zone)); - return strftimev(fmt, self, set_tmx); -} - -/* - * call-seq: - * dt.iso8601([n=0]) -> string - * dt.xmlschema([n=0]) -> string - * - * This method is equivalent to strftime('%FT%T%:z'). - * The optional argument +n+ is the number of digits for fractional seconds. - * - * DateTime.parse('2001-02-03T04:05:06.123456789+07:00').iso8601(9) - * #=> "2001-02-03T04:05:06.123456789+07:00" - */ -static VALUE -dt_lite_iso8601(int argc, VALUE *argv, VALUE self) -{ - long n = 0; - - rb_check_arity(argc, 0, 1); - if (argc >= 1) - n = NUM2LONG(argv[0]); - - return rb_str_append(strftimev("%Y-%m-%d", self, set_tmx), - iso8601_timediv(self, n)); -} - -/* - * call-seq: - * dt.rfc3339([n=0]) -> string - * - * This method is equivalent to strftime('%FT%T%:z'). - * The optional argument +n+ is the number of digits for fractional seconds. - * - * DateTime.parse('2001-02-03T04:05:06.123456789+07:00').rfc3339(9) - * #=> "2001-02-03T04:05:06.123456789+07:00" - */ -static VALUE -dt_lite_rfc3339(int argc, VALUE *argv, VALUE self) -{ - return dt_lite_iso8601(argc, argv, self); -} - -/* - * call-seq: - * dt.jisx0301([n=0]) -> string - * - * Returns a string in a JIS X 0301 format. - * The optional argument +n+ is the number of digits for fractional seconds. - * - * DateTime.parse('2001-02-03T04:05:06.123456789+07:00').jisx0301(9) - * #=> "H13.02.03T04:05:06.123456789+07:00" - */ -static VALUE -dt_lite_jisx0301(int argc, VALUE *argv, VALUE self) -{ - long n = 0; - - rb_check_arity(argc, 0, 1); - if (argc >= 1) - n = NUM2LONG(argv[0]); - - return rb_str_append(d_lite_jisx0301(self), - iso8601_timediv(self, n)); -} - -/* - * call-seq: - * deconstruct_keys(array_of_names_or_nil) -> hash - * - * Returns a hash of the name/value pairs, to use in pattern matching. - * Possible keys are: :year, :month, :day, - * :wday, :yday, :hour, :min, - * :sec, :sec_fraction, :zone. - * - * Possible usages: - * - * dt = DateTime.new(2022, 10, 5, 13, 30) - * - * if d in wday: 1..5, hour: 10..18 # uses deconstruct_keys underneath - * puts "Working time" - * end - * #=> prints "Working time" - * - * case dt - * in year: ...2022 - * puts "too old" - * in month: ..9 - * puts "quarter 1-3" - * in wday: 1..5, month: - * puts "working day in month #{month}" - * end - * #=> prints "working day in month 10" - * - * Note that deconstruction by pattern can also be combined with class check: - * - * if d in DateTime(wday: 1..5, hour: 10..18, day: ..7) - * puts "Working time, first week of the month" - * end - * - */ -static VALUE -dt_lite_deconstruct_keys(VALUE self, VALUE keys) -{ - return deconstruct_keys(self, keys, /* is_datetime=true */ 1); -} - -/* conversions */ - -#define f_subsec(x) rb_funcall(x, rb_intern("subsec"), 0) -#define f_utc_offset(x) rb_funcall(x, rb_intern("utc_offset"), 0) -#define f_local3(x,y,m,d) rb_funcall(x, rb_intern("local"), 3, y, m, d) - -/* - * call-seq: - * t.to_time -> time - * - * Returns self. - */ -static VALUE -time_to_time(VALUE self) -{ - return self; -} - -/* - * call-seq: - * t.to_date -> date - * - * Returns a Date object which denotes self. - */ -static VALUE -time_to_date(VALUE self) -{ - VALUE y, nth, ret; - int ry, m, d; - - y = f_year(self); - m = FIX2INT(f_mon(self)); - d = FIX2INT(f_mday(self)); - - decode_year(y, -1, &nth, &ry); - - ret = d_simple_new_internal(cDate, - nth, 0, - GREGORIAN, - ry, m, d, - HAVE_CIVIL); - { - get_d1(ret); - set_sg(dat, DEFAULT_SG); - } - return ret; -} - -/* - * call-seq: - * t.to_datetime -> datetime - * - * Returns a DateTime object which denotes self. - */ -static VALUE -time_to_datetime(VALUE self) -{ - VALUE y, sf, nth, ret; - int ry, m, d, h, min, s, of; - - y = f_year(self); - m = FIX2INT(f_mon(self)); - d = FIX2INT(f_mday(self)); - - h = FIX2INT(f_hour(self)); - min = FIX2INT(f_min(self)); - s = FIX2INT(f_sec(self)); - if (s == 60) - s = 59; - - sf = sec_to_ns(f_subsec(self)); - of = FIX2INT(f_utc_offset(self)); - - decode_year(y, -1, &nth, &ry); - - ret = d_complex_new_internal(cDateTime, - nth, 0, - 0, sf, - of, GREGORIAN, - ry, m, d, - h, min, s, - HAVE_CIVIL | HAVE_TIME); - { - get_d1(ret); - set_sg(dat, DEFAULT_SG); - } - return ret; -} - -/* - * call-seq: - * to_time -> time - * - * Returns a new Time object with the same value as +self+; - * if +self+ is a Julian date, derives its Gregorian date - * for conversion to the \Time object: - * - * Date.new(2001, 2, 3).to_time # => 2001-02-03 00:00:00 -0600 - * Date.new(2001, 2, 3, Date::JULIAN).to_time # => 2001-02-16 00:00:00 -0600 - * - */ -static VALUE -date_to_time(VALUE self) -{ - VALUE t; - - get_d1a(self); - - if (m_julian_p(adat)) { - VALUE g = d_lite_gregorian(self); - get_d1b(g); - adat = bdat; - self = g; - } - - t = f_local3(rb_cTime, - m_real_year(adat), - INT2FIX(m_mon(adat)), - INT2FIX(m_mday(adat))); - RB_GC_GUARD(self); /* may be the converted gregorian */ - return t; -} - -/* - * call-seq: - * to_date -> self - * - * Returns +self+. - */ -static VALUE -date_to_date(VALUE self) -{ - return self; -} - -/* - * call-seq: - * d.to_datetime -> datetime - * - * Returns a DateTime whose value is the same as +self+: - * - * Date.new(2001, 2, 3).to_datetime # => # - * - */ -static VALUE -date_to_datetime(VALUE self) -{ - get_d1a(self); - - if (simple_dat_p(adat)) { - VALUE new = d_lite_s_alloc_simple(cDateTime); - { - get_d1b(new); - bdat->s = adat->s; - return new; - } - } - else { - VALUE new = d_lite_s_alloc_complex(cDateTime); - { - get_d1b(new); - bdat->c = adat->c; - bdat->c.df = 0; - RB_OBJ_WRITE(new, &bdat->c.sf, INT2FIX(0)); -#ifndef USE_PACK - bdat->c.hour = 0; - bdat->c.min = 0; - bdat->c.sec = 0; -#else - bdat->c.pc = PACK5(EX_MON(adat->c.pc), EX_MDAY(adat->c.pc), - 0, 0, 0); - bdat->c.flags |= HAVE_DF | HAVE_TIME; -#endif - return new; - } - } -} - -/* - * call-seq: - * dt.to_time -> time - * - * Returns a Time object which denotes self. - */ -static VALUE -datetime_to_time(VALUE self) -{ - get_d1(self); - - if (m_julian_p(dat)) { - VALUE g = d_lite_gregorian(self); - get_d1a(g); - dat = adat; - self = g; - } - - { - VALUE t; - - t = rb_funcall(rb_cTime, - rb_intern("new"), - 7, - m_real_year(dat), - INT2FIX(m_mon(dat)), - INT2FIX(m_mday(dat)), - INT2FIX(m_hour(dat)), - INT2FIX(m_min(dat)), - f_add(INT2FIX(m_sec(dat)), - m_sf_in_sec(dat)), - INT2FIX(m_of(dat))); - RB_GC_GUARD(self); /* may be the converted gregorian */ - return t; - } -} - -/* - * call-seq: - * dt.to_date -> date - * - * Returns a Date object which denotes self. - */ -static VALUE -datetime_to_date(VALUE self) -{ - get_d1a(self); - - if (simple_dat_p(adat)) { - VALUE new = d_lite_s_alloc_simple(cDate); - { - get_d1b(new); - bdat->s = adat->s; - bdat->s.jd = m_local_jd(adat); - return new; - } - } - else { - VALUE new = d_lite_s_alloc_simple(cDate); - { - get_d1b(new); - copy_complex_to_simple(new, &bdat->s, &adat->c); - bdat->s.jd = m_local_jd(adat); - bdat->s.flags &= ~(HAVE_DF | HAVE_TIME | COMPLEX_DAT); - return new; - } - } -} - -/* - * call-seq: - * dt.to_datetime -> self - * - * Returns self. - */ -static VALUE -datetime_to_datetime(VALUE self) -{ - return self; -} - -#ifndef NDEBUG -/* tests */ - -#define MIN_YEAR -4713 -#define MAX_YEAR 1000000 -#define MIN_JD -327 -#define MAX_JD 366963925 - -/* :nodoc: */ -static int -test_civil(int from, int to, double sg) -{ - int j; - - fprintf(stderr, "test_civil: %d...%d (%d) - %.0f\n", - from, to, to - from, sg); - for (j = from; j <= to; j++) { - int y, m, d, rj, ns; - - c_jd_to_civil(j, sg, &y, &m, &d); - c_civil_to_jd(y, m, d, sg, &rj, &ns); - if (j != rj) { - fprintf(stderr, "%d != %d\n", j, rj); - return 0; - } - } - return 1; -} - -/* :nodoc: */ -static VALUE -date_s_test_civil(VALUE klass) -{ - if (!test_civil(MIN_JD, MIN_JD + 366, GREGORIAN)) - return Qfalse; - if (!test_civil(2305814, 2598007, GREGORIAN)) - return Qfalse; - if (!test_civil(MAX_JD - 366, MAX_JD, GREGORIAN)) - return Qfalse; - - if (!test_civil(MIN_JD, MIN_JD + 366, ITALY)) - return Qfalse; - if (!test_civil(2305814, 2598007, ITALY)) - return Qfalse; - if (!test_civil(MAX_JD - 366, MAX_JD, ITALY)) - return Qfalse; - - return Qtrue; -} - -/* :nodoc: */ -static int -test_ordinal(int from, int to, double sg) -{ - int j; - - fprintf(stderr, "test_ordinal: %d...%d (%d) - %.0f\n", - from, to, to - from, sg); - for (j = from; j <= to; j++) { - int y, d, rj, ns; - - c_jd_to_ordinal(j, sg, &y, &d); - c_ordinal_to_jd(y, d, sg, &rj, &ns); - if (j != rj) { - fprintf(stderr, "%d != %d\n", j, rj); - return 0; - } - } - return 1; -} - -/* :nodoc: */ -static VALUE -date_s_test_ordinal(VALUE klass) -{ - if (!test_ordinal(MIN_JD, MIN_JD + 366, GREGORIAN)) - return Qfalse; - if (!test_ordinal(2305814, 2598007, GREGORIAN)) - return Qfalse; - if (!test_ordinal(MAX_JD - 366, MAX_JD, GREGORIAN)) - return Qfalse; - - if (!test_ordinal(MIN_JD, MIN_JD + 366, ITALY)) - return Qfalse; - if (!test_ordinal(2305814, 2598007, ITALY)) - return Qfalse; - if (!test_ordinal(MAX_JD - 366, MAX_JD, ITALY)) - return Qfalse; - - return Qtrue; -} - -/* :nodoc: */ -static int -test_commercial(int from, int to, double sg) -{ - int j; - - fprintf(stderr, "test_commercial: %d...%d (%d) - %.0f\n", - from, to, to - from, sg); - for (j = from; j <= to; j++) { - int y, w, d, rj, ns; - - c_jd_to_commercial(j, sg, &y, &w, &d); - c_commercial_to_jd(y, w, d, sg, &rj, &ns); - if (j != rj) { - fprintf(stderr, "%d != %d\n", j, rj); - return 0; - } - } - return 1; -} - -/* :nodoc: */ -static VALUE -date_s_test_commercial(VALUE klass) -{ - if (!test_commercial(MIN_JD, MIN_JD + 366, GREGORIAN)) - return Qfalse; - if (!test_commercial(2305814, 2598007, GREGORIAN)) - return Qfalse; - if (!test_commercial(MAX_JD - 366, MAX_JD, GREGORIAN)) - return Qfalse; - - if (!test_commercial(MIN_JD, MIN_JD + 366, ITALY)) - return Qfalse; - if (!test_commercial(2305814, 2598007, ITALY)) - return Qfalse; - if (!test_commercial(MAX_JD - 366, MAX_JD, ITALY)) - return Qfalse; - - return Qtrue; -} - -/* :nodoc: */ -static int -test_weeknum(int from, int to, int f, double sg) -{ - int j; - - fprintf(stderr, "test_weeknum: %d...%d (%d) - %.0f\n", - from, to, to - from, sg); - for (j = from; j <= to; j++) { - int y, w, d, rj, ns; - - c_jd_to_weeknum(j, f, sg, &y, &w, &d); - c_weeknum_to_jd(y, w, d, f, sg, &rj, &ns); - if (j != rj) { - fprintf(stderr, "%d != %d\n", j, rj); - return 0; - } - } - return 1; -} - -/* :nodoc: */ -static VALUE -date_s_test_weeknum(VALUE klass) -{ - int f; - - for (f = 0; f <= 1; f++) { - if (!test_weeknum(MIN_JD, MIN_JD + 366, f, GREGORIAN)) - return Qfalse; - if (!test_weeknum(2305814, 2598007, f, GREGORIAN)) - return Qfalse; - if (!test_weeknum(MAX_JD - 366, MAX_JD, f, GREGORIAN)) - return Qfalse; - - if (!test_weeknum(MIN_JD, MIN_JD + 366, f, ITALY)) - return Qfalse; - if (!test_weeknum(2305814, 2598007, f, ITALY)) - return Qfalse; - if (!test_weeknum(MAX_JD - 366, MAX_JD, f, ITALY)) - return Qfalse; - } - - return Qtrue; -} - -/* :nodoc: */ -static int -test_nth_kday(int from, int to, double sg) -{ - int j; - - fprintf(stderr, "test_nth_kday: %d...%d (%d) - %.0f\n", - from, to, to - from, sg); - for (j = from; j <= to; j++) { - int y, m, n, k, rj, ns; - - c_jd_to_nth_kday(j, sg, &y, &m, &n, &k); - c_nth_kday_to_jd(y, m, n, k, sg, &rj, &ns); - if (j != rj) { - fprintf(stderr, "%d != %d\n", j, rj); - return 0; - } - } - return 1; -} - -/* :nodoc: */ -static VALUE -date_s_test_nth_kday(VALUE klass) -{ - if (!test_nth_kday(MIN_JD, MIN_JD + 366, GREGORIAN)) - return Qfalse; - if (!test_nth_kday(2305814, 2598007, GREGORIAN)) - return Qfalse; - if (!test_nth_kday(MAX_JD - 366, MAX_JD, GREGORIAN)) - return Qfalse; - - if (!test_nth_kday(MIN_JD, MIN_JD + 366, ITALY)) - return Qfalse; - if (!test_nth_kday(2305814, 2598007, ITALY)) - return Qfalse; - if (!test_nth_kday(MAX_JD - 366, MAX_JD, ITALY)) - return Qfalse; - - return Qtrue; -} - -/* :nodoc: */ -static int -test_unit_v2v(VALUE i, - VALUE (* conv1)(VALUE), - VALUE (* conv2)(VALUE)) -{ - VALUE c, o; - c = (*conv1)(i); - o = (*conv2)(c); - return f_eqeq_p(o, i); -} - -/* :nodoc: */ -static int -test_unit_v2v_iter2(VALUE (* conv1)(VALUE), - VALUE (* conv2)(VALUE)) -{ - if (!test_unit_v2v(INT2FIX(0), conv1, conv2)) - return 0; - if (!test_unit_v2v(INT2FIX(1), conv1, conv2)) - return 0; - if (!test_unit_v2v(INT2FIX(2), conv1, conv2)) - return 0; - if (!test_unit_v2v(INT2FIX(3), conv1, conv2)) - return 0; - if (!test_unit_v2v(INT2FIX(11), conv1, conv2)) - return 0; - if (!test_unit_v2v(INT2FIX(65535), conv1, conv2)) - return 0; - if (!test_unit_v2v(INT2FIX(1073741823), conv1, conv2)) - return 0; - if (!test_unit_v2v(INT2NUM(1073741824), conv1, conv2)) - return 0; - if (!test_unit_v2v(rb_rational_new2(INT2FIX(0), INT2FIX(1)), conv1, conv2)) - return 0; - if (!test_unit_v2v(rb_rational_new2(INT2FIX(1), INT2FIX(1)), conv1, conv2)) - return 0; - if (!test_unit_v2v(rb_rational_new2(INT2FIX(1), INT2FIX(2)), conv1, conv2)) - return 0; - if (!test_unit_v2v(rb_rational_new2(INT2FIX(2), INT2FIX(3)), conv1, conv2)) - return 0; - return 1; -} - -/* :nodoc: */ -static int -test_unit_v2v_iter(VALUE (* conv1)(VALUE), - VALUE (* conv2)(VALUE)) -{ - if (!test_unit_v2v_iter2(conv1, conv2)) - return 0; - if (!test_unit_v2v_iter2(conv2, conv1)) - return 0; - return 1; -} - -/* :nodoc: */ -static VALUE -date_s_test_unit_conv(VALUE klass) -{ - if (!test_unit_v2v_iter(sec_to_day, day_to_sec)) - return Qfalse; - if (!test_unit_v2v_iter(ms_to_sec, sec_to_ms)) - return Qfalse; - if (!test_unit_v2v_iter(ns_to_day, day_to_ns)) - return Qfalse; - if (!test_unit_v2v_iter(ns_to_sec, sec_to_ns)) - return Qfalse; - return Qtrue; -} - -/* :nodoc: */ -static VALUE -date_s_test_all(VALUE klass) -{ - if (date_s_test_civil(klass) == Qfalse) - return Qfalse; - if (date_s_test_ordinal(klass) == Qfalse) - return Qfalse; - if (date_s_test_commercial(klass) == Qfalse) - return Qfalse; - if (date_s_test_weeknum(klass) == Qfalse) - return Qfalse; - if (date_s_test_nth_kday(klass) == Qfalse) - return Qfalse; - if (date_s_test_unit_conv(klass) == Qfalse) - return Qfalse; - return Qtrue; -} -#endif - -static const char *monthnames[] = { - NULL, - "January", "February", "March", - "April", "May", "June", - "July", "August", "September", - "October", "November", "December" -}; - -static const char *abbr_monthnames[] = { - NULL, - "Jan", "Feb", "Mar", "Apr", - "May", "Jun", "Jul", "Aug", - "Sep", "Oct", "Nov", "Dec" -}; - -static const char *daynames[] = { - "Sunday", "Monday", "Tuesday", "Wednesday", - "Thursday", "Friday", "Saturday" -}; - -static const char *abbr_daynames[] = { - "Sun", "Mon", "Tue", "Wed", - "Thu", "Fri", "Sat" -}; - -static VALUE -mk_ary_of_str(long len, const char *a[]) -{ - VALUE o; - long i; - - o = rb_ary_new2(len); - for (i = 0; i < len; i++) { - VALUE e; - - if (!a[i]) - e = Qnil; - else { - e = rb_usascii_str_new2(a[i]); - rb_obj_freeze(e); - } - rb_ary_push(o, e); - } - rb_ary_freeze(o); - return o; -} - -/* :nodoc: */ -static VALUE -d_lite_zero(VALUE x) -{ - return INT2FIX(0); -} - -void -Init_date_core(void) -{ - #ifdef HAVE_RB_EXT_RACTOR_SAFE - RB_EXT_RACTOR_SAFE(true); - #endif - id_cmp = rb_intern_const("<=>"); - id_le_p = rb_intern_const("<="); - id_ge_p = rb_intern_const(">="); - id_eqeq_p = rb_intern_const("=="); - - sym_year = ID2SYM(rb_intern_const("year")); - sym_month = ID2SYM(rb_intern_const("month")); - sym_yday = ID2SYM(rb_intern_const("yday")); - sym_wday = ID2SYM(rb_intern_const("wday")); - sym_day = ID2SYM(rb_intern_const("day")); - sym_hour = ID2SYM(rb_intern_const("hour")); - sym_min = ID2SYM(rb_intern_const("min")); - sym_sec = ID2SYM(rb_intern_const("sec")); - sym_sec_fraction = ID2SYM(rb_intern_const("sec_fraction")); - sym_zone = ID2SYM(rb_intern_const("zone")); - - half_days_in_day = rb_rational_new2(INT2FIX(1), INT2FIX(2)); - rb_gc_register_mark_object(half_days_in_day); - -#if (LONG_MAX / DAY_IN_SECONDS) > SECOND_IN_NANOSECONDS - day_in_nanoseconds = LONG2NUM((long)DAY_IN_SECONDS * - SECOND_IN_NANOSECONDS); -#elif defined HAVE_LONG_LONG - day_in_nanoseconds = LL2NUM((LONG_LONG)DAY_IN_SECONDS * - SECOND_IN_NANOSECONDS); -#else - day_in_nanoseconds = f_mul(INT2FIX(DAY_IN_SECONDS), - INT2FIX(SECOND_IN_NANOSECONDS)); -#endif - rb_gc_register_mark_object(day_in_nanoseconds); - - positive_inf = +INFINITY; - negative_inf = -INFINITY; - - /* - * \Class \Date provides methods for storing and manipulating - * calendar dates. - * - * Consider using - * {class Time}[rdoc-ref:Time] - * instead of class \Date if: - * - * - You need both dates and times; \Date handles only dates. - * - You need only Gregorian dates (and not Julian dates); - * see {Julian and Gregorian Calendars}[rdoc-ref:language/calendars.rdoc]. - * - * A \Date object, once created, is immutable, and cannot be modified. - * - * == Creating a \Date - * - * You can create a date for the current date, using Date.today: - * - * Date.today # => # - * - * You can create a specific date from various combinations of arguments: - * - * - Date.new takes integer year, month, and day-of-month: - * - * Date.new(1999, 12, 31) # => # - * - * - Date.ordinal takes integer year and day-of-year: - * - * Date.ordinal(1999, 365) # => # - * - * - Date.jd takes integer Julian day: - * - * Date.jd(2451544) # => # - * - * - Date.commercial takes integer commercial data (year, week, day-of-week): - * - * Date.commercial(1999, 52, 5) # => # - * - * - Date.parse takes a string, which it parses heuristically: - * - * Date.parse('1999-12-31') # => # - * Date.parse('31-12-1999') # => # - * Date.parse('1999-365') # => # - * Date.parse('1999-W52-5') # => # - * - * - Date.strptime takes a date string and a format string, - * then parses the date string according to the format string: - * - * Date.strptime('1999-12-31', '%Y-%m-%d') # => # - * Date.strptime('31-12-1999', '%d-%m-%Y') # => # - * Date.strptime('1999-365', '%Y-%j') # => # - * Date.strptime('1999-W52-5', '%G-W%V-%u') # => # - * Date.strptime('1999 52 5', '%Y %U %w') # => # - * Date.strptime('1999 52 5', '%Y %W %u') # => # - * Date.strptime('fri31dec99', '%a%d%b%y') # => # - * - * See also the specialized methods in - * {"Specialized Format Strings" in Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc@Specialized+Format+Strings] - * - * == Argument +limit+ - * - * Certain singleton methods in \Date that parse string arguments - * also take optional keyword argument +limit+, - * which can limit the length of the string argument. - * - * When +limit+ is: - * - * - Non-negative: - * raises ArgumentError if the string length is greater than _limit_. - * - Other numeric or +nil+: ignores +limit+. - * - Other non-numeric: raises TypeError. - * - */ - cDate = rb_define_class("Date", rb_cObject); - - /* Exception for invalid date/time */ - eDateError = rb_define_class_under(cDate, "Error", rb_eArgError); - - rb_include_module(cDate, rb_mComparable); - - /* An array of strings of full month names in English. The first - * element is nil. - */ - rb_define_const(cDate, "MONTHNAMES", mk_ary_of_str(13, monthnames)); - - /* An array of strings of abbreviated month names in English. The - * first element is nil. - */ - rb_define_const(cDate, "ABBR_MONTHNAMES", - mk_ary_of_str(13, abbr_monthnames)); - - /* An array of strings of the full names of days of the week in English. - * The first is "Sunday". - */ - rb_define_const(cDate, "DAYNAMES", mk_ary_of_str(7, daynames)); - - /* An array of strings of abbreviated day names in English. The - * first is "Sun". - */ - rb_define_const(cDate, "ABBR_DAYNAMES", mk_ary_of_str(7, abbr_daynames)); - - /* The Julian day number of the day of calendar reform for Italy - * and some catholic countries. - */ - rb_define_const(cDate, "ITALY", INT2FIX(ITALY)); - - /* The Julian day number of the day of calendar reform for England - * and her colonies. - */ - rb_define_const(cDate, "ENGLAND", INT2FIX(ENGLAND)); - - /* The Julian day number of the day of calendar reform for the - * proleptic Julian calendar. - */ - rb_define_const(cDate, "JULIAN", DBL2NUM(JULIAN)); - - /* The Julian day number of the day of calendar reform for the - * proleptic Gregorian calendar. - */ - rb_define_const(cDate, "GREGORIAN", DBL2NUM(GREGORIAN)); - - rb_define_alloc_func(cDate, d_lite_s_alloc_simple); - -#ifndef NDEBUG - rb_define_private_method(CLASS_OF(cDate), "_valid_jd?", - date_s__valid_jd_p, -1); - rb_define_private_method(CLASS_OF(cDate), "_valid_ordinal?", - date_s__valid_ordinal_p, -1); - rb_define_private_method(CLASS_OF(cDate), "_valid_civil?", - date_s__valid_civil_p, -1); - rb_define_private_method(CLASS_OF(cDate), "_valid_date?", - date_s__valid_civil_p, -1); - rb_define_private_method(CLASS_OF(cDate), "_valid_commercial?", - date_s__valid_commercial_p, -1); - rb_define_private_method(CLASS_OF(cDate), "_valid_weeknum?", - date_s__valid_weeknum_p, -1); - rb_define_private_method(CLASS_OF(cDate), "_valid_nth_kday?", - date_s__valid_nth_kday_p, -1); -#endif - - rb_define_singleton_method(cDate, "valid_jd?", date_s_valid_jd_p, -1); - rb_define_singleton_method(cDate, "valid_ordinal?", - date_s_valid_ordinal_p, -1); - rb_define_singleton_method(cDate, "valid_civil?", date_s_valid_civil_p, -1); - rb_define_singleton_method(cDate, "valid_date?", date_s_valid_civil_p, -1); - rb_define_singleton_method(cDate, "valid_commercial?", - date_s_valid_commercial_p, -1); - -#ifndef NDEBUG - rb_define_private_method(CLASS_OF(cDate), "valid_weeknum?", - date_s_valid_weeknum_p, -1); - rb_define_private_method(CLASS_OF(cDate), "valid_nth_kday?", - date_s_valid_nth_kday_p, -1); - rb_define_private_method(CLASS_OF(cDate), "zone_to_diff", - date_s_zone_to_diff, 1); -#endif - - rb_define_singleton_method(cDate, "julian_leap?", date_s_julian_leap_p, 1); - rb_define_singleton_method(cDate, "gregorian_leap?", - date_s_gregorian_leap_p, 1); - rb_define_singleton_method(cDate, "leap?", - date_s_gregorian_leap_p, 1); - -#ifndef NDEBUG - rb_define_singleton_method(cDate, "new!", date_s_new_bang, -1); - rb_define_alias(rb_singleton_class(cDate), "new_l!", "new"); -#endif - - rb_define_singleton_method(cDate, "jd", date_s_jd, -1); - rb_define_singleton_method(cDate, "ordinal", date_s_ordinal, -1); - rb_define_singleton_method(cDate, "civil", date_s_civil, -1); - rb_define_singleton_method(cDate, "commercial", date_s_commercial, -1); - -#ifndef NDEBUG - rb_define_singleton_method(cDate, "weeknum", date_s_weeknum, -1); - rb_define_singleton_method(cDate, "nth_kday", date_s_nth_kday, -1); -#endif - - rb_define_singleton_method(cDate, "today", date_s_today, -1); - rb_define_singleton_method(cDate, "_strptime", date_s__strptime, -1); - rb_define_singleton_method(cDate, "strptime", date_s_strptime, -1); - rb_define_singleton_method(cDate, "_parse", date_s__parse, -1); - rb_define_singleton_method(cDate, "parse", date_s_parse, -1); - rb_define_singleton_method(cDate, "_iso8601", date_s__iso8601, -1); - rb_define_singleton_method(cDate, "iso8601", date_s_iso8601, -1); - rb_define_singleton_method(cDate, "_rfc3339", date_s__rfc3339, -1); - rb_define_singleton_method(cDate, "rfc3339", date_s_rfc3339, -1); - rb_define_singleton_method(cDate, "_xmlschema", date_s__xmlschema, -1); - rb_define_singleton_method(cDate, "xmlschema", date_s_xmlschema, -1); - rb_define_singleton_method(cDate, "_rfc2822", date_s__rfc2822, -1); - rb_define_singleton_method(cDate, "_rfc822", date_s__rfc2822, -1); - rb_define_singleton_method(cDate, "rfc2822", date_s_rfc2822, -1); - rb_define_singleton_method(cDate, "rfc822", date_s_rfc2822, -1); - rb_define_singleton_method(cDate, "_httpdate", date_s__httpdate, -1); - rb_define_singleton_method(cDate, "httpdate", date_s_httpdate, -1); - rb_define_singleton_method(cDate, "_jisx0301", date_s__jisx0301, -1); - rb_define_singleton_method(cDate, "jisx0301", date_s_jisx0301, -1); - - rb_define_method(cDate, "initialize", date_initialize, -1); - rb_define_method(cDate, "initialize_copy", d_lite_initialize_copy, 1); - -#ifndef NDEBUG - rb_define_method(cDate, "fill", d_lite_fill, 0); -#endif - - rb_define_method(cDate, "ajd", d_lite_ajd, 0); - rb_define_method(cDate, "amjd", d_lite_amjd, 0); - rb_define_method(cDate, "jd", d_lite_jd, 0); - rb_define_method(cDate, "mjd", d_lite_mjd, 0); - rb_define_method(cDate, "ld", d_lite_ld, 0); - - rb_define_method(cDate, "year", d_lite_year, 0); - rb_define_method(cDate, "yday", d_lite_yday, 0); - rb_define_method(cDate, "mon", d_lite_mon, 0); - rb_define_method(cDate, "month", d_lite_mon, 0); - rb_define_method(cDate, "mday", d_lite_mday, 0); - rb_define_method(cDate, "day", d_lite_mday, 0); - rb_define_method(cDate, "day_fraction", d_lite_day_fraction, 0); - - rb_define_method(cDate, "cwyear", d_lite_cwyear, 0); - rb_define_method(cDate, "cweek", d_lite_cweek, 0); - rb_define_method(cDate, "cwday", d_lite_cwday, 0); - -#ifndef NDEBUG - rb_define_private_method(cDate, "wnum0", d_lite_wnum0, 0); - rb_define_private_method(cDate, "wnum1", d_lite_wnum1, 0); -#endif - - rb_define_method(cDate, "wday", d_lite_wday, 0); - - rb_define_method(cDate, "sunday?", d_lite_sunday_p, 0); - rb_define_method(cDate, "monday?", d_lite_monday_p, 0); - rb_define_method(cDate, "tuesday?", d_lite_tuesday_p, 0); - rb_define_method(cDate, "wednesday?", d_lite_wednesday_p, 0); - rb_define_method(cDate, "thursday?", d_lite_thursday_p, 0); - rb_define_method(cDate, "friday?", d_lite_friday_p, 0); - rb_define_method(cDate, "saturday?", d_lite_saturday_p, 0); - -#ifndef NDEBUG - rb_define_method(cDate, "nth_kday?", d_lite_nth_kday_p, 2); -#endif - - rb_define_private_method(cDate, "hour", d_lite_zero, 0); - rb_define_private_method(cDate, "min", d_lite_zero, 0); - rb_define_private_method(cDate, "minute", d_lite_zero, 0); - rb_define_private_method(cDate, "sec", d_lite_zero, 0); - rb_define_private_method(cDate, "second", d_lite_zero, 0); - - rb_define_method(cDate, "julian?", d_lite_julian_p, 0); - rb_define_method(cDate, "gregorian?", d_lite_gregorian_p, 0); - rb_define_method(cDate, "leap?", d_lite_leap_p, 0); - - rb_define_method(cDate, "start", d_lite_start, 0); - rb_define_method(cDate, "new_start", d_lite_new_start, -1); - rb_define_method(cDate, "italy", d_lite_italy, 0); - rb_define_method(cDate, "england", d_lite_england, 0); - rb_define_method(cDate, "julian", d_lite_julian, 0); - rb_define_method(cDate, "gregorian", d_lite_gregorian, 0); - - rb_define_method(cDate, "+", d_lite_plus, 1); - rb_define_method(cDate, "-", d_lite_minus, 1); - - rb_define_method(cDate, "next_day", d_lite_next_day, -1); - rb_define_method(cDate, "prev_day", d_lite_prev_day, -1); - rb_define_method(cDate, "next", d_lite_next, 0); - rb_define_method(cDate, "succ", d_lite_next, 0); - - rb_define_method(cDate, ">>", d_lite_rshift, 1); - rb_define_method(cDate, "<<", d_lite_lshift, 1); - - rb_define_method(cDate, "next_month", d_lite_next_month, -1); - rb_define_method(cDate, "prev_month", d_lite_prev_month, -1); - rb_define_method(cDate, "next_year", d_lite_next_year, -1); - rb_define_method(cDate, "prev_year", d_lite_prev_year, -1); - - rb_define_method(cDate, "step", d_lite_step, -1); - rb_define_method(cDate, "upto", d_lite_upto, 1); - rb_define_method(cDate, "downto", d_lite_downto, 1); - - rb_define_method(cDate, "<=>", d_lite_cmp, 1); - rb_define_method(cDate, "===", d_lite_equal, 1); - rb_define_method(cDate, "eql?", d_lite_eql_p, 1); - rb_define_method(cDate, "hash", d_lite_hash, 0); - - rb_define_method(cDate, "to_s", d_lite_to_s, 0); -#ifndef NDEBUG - rb_define_method(cDate, "inspect_raw", d_lite_inspect_raw, 0); -#endif - rb_define_method(cDate, "inspect", d_lite_inspect, 0); - - rb_define_method(cDate, "strftime", d_lite_strftime, -1); - - rb_define_method(cDate, "asctime", d_lite_asctime, 0); - rb_define_method(cDate, "ctime", d_lite_asctime, 0); - rb_define_method(cDate, "iso8601", d_lite_iso8601, 0); - rb_define_method(cDate, "xmlschema", d_lite_iso8601, 0); - rb_define_method(cDate, "rfc3339", d_lite_rfc3339, 0); - rb_define_method(cDate, "rfc2822", d_lite_rfc2822, 0); - rb_define_method(cDate, "rfc822", d_lite_rfc2822, 0); - rb_define_method(cDate, "httpdate", d_lite_httpdate, 0); - rb_define_method(cDate, "jisx0301", d_lite_jisx0301, 0); - - rb_define_method(cDate, "deconstruct_keys", d_lite_deconstruct_keys, 1); - -#ifndef NDEBUG - rb_define_method(cDate, "marshal_dump_old", d_lite_marshal_dump_old, 0); -#endif - rb_define_method(cDate, "marshal_dump", d_lite_marshal_dump, 0); - rb_define_method(cDate, "marshal_load", d_lite_marshal_load, 1); - rb_define_singleton_method(cDate, "_load", date_s__load, 1); - - /* - * == DateTime - * - * A subclass of Date that easily handles date, hour, minute, second, - * and offset. - * - * DateTime class is considered deprecated. Use Time class. - * - * DateTime does not consider any leap seconds, does not track - * any summer time rules. - * - * A DateTime object is created with DateTime::new, DateTime::jd, - * DateTime::ordinal, DateTime::commercial, DateTime::parse, - * DateTime::strptime, DateTime::now, Time#to_datetime, etc. - * - * require 'date' - * - * DateTime.new(2001,2,3,4,5,6) - * #=> # - * - * The last element of day, hour, minute, or second can be a - * fractional number. The fractional number's precision is assumed - * at most nanosecond. - * - * DateTime.new(2001,2,3.5) - * #=> # - * - * An optional argument, the offset, indicates the difference - * between the local time and UTC. For example, Rational(3,24) - * represents ahead of 3 hours of UTC, Rational(-5,24) represents - * behind of 5 hours of UTC. The offset should be -1 to +1, and - * its precision is assumed at most second. The default value is - * zero (equals to UTC). - * - * DateTime.new(2001,2,3,4,5,6,Rational(3,24)) - * #=> # - * - * The offset also accepts string form: - * - * DateTime.new(2001,2,3,4,5,6,'+03:00') - * #=> # - * - * An optional argument, the day of calendar reform (+start+), denotes - * a Julian day number, which should be 2298874 to 2426355 or - * negative/positive infinity. - * The default value is +Date::ITALY+ (2299161=1582-10-15). - * - * A DateTime object has various methods. See each reference. - * - * d = DateTime.parse('3rd Feb 2001 04:05:06+03:30') - * #=> # - * d.hour #=> 4 - * d.min #=> 5 - * d.sec #=> 6 - * d.offset #=> (7/48) - * d.zone #=> "+03:30" - * d += Rational('1.5') - * #=> # - * d = d.new_offset('+09:00') - * #=> # - * d.strftime('%I:%M:%S %p') - * #=> "09:35:06 PM" - * d > DateTime.new(1999) - * #=> true - * - * === When should you use DateTime and when should you use Time? - * - * It's a common misconception that - * {William Shakespeare}[https://en.wikipedia.org/wiki/William_Shakespeare] - * and - * {Miguel de Cervantes}[https://en.wikipedia.org/wiki/Miguel_de_Cervantes] - * died on the same day in history - - * so much so that UNESCO named April 23 as - * {World Book Day because of this fact}[https://en.wikipedia.org/wiki/World_Book_Day]. - * However, because England hadn't yet adopted the - * {Gregorian Calendar Reform}[https://en.wikipedia.org/wiki/Gregorian_calendar#Gregorian_reform] - * (and wouldn't until {1752}[https://en.wikipedia.org/wiki/Calendar_(New_Style)_Act_1750]) - * their deaths are actually 10 days apart. - * Since Ruby's Time class implements a - * {proleptic Gregorian calendar}[https://en.wikipedia.org/wiki/Proleptic_Gregorian_calendar] - * and has no concept of calendar reform there's no way - * to express this with Time objects. This is where DateTime steps in: - * - * shakespeare = DateTime.iso8601('1616-04-23', Date::ENGLAND) - * #=> Tue, 23 Apr 1616 00:00:00 +0000 - * cervantes = DateTime.iso8601('1616-04-23', Date::ITALY) - * #=> Sat, 23 Apr 1616 00:00:00 +0000 - * - * Already you can see something is weird - the days of the week - * are different. Taking this further: - * - * cervantes == shakespeare - * #=> false - * (shakespeare - cervantes).to_i - * #=> 10 - * - * This shows that in fact they died 10 days apart (in reality - * 11 days since Cervantes died a day earlier but was buried on - * the 23rd). We can see the actual date of Shakespeare's death by - * using the #gregorian method to convert it: - * - * shakespeare.gregorian - * #=> Tue, 03 May 1616 00:00:00 +0000 - * - * So there's an argument that all the celebrations that take - * place on the 23rd April in Stratford-upon-Avon are actually - * the wrong date since England is now using the Gregorian calendar. - * You can see why when we transition across the reform - * date boundary: - * - * # start off with the anniversary of Shakespeare's birth in 1751 - * shakespeare = DateTime.iso8601('1751-04-23', Date::ENGLAND) - * #=> Tue, 23 Apr 1751 00:00:00 +0000 - * - * # add 366 days since 1752 is a leap year and April 23 is after February 29 - * shakespeare + 366 - * #=> Thu, 23 Apr 1752 00:00:00 +0000 - * - * # add another 365 days to take us to the anniversary in 1753 - * shakespeare + 366 + 365 - * #=> Fri, 04 May 1753 00:00:00 +0000 - * - * As you can see, if we're accurately tracking the number of - * {solar years}[https://en.wikipedia.org/wiki/Tropical_year] - * since Shakespeare's birthday then the correct anniversary date - * would be the 4th May and not the 23rd April. - * - * So when should you use DateTime in Ruby and when should - * you use Time? Almost certainly you'll want to use Time - * since your app is probably dealing with current dates and - * times. However, if you need to deal with dates and times in a - * historical context you'll want to use DateTime to avoid - * making the same mistakes as UNESCO. If you also have to deal - * with timezones then best of luck - just bear in mind that - * you'll probably be dealing with - * {local solar times}[https://en.wikipedia.org/wiki/Solar_time], - * since it wasn't until the 19th century that the introduction - * of the railways necessitated the need for - * {Standard Time}[https://en.wikipedia.org/wiki/Standard_time#Great_Britain] - * and eventually timezones. - */ - - cDateTime = rb_define_class("DateTime", cDate); - rb_define_alloc_func(cDateTime, d_lite_s_alloc_complex); - - rb_define_singleton_method(cDateTime, "jd", datetime_s_jd, -1); - rb_define_singleton_method(cDateTime, "ordinal", datetime_s_ordinal, -1); - rb_define_singleton_method(cDateTime, "civil", datetime_s_civil, -1); - rb_define_singleton_method(cDateTime, "new", datetime_s_civil, -1); - rb_define_singleton_method(cDateTime, "commercial", - datetime_s_commercial, -1); - -#ifndef NDEBUG - rb_define_singleton_method(cDateTime, "weeknum", - datetime_s_weeknum, -1); - rb_define_singleton_method(cDateTime, "nth_kday", - datetime_s_nth_kday, -1); -#endif - - rb_undef_method(CLASS_OF(cDateTime), "today"); - - rb_define_singleton_method(cDateTime, "now", datetime_s_now, -1); - rb_define_singleton_method(cDateTime, "_strptime", - datetime_s__strptime, -1); - rb_define_singleton_method(cDateTime, "strptime", - datetime_s_strptime, -1); - rb_define_singleton_method(cDateTime, "parse", - datetime_s_parse, -1); - rb_define_singleton_method(cDateTime, "iso8601", - datetime_s_iso8601, -1); - rb_define_singleton_method(cDateTime, "rfc3339", - datetime_s_rfc3339, -1); - rb_define_singleton_method(cDateTime, "xmlschema", - datetime_s_xmlschema, -1); - rb_define_singleton_method(cDateTime, "rfc2822", - datetime_s_rfc2822, -1); - rb_define_singleton_method(cDateTime, "rfc822", - datetime_s_rfc2822, -1); - rb_define_singleton_method(cDateTime, "httpdate", - datetime_s_httpdate, -1); - rb_define_singleton_method(cDateTime, "jisx0301", - datetime_s_jisx0301, -1); - - rb_define_method(cDateTime, "hour", d_lite_hour, 0); - rb_define_method(cDateTime, "min", d_lite_min, 0); - rb_define_method(cDateTime, "minute", d_lite_min, 0); - rb_define_method(cDateTime, "sec", d_lite_sec, 0); - rb_define_method(cDateTime, "second", d_lite_sec, 0); - rb_define_method(cDateTime, "sec_fraction", d_lite_sec_fraction, 0); - rb_define_method(cDateTime, "second_fraction", d_lite_sec_fraction, 0); - rb_define_method(cDateTime, "offset", d_lite_offset, 0); - rb_define_method(cDateTime, "zone", d_lite_zone, 0); - rb_define_method(cDateTime, "new_offset", d_lite_new_offset, -1); - - rb_define_method(cDateTime, "to_s", dt_lite_to_s, 0); - - rb_define_method(cDateTime, "strftime", dt_lite_strftime, -1); - - rb_define_method(cDateTime, "iso8601", dt_lite_iso8601, -1); - rb_define_method(cDateTime, "xmlschema", dt_lite_iso8601, -1); - rb_define_method(cDateTime, "rfc3339", dt_lite_rfc3339, -1); - rb_define_method(cDateTime, "jisx0301", dt_lite_jisx0301, -1); - - rb_define_method(cDateTime, "deconstruct_keys", dt_lite_deconstruct_keys, 1); - - /* conversions */ - - rb_define_method(rb_cTime, "to_time", time_to_time, 0); - rb_define_method(rb_cTime, "to_date", time_to_date, 0); - rb_define_method(rb_cTime, "to_datetime", time_to_datetime, 0); - - rb_define_method(cDate, "to_time", date_to_time, 0); - rb_define_method(cDate, "to_date", date_to_date, 0); - rb_define_method(cDate, "to_datetime", date_to_datetime, 0); - - rb_define_method(cDateTime, "to_time", datetime_to_time, 0); - rb_define_method(cDateTime, "to_date", datetime_to_date, 0); - rb_define_method(cDateTime, "to_datetime", datetime_to_datetime, 0); - -#ifndef NDEBUG - /* tests */ - - rb_define_singleton_method(cDate, "test_civil", date_s_test_civil, 0); - rb_define_singleton_method(cDate, "test_ordinal", date_s_test_ordinal, 0); - rb_define_singleton_method(cDate, "test_commercial", - date_s_test_commercial, 0); - rb_define_singleton_method(cDate, "test_weeknum", date_s_test_weeknum, 0); - rb_define_singleton_method(cDate, "test_nth_kday", date_s_test_nth_kday, 0); - rb_define_singleton_method(cDate, "test_unit_conv", - date_s_test_unit_conv, 0); - rb_define_singleton_method(cDate, "test_all", date_s_test_all, 0); -#endif -} - -/* -Local variables: -c-file-style: "ruby" -End: -*/ diff --git a/ext/date/date_parse.c b/ext/date/date_parse.c deleted file mode 100644 index a1600e47..00000000 --- a/ext/date/date_parse.c +++ /dev/null @@ -1,3086 +0,0 @@ -/* - date_parse.c: Coded by Tadayoshi Funaba 2011,2012 -*/ - -#include "ruby.h" -#include "ruby/encoding.h" -#include "ruby/re.h" -#include - -#undef strncasecmp -#define strncasecmp STRNCASECMP - -RUBY_EXTERN VALUE rb_int_positive_pow(long x, unsigned long y); -RUBY_EXTERN unsigned long ruby_scan_digits(const char *str, ssize_t len, int base, size_t *retlen, int *overflow); - -/* #define TIGHT_PARSER */ - -#define sizeof_array(o) (sizeof o / sizeof o[0]) - -#define f_negate(x) rb_funcall(x, rb_intern("-@"), 0) -#define f_add(x,y) rb_funcall(x, '+', 1, y) -#define f_sub(x,y) rb_funcall(x, '-', 1, y) -#define f_mul(x,y) rb_funcall(x, '*', 1, y) -#define f_div(x,y) rb_funcall(x, '/', 1, y) -#define f_idiv(x,y) rb_funcall(x, rb_intern("div"), 1, y) -#define f_mod(x,y) rb_funcall(x, '%', 1, y) -#define f_expt(x,y) rb_funcall(x, rb_intern("**"), 1, y) - -#define f_lt_p(x,y) rb_funcall(x, '<', 1, y) -#define f_gt_p(x,y) rb_funcall(x, '>', 1, y) -#define f_le_p(x,y) rb_funcall(x, rb_intern("<="), 1, y) -#define f_ge_p(x,y) rb_funcall(x, rb_intern(">="), 1, y) - -#define f_to_s(x) rb_funcall(x, rb_intern("to_s"), 0) - -#define f_match(r,s) rb_funcall(r, rb_intern("match"), 1, s) -#define f_aref(o,i) rb_funcall(o, rb_intern("[]"), 1, i) -#define f_aref2(o,i,j) rb_funcall(o, rb_intern("[]"), 2, i, j) -#define f_begin(o,i) rb_funcall(o, rb_intern("begin"), 1, i) -#define f_end(o,i) rb_funcall(o, rb_intern("end"), 1, i) -#define f_aset(o,i,v) rb_funcall(o, rb_intern("[]="), 2, i, v) -#define f_aset2(o,i,j,v) rb_funcall(o, rb_intern("[]="), 3, i, j, v) -#define f_sub_bang(s,r,x) rb_funcall(s, rb_intern("sub!"), 2, r, x) -#define f_gsub_bang(s,r,x) rb_funcall(s, rb_intern("gsub!"), 2, r, x) - -#define set_hash(k,v) rb_hash_aset(hash, ID2SYM(rb_intern(k"")), v) -#define ref_hash(k) rb_hash_aref(hash, ID2SYM(rb_intern(k""))) -#define del_hash(k) rb_hash_delete(hash, ID2SYM(rb_intern(k""))) - -#define cstr2num(s) rb_cstr_to_inum(s, 10, 0) -#define str2num(s) rb_str_to_inum(s, 10, 0) - -static const char abbr_days[][4] = { - "sun", "mon", "tue", "wed", - "thu", "fri", "sat" -}; - -static const char abbr_months[][4] = { - "jan", "feb", "mar", "apr", "may", "jun", - "jul", "aug", "sep", "oct", "nov", "dec" -}; - -#define issign(c) ((c) == '-' || (c) == '+') -#define asp_string() rb_str_new(" ", 1) -#ifdef TIGHT_PARSER -#define asuba_string() rb_str_new("\001", 1) -#define asubb_string() rb_str_new("\002", 1) -#define asubw_string() rb_str_new("\027", 1) -#define asubt_string() rb_str_new("\024", 1) -#endif - -static size_t -digit_span(const char *s, const char *e) -{ - size_t i = 0; - while (s + i < e && isdigit((unsigned char)s[i])) i++; - return i; -} - -static void -s3e(VALUE hash, VALUE y, VALUE m, VALUE d, int bc) -{ - VALUE vbuf = 0; - VALUE c = Qnil; - - if (!RB_TYPE_P(m, T_STRING)) - m = f_to_s(m); - - if (!NIL_P(y) && !NIL_P(m) && NIL_P(d)) { - VALUE oy = y; - VALUE om = m; - VALUE od = d; - - y = od; - m = oy; - d = om; - } - - if (NIL_P(y)) { - if (!NIL_P(d) && RSTRING_LEN(d) > 2) { - y = d; - d = Qnil; - } - if (!NIL_P(d) && RSTRING_LEN(d) > 0 && *RSTRING_PTR(d) == '\'') { - y = d; - d = Qnil; - } - } - - if (!NIL_P(y)) { - const char *s, *bp, *ep; - size_t l; - - s = RSTRING_PTR(y); - ep = RSTRING_END(y); - while (s < ep && !issign(*s) && !isdigit((unsigned char)*s)) - s++; - if (s >= ep) goto no_date; - bp = s; - if (issign((unsigned char)*s)) - s++; - l = digit_span(s, ep); - ep = s + l; - if (*ep) { - y = d; - d = rb_str_new(bp, ep - bp); - } - no_date:; - } - - if (!NIL_P(m)) { - const char *s; - - s = RSTRING_PTR(m); - if (*s == '\'' || RSTRING_LEN(m) > 2) { - /* us -> be */ - VALUE oy = y; - VALUE om = m; - VALUE od = d; - - y = om; - m = od; - d = oy; - } - } - - if (!NIL_P(d)) { - const char *s; - - s = RSTRING_PTR(d); - if (*s == '\'' || RSTRING_LEN(d) > 2) { - VALUE oy = y; - VALUE od = d; - - y = od; - d = oy; - } - } - - if (!NIL_P(y)) { - const char *s, *bp, *ep; - int sign = 0; - size_t l; - VALUE iy; - - s = RSTRING_PTR(y); - ep = RSTRING_END(y); - while (s < ep && !issign(*s) && !isdigit((unsigned char)*s)) - s++; - if (s >= ep) goto no_year; - bp = s; - if (issign(*s)) { - s++; - sign = 1; - } - if (sign) - c = Qfalse; - l = digit_span(s, ep); - ep = s + l; - if (l > 2) - c = Qfalse; - { - char *buf; - - buf = ALLOCV_N(char, vbuf, ep - bp + 1); - memcpy(buf, bp, ep - bp); - buf[ep - bp] = '\0'; - iy = cstr2num(buf); - ALLOCV_END(vbuf); - } - set_hash("year", iy); - no_year:; - } - - if (bc) - set_hash("_bc", Qtrue); - - if (!NIL_P(m)) { - const char *s, *bp, *ep; - size_t l; - VALUE im; - - s = RSTRING_PTR(m); - ep = RSTRING_END(m); - while (s < ep && !isdigit((unsigned char)*s)) - s++; - if (s >= ep) goto no_month; - bp = s; - l = digit_span(s, ep); - ep = s + l; - { - char *buf; - - buf = ALLOCV_N(char, vbuf, ep - bp + 1); - memcpy(buf, bp, ep - bp); - buf[ep - bp] = '\0'; - im = cstr2num(buf); - ALLOCV_END(vbuf); - } - set_hash("mon", im); - no_month:; - } - - if (!NIL_P(d)) { - const char *s, *bp, *ep; - size_t l; - VALUE id; - - s = RSTRING_PTR(d); - ep = RSTRING_END(d); - while (s < ep && !isdigit((unsigned char)*s)) - s++; - if (s >= ep) goto no_mday; - bp = s; - l = digit_span(s, ep); - ep = s + l; - { - char *buf; - - buf = ALLOCV_N(char, vbuf, ep - bp + 1); - memcpy(buf, bp, ep - bp); - buf[ep - bp] = '\0'; - id = cstr2num(buf); - ALLOCV_END(vbuf); - } - set_hash("mday", id); - no_mday:; - } - - if (!NIL_P(c)) - set_hash("_comp", c); -} - -#define DAYS "sunday|monday|tuesday|wednesday|thursday|friday|saturday" -#define MONTHS "january|february|march|april|may|june|july|august|september|october|november|december" -#define ABBR_DAYS "sun|mon|tue|wed|thu|fri|sat" -#define ABBR_MONTHS "jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec" - -#define NUMBER "(? n && isspace((unsigned char)s[l - n - 1])); - return n; -} - -static long -shrunk_size(const char *s, long l) -{ - long i, ni; - int sp = 0; - for (i = ni = 0; i < l; ++i) { - if (!isspace((unsigned char)s[i])) { - if (sp) ni++; - sp = 0; - ni++; - } - else { - sp = 1; - } - } - return ni < l ? ni : 0; -} - -static long -shrink_space(char *d, const char *s, long l) -{ - long i, ni; - int sp = 0; - for (i = ni = 0; i < l; ++i) { - if (!isspace((unsigned char)s[i])) { - if (sp) d[ni++] = ' '; - sp = 0; - d[ni++] = s[i]; - } - else { - sp = 1; - } - } - return ni; -} - -VALUE -date_zone_to_diff(VALUE str) -{ - VALUE offset = Qnil; - long l = RSTRING_LEN(str); - const char *s = RSTRING_PTR(str); - - { - int dst = 0; - int w; - - if ((w = str_end_with_word(s, l, "time")) > 0) { - int wtime = w; - l -= w; - if ((w = str_end_with_word(s, l, "standard")) > 0) { - l -= w; - } - else if ((w = str_end_with_word(s, l, "daylight")) > 0) { - l -= w; - dst = 1; - } - else { - l += wtime; - } - } - else if ((w = str_end_with_word(s, l, "dst")) > 0) { - l -= w; - dst = 1; - } - - { - const char *zn = s; - long sl = shrunk_size(s, l); - char shrunk_buff[MAX_WORD_LENGTH]; /* no terminator to be added */ - const struct zone *z = 0; - - if (sl <= 0) { - sl = l; - } - else if (sl <= MAX_WORD_LENGTH) { - char *d = shrunk_buff; - sl = shrink_space(d, s, l); - zn = d; - } - - if (sl > 0 && sl <= MAX_WORD_LENGTH) { - z = zonetab(zn, (unsigned int)sl); - } - - if (z) { - int d = z->offset; - if (dst) - d += 3600; - offset = INT2FIX(d); - goto ok; - } - } - - { - char *p; - int sign = 0; - long hour = 0, min = 0, sec = 0; - - if (l > 3 && - (strncasecmp(s, "gmt", 3) == 0 || - strncasecmp(s, "utc", 3) == 0)) { - s += 3; - l -= 3; - } - if (issign(*s)) { - sign = *s == '-'; - s++; - l--; - -#define out_of_range(v, min, max) ((v) < (min) || (max) < (v)) - hour = STRTOUL(s, &p, 10); - if (*p == ':') { - if (out_of_range(hour, 0, 23)) return Qnil; - s = ++p; - min = STRTOUL(s, &p, 10); - if (out_of_range(min, 0, 59)) return Qnil; - if (*p == ':') { - s = ++p; - sec = STRTOUL(s, &p, 10); - if (out_of_range(sec, 0, 59)) return Qnil; - } - } - else if (*p == ',' || *p == '.') { - /* fractional hour */ - size_t n; - int ov; - /* no over precision for offset; 10**-7 hour = 0.36 - * milliseconds should be enough. */ - const size_t max_digits = 7; /* 36 * 10**7 < 32-bit FIXNUM_MAX */ - - if (out_of_range(hour, 0, 23)) return Qnil; - - n = (s + l) - ++p; - if (n > max_digits) n = max_digits; - sec = ruby_scan_digits(p, n, 10, &n, &ov); - if ((p += n) < s + l && *p >= ('5' + !(sec & 1)) && *p <= '9') { - /* round half to even */ - sec++; - } - sec *= 36; - if (sign) { - hour = -hour; - sec = -sec; - } - if (n <= 2) { - /* HH.nn or HH.n */ - if (n == 1) sec *= 10; - offset = INT2FIX(sec + hour * 3600); - } - else { - VALUE denom = rb_int_positive_pow(10, (int)(n - 2)); - offset = f_add(rb_rational_new(INT2FIX(sec), denom), INT2FIX(hour * 3600)); - if (rb_rational_den(offset) == INT2FIX(1)) { - offset = rb_rational_num(offset); - } - } - goto ok; - } - else if (l > 2) { - size_t n; - int ov; - - if (l >= 1) - hour = ruby_scan_digits(&s[0], 2 - l % 2, 10, &n, &ov); - if (l >= 3) - min = ruby_scan_digits(&s[2 - l % 2], 2, 10, &n, &ov); - if (l >= 5) - sec = ruby_scan_digits(&s[4 - l % 2], 2, 10, &n, &ov); - } - sec += min * 60 + hour * 3600; - if (sign) sec = -sec; - offset = INT2FIX(sec); -#undef out_of_range - } - } - } - RB_GC_GUARD(str); - ok: - return offset; -} - -static int -day_num(VALUE s) -{ - int i; - - for (i = 0; i < (int)sizeof_array(abbr_days); i++) - if (strncasecmp(abbr_days[i], RSTRING_PTR(s), 3) == 0) - break; - return i; -} - -static int -mon_num(VALUE s) -{ - int i; - - for (i = 0; i < (int)sizeof_array(abbr_months); i++) - if (strncasecmp(abbr_months[i], RSTRING_PTR(s), 3) == 0) - break; - return i + 1; -} - -static int -parse_day_cb(VALUE m, VALUE hash) -{ - VALUE s; - - s = rb_reg_nth_match(1, m); - set_hash("wday", INT2FIX(day_num(s))); - return 1; -} - -static int -parse_day(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "\\b(" ABBR_DAYS ")[^-/\\d\\s]*" -#else - "(" VALID_DAYS ")" -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); -#ifndef TIGHT_PARSER - SUBS(str, pat, parse_day_cb); -#else - SUBW(str, pat, parse_day_cb); -#endif -} - -static int -parse_time2_cb(VALUE m, VALUE hash) -{ - VALUE h, min, s, f, p; - - h = rb_reg_nth_match(1, m); - h = str2num(h); - - min = rb_reg_nth_match(2, m); - if (!NIL_P(min)) - min = str2num(min); - - s = rb_reg_nth_match(3, m); - if (!NIL_P(s)) - s = str2num(s); - - f = rb_reg_nth_match(4, m); - - if (!NIL_P(f)) - f = rb_rational_new2(str2num(f), - f_expt(INT2FIX(10), LONG2NUM(RSTRING_LEN(f)))); - - p = rb_reg_nth_match(5, m); - - if (!NIL_P(p)) { - int ih = NUM2INT(h); - ih %= 12; - if (*RSTRING_PTR(p) == 'P' || *RSTRING_PTR(p) == 'p') - ih += 12; - h = INT2FIX(ih); - } - - set_hash("hour", h); - if (!NIL_P(min)) - set_hash("min", min); - if (!NIL_P(s)) - set_hash("sec", s); - if (!NIL_P(f)) - set_hash("sec_fraction", f); - - return 1; -} - -static int -parse_time_cb(VALUE m, VALUE hash) -{ - static const char pat_source[] = - "\\A(\\d+)h?" - "(?:\\s*:?\\s*(\\d+)m?" - "(?:" - "\\s*:?\\s*(\\d+)(?:[,.](\\d+))?s?" - ")?" - ")?" - "(?:\\s*([ap])(?:m\\b|\\.m\\.))?"; - static VALUE pat = Qnil; - VALUE s1, s2; - - s1 = rb_reg_nth_match(1, m); - s2 = rb_reg_nth_match(2, m); - - if (!NIL_P(s2)) - set_hash("zone", s2); - - REGCOMP_I(pat); - - { - VALUE m = f_match(pat, s1); - - if (NIL_P(m)) - return 0; - parse_time2_cb(m, hash); - } - - return 1; -} - -static int -parse_time(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "(" - "" NUMBER "+\\s*" - "(?:" - "(?:" - ":\\s*\\d+" - "(?:" -#ifndef TIGHT_PARSER - "\\s*:\\s*\\d+(?:[,.]\\d*)?" -#else - "\\s*:\\s*\\d+(?:[,.]\\d+)?" -#endif - ")?" - "|" - "h(?:\\s*\\d+m?(?:\\s*\\d+s?)?)?" - ")" - "(?:" - "\\s*" - "[ap](?:m\\b|\\.m\\.)" - ")?" - "|" - "[ap](?:m\\b|\\.m\\.)" - ")" - ")" - "(?:" - "\\s*" - "(" - "(?:gmt|utc?)?[-+]\\d+(?:[,.:]\\d+(?::\\d+)?)?" - "|" - "(?-i:[[:alpha:].\\s]+)(?:standard|daylight)\\stime\\b" - "|" - "(?-i:[[:alpha:]]+)(?:\\sdst)?\\b" - ")" - ")?"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); -#ifndef TIGHT_PARSER - SUBS(str, pat, parse_time_cb); -#else - SUBT(str, pat, parse_time_cb); -#endif -} - -#define BEGIN_ERA "\\b" -#define END_ERA "(?!(? 1) - return 0; - return 1; -} -#endif - -static int -parse_eu_cb(VALUE m, VALUE hash) -{ -#ifndef TIGHT_PARSER - VALUE y, mon, d, b; - - d = rb_reg_nth_match(1, m); - mon = rb_reg_nth_match(2, m); - b = rb_reg_nth_match(3, m); - y = rb_reg_nth_match(4, m); - - mon = INT2FIX(mon_num(mon)); - - s3e(hash, y, mon, d, !NIL_P(b) && - (*RSTRING_PTR(b) == 'B' || - *RSTRING_PTR(b) == 'b')); -#else - VALUE y, mon, d; - - d = rb_reg_nth_match(1, m); - mon = rb_reg_nth_match(2, m); - y = rb_reg_nth_match(3, m); - - if (!check_apost(d, mon, y)) - return 0; - - mon = INT2FIX(mon_num(mon)); - - s3e(hash, y, mon, d, 0); -#endif - return 1; -} - -static int -parse_eu(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifdef TIGHT_PARSER - BOS - FPW_COM FPT_COM -#endif -#ifndef TIGHT_PARSER - "('?" NUMBER "+)[^-\\d\\s]*" -#else - "(\\d+)(?:(?:st|nd|rd|th)\\b)?" -#endif - "\\s*" -#ifndef TIGHT_PARSER - "(" ABBR_MONTHS ")[^-\\d\\s']*" -#else - "(" VALID_MONTHS ")" -#endif - "(?:" - "\\s*" -#ifndef TIGHT_PARSER - "(?:" - BEGIN_ERA - "(c(?:e|\\.e\\.)|b(?:ce|\\.c\\.e\\.)|a(?:d|\\.d\\.)|b(?:c|\\.c\\.))" - END_ERA - ")?" - "\\s*" - "('?-?\\d+(?:(?:st|nd|rd|th)\\b)?)" -#else - "(?:" FPA ")?" - "\\s*" - "([-']?\\d+)" - "\\s*" - "(?:" FPA "|" FPB ")?" -#endif - ")?" -#ifdef TIGHT_PARSER - COM_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_eu_cb); -} - -static int -parse_us_cb(VALUE m, VALUE hash) -{ -#ifndef TIGHT_PARSER - VALUE y, mon, d, b; - - mon = rb_reg_nth_match(1, m); - d = rb_reg_nth_match(2, m); - - b = rb_reg_nth_match(3, m); - y = rb_reg_nth_match(4, m); - - mon = INT2FIX(mon_num(mon)); - - s3e(hash, y, mon, d, !NIL_P(b) && - (*RSTRING_PTR(b) == 'B' || - *RSTRING_PTR(b) == 'b')); -#else - VALUE y, mon, d; - - mon = rb_reg_nth_match(1, m); - d = rb_reg_nth_match(2, m); - y = rb_reg_nth_match(3, m); - - if (!check_apost(mon, d, y)) - return 0; - - mon = INT2FIX(mon_num(mon)); - - s3e(hash, y, mon, d, 0); -#endif - return 1; -} - -static int -parse_us(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifdef TIGHT_PARSER - BOS - FPW_COM FPT_COM -#endif -#ifndef TIGHT_PARSER - "\\b(" ABBR_MONTHS ")[^-\\d\\s']*" -#else - "\\b(" VALID_MONTHS ")" -#endif - "\\s*" -#ifndef TIGHT_PARSER - "('?\\d+)[^-\\d\\s']*" -#else - "('?\\d+)(?:(?:st|nd|rd|th)\\b)?" - COM_FPT -#endif - "(?:" - "\\s*+,?" - "\\s*+" -#ifndef TIGHT_PARSER - "(c(?:e|\\.e\\.)|b(?:ce|\\.c\\.e\\.)|a(?:d|\\.d\\.)|b(?:c|\\.c\\.))?" - "\\s*" - "('?-?\\d+)" -#else - "(?:" FPA ")?" - "\\s*" - "([-']?\\d+)" - "\\s*" - "(?:" FPA "|" FPB ")?" -#endif - ")?" -#ifdef TIGHT_PARSER - COM_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_us_cb); -} - -static int -parse_iso_cb(VALUE m, VALUE hash) -{ - VALUE y, mon, d; - - y = rb_reg_nth_match(1, m); - mon = rb_reg_nth_match(2, m); - d = rb_reg_nth_match(3, m); - -#ifdef TIGHT_PARSER - if (!check_apost(y, mon, d)) - return 0; -#endif - - s3e(hash, y, mon, d, 0); - return 1; -} - -static int -parse_iso(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "('?[-+]?" NUMBER "+)-(\\d+)-('?-?\\d+)" -#else - BOS - FPW_COM FPT_COM - "([-+']?\\d+)-(\\d+)-([-']?\\d+)" - TEE_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_0(pat); - SUBS(str, pat, parse_iso_cb); -} - -static int -parse_iso21_cb(VALUE m, VALUE hash) -{ - VALUE y, w, d; - - y = rb_reg_nth_match(1, m); - w = rb_reg_nth_match(2, m); - d = rb_reg_nth_match(3, m); - - if (!NIL_P(y)) - set_hash("cwyear", str2num(y)); - set_hash("cweek", str2num(w)); - if (!NIL_P(d)) - set_hash("cwday", str2num(d)); - - return 1; -} - -static int -parse_iso21(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "\\b(\\d{2}|\\d{4})?-?w(\\d{2})(?:-?(\\d))?\\b" -#else - BOS - FPW_COM FPT_COM - "(\\d{2}|\\d{4})?-?w(\\d{2})(?:-?(\\d))?" - TEE_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_iso21_cb); -} - -static int -parse_iso22_cb(VALUE m, VALUE hash) -{ - VALUE d; - - d = rb_reg_nth_match(1, m); - set_hash("cwday", str2num(d)); - return 1; -} - -static int -parse_iso22(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "-w-(\\d)\\b" -#else - BOS - FPW_COM FPT_COM - "-w-(\\d)" - TEE_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_iso22_cb); -} - -static int -parse_iso23_cb(VALUE m, VALUE hash) -{ - VALUE mon, d; - - mon = rb_reg_nth_match(1, m); - d = rb_reg_nth_match(2, m); - - if (!NIL_P(mon)) - set_hash("mon", str2num(mon)); - set_hash("mday", str2num(d)); - - return 1; -} - -static int -parse_iso23(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "--(\\d{2})?-(\\d{2})\\b" -#else - BOS - FPW_COM FPT_COM - "--(\\d{2})?-(\\d{2})" - TEE_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_0(pat); - SUBS(str, pat, parse_iso23_cb); -} - -static int -parse_iso24_cb(VALUE m, VALUE hash) -{ - VALUE mon, d; - - mon = rb_reg_nth_match(1, m); - d = rb_reg_nth_match(2, m); - - set_hash("mon", str2num(mon)); - if (!NIL_P(d)) - set_hash("mday", str2num(d)); - - return 1; -} - -static int -parse_iso24(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "--(\\d{2})(\\d{2})?\\b" -#else - BOS - FPW_COM FPT_COM - "--(\\d{2})(\\d{2})?" - TEE_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_0(pat); - SUBS(str, pat, parse_iso24_cb); -} - -static int -parse_iso25_cb(VALUE m, VALUE hash) -{ - VALUE y, d; - - y = rb_reg_nth_match(1, m); - d = rb_reg_nth_match(2, m); - - set_hash("year", str2num(y)); - set_hash("yday", str2num(d)); - - return 1; -} - -static int -parse_iso25(VALUE str, VALUE hash) -{ - static const char pat0_source[] = -#ifndef TIGHT_PARSER - "[,.](\\d{2}|\\d{4})-\\d{3}\\b" -#else - BOS - FPW_COM FPT_COM - "[,.](\\d{2}|\\d{4})-\\d{3}" - TEE_FPT COM_FPW - EOS -#endif - ; - static VALUE pat0 = Qnil; - static const char pat_source[] = -#ifndef TIGHT_PARSER - "\\b(\\d{2}|\\d{4})-(\\d{3})\\b" -#else - BOS - FPW_COM FPT_COM - "(\\d{2}|\\d{4})-(\\d{3})" - TEE_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_0(pat0); - REGCOMP_0(pat); - - if (!NIL_P(f_match(pat0, str))) - return 0; - SUBS(str, pat, parse_iso25_cb); -} - -static int -parse_iso26_cb(VALUE m, VALUE hash) -{ - VALUE d; - - d = rb_reg_nth_match(1, m); - set_hash("yday", str2num(d)); - - return 1; -} -static int -parse_iso26(VALUE str, VALUE hash) -{ - static const char pat0_source[] = -#ifndef TIGHT_PARSER - "\\d-\\d{3}\\b" -#else - BOS - FPW_COM FPT_COM - "\\d-\\d{3}" - TEE_FPT COM_FPW - EOS -#endif - ; - static VALUE pat0 = Qnil; - static const char pat_source[] = -#ifndef TIGHT_PARSER - "\\b-(\\d{3})\\b" -#else - BOS - FPW_COM FPT_COM - "-(\\d{3})" - TEE_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_0(pat0); - REGCOMP_0(pat); - - if (!NIL_P(f_match(pat0, str))) - return 0; - SUBS(str, pat, parse_iso26_cb); -} - -static int -parse_iso2(VALUE str, VALUE hash) -{ - if (parse_iso21(str, hash)) - goto ok; - if (parse_iso22(str, hash)) - goto ok; - if (parse_iso23(str, hash)) - goto ok; - if (parse_iso24(str, hash)) - goto ok; - if (parse_iso25(str, hash)) - goto ok; - if (parse_iso26(str, hash)) - goto ok; - return 0; - - ok: - return 1; -} - -#define JISX0301_ERA_INITIALS "mtshr" -#define JISX0301_DEFAULT_ERA 'H' /* obsolete */ - -static int -gengo(int c) -{ - int e; - - switch (c) { - case 'M': case 'm': e = 1867; break; - case 'T': case 't': e = 1911; break; - case 'S': case 's': e = 1925; break; - case 'H': case 'h': e = 1988; break; - case 'R': case 'r': e = 2018; break; - default: e = 0; break; - } - return e; -} - -static int -parse_jis_cb(VALUE m, VALUE hash) -{ - VALUE e, y, mon, d; - int ep; - - e = rb_reg_nth_match(1, m); - y = rb_reg_nth_match(2, m); - mon = rb_reg_nth_match(3, m); - d = rb_reg_nth_match(4, m); - - ep = gengo(*RSTRING_PTR(e)); - - set_hash("year", f_add(str2num(y), INT2FIX(ep))); - set_hash("mon", str2num(mon)); - set_hash("mday", str2num(d)); - - return 1; -} - -static int -parse_jis(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "\\b([" JISX0301_ERA_INITIALS "])(\\d+)\\.(\\d+)\\.(\\d+)" -#else - BOS - FPW_COM FPT_COM - "([" JISX0301_ERA_INITIALS "])(\\d+)\\.(\\d+)\\.(\\d+)" - TEE_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_jis_cb); -} - -static int -parse_vms11_cb(VALUE m, VALUE hash) -{ - VALUE y, mon, d; - - d = rb_reg_nth_match(1, m); - mon = rb_reg_nth_match(2, m); - y = rb_reg_nth_match(3, m); - -#ifdef TIGHT_PARSER - if (!check_apost(d, mon, y)) - return 0; -#endif - - mon = INT2FIX(mon_num(mon)); - - s3e(hash, y, mon, d, 0); - return 1; -} - -static int -parse_vms11(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "('?-?" NUMBER "+)-(" ABBR_MONTHS ")[^-/.]*" - "-('?-?\\d+)" -#else - BOS - FPW_COM FPT_COM - "([-']?\\d+)-(" DOTLESS_VALID_MONTHS ")" - "-([-']?\\d+)" - COM_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_vms11_cb); -} - -static int -parse_vms12_cb(VALUE m, VALUE hash) -{ - VALUE y, mon, d; - - mon = rb_reg_nth_match(1, m); - d = rb_reg_nth_match(2, m); - y = rb_reg_nth_match(3, m); - -#ifdef TIGHT_PARSER - if (!check_apost(mon, d, y)) - return 0; -#endif - - mon = INT2FIX(mon_num(mon)); - - s3e(hash, y, mon, d, 0); - return 1; -} - -static int -parse_vms12(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "\\b(" ABBR_MONTHS ")[^-/.]*" - "-('?-?\\d+)(?:-('?-?\\d+))?" -#else - BOS - FPW_COM FPT_COM - "(" DOTLESS_VALID_MONTHS ")" - "-([-']?\\d+)(?:-([-']?\\d+))?" - COM_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_vms12_cb); -} - -static int -parse_vms(VALUE str, VALUE hash) -{ - if (parse_vms11(str, hash)) - goto ok; - if (parse_vms12(str, hash)) - goto ok; - return 0; - - ok: - return 1; -} - -static int -parse_sla_cb(VALUE m, VALUE hash) -{ - VALUE y, mon, d; - - y = rb_reg_nth_match(1, m); - mon = rb_reg_nth_match(2, m); - d = rb_reg_nth_match(3, m); - -#ifdef TIGHT_PARSER - if (!check_apost(y, mon, d)) - return 0; -#endif - - s3e(hash, y, mon, d, 0); - return 1; -} - -static int -parse_sla(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "('?-?" NUMBER "+)/\\s*('?\\d+)(?:\\D\\s*('?-?\\d+))?" -#else - BOS - FPW_COM FPT_COM - "([-']?\\d+)/\\s*('?\\d+)(?:(?:[-/]|\\s+)\\s*([-']?\\d+))?" - COM_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_sla_cb); -} - -#ifdef TIGHT_PARSER -static int -parse_sla2_cb(VALUE m, VALUE hash) -{ - VALUE y, mon, d; - - d = rb_reg_nth_match(1, m); - mon = rb_reg_nth_match(2, m); - y = rb_reg_nth_match(3, m); - - if (!check_apost(d, mon, y)) - return 0; - - mon = INT2FIX(mon_num(mon)); - - s3e(hash, y, mon, d, 0); - return 1; -} - -static int -parse_sla2(VALUE str, VALUE hash) -{ - static const char pat_source[] = - BOS - FPW_COM FPT_COM - "([-']?\\d+)/\\s*(" DOTLESS_VALID_MONTHS ")(?:(?:[-/]|\\s+)\\s*([-']?\\d+))?" - COM_FPT COM_FPW - EOS - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_sla2_cb); -} - -static int -parse_sla3_cb(VALUE m, VALUE hash) -{ - VALUE y, mon, d; - - mon = rb_reg_nth_match(1, m); - d = rb_reg_nth_match(2, m); - y = rb_reg_nth_match(3, m); - - if (!check_apost(mon, d, y)) - return 0; - - mon = INT2FIX(mon_num(mon)); - - s3e(hash, y, mon, d, 0); - return 1; -} - -static int -parse_sla3(VALUE str, VALUE hash) -{ - static const char pat_source[] = - BOS - FPW_COM FPT_COM - "(" DOTLESS_VALID_MONTHS ")/\\s*([-']?\\d+)(?:(?:[-/]|\\s+)\\s*([-']?\\d+))?" - COM_FPT COM_FPW - EOS - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_sla3_cb); -} -#endif - -static int -parse_dot_cb(VALUE m, VALUE hash) -{ - VALUE y, mon, d; - - y = rb_reg_nth_match(1, m); - mon = rb_reg_nth_match(2, m); - d = rb_reg_nth_match(3, m); - -#ifdef TIGHT_PARSER - if (!check_apost(y, mon, d)) - return 0; -#endif - - s3e(hash, y, mon, d, 0); - return 1; -} - -static int -parse_dot(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "('?-?" NUMBER "+)\\.\\s*('?\\d+)\\.\\s*('?-?\\d+)" -#else - BOS - FPW_COM FPT_COM - "([-']?\\d+)\\.\\s*(\\d+)\\.\\s*([-']?\\d+)" - COM_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_dot_cb); -} - -#ifdef TIGHT_PARSER -static int -parse_dot2_cb(VALUE m, VALUE hash) -{ - VALUE y, mon, d; - - d = rb_reg_nth_match(1, m); - mon = rb_reg_nth_match(2, m); - y = rb_reg_nth_match(3, m); - - if (!check_apost(d, mon, y)) - return 0; - - mon = INT2FIX(mon_num(mon)); - - s3e(hash, y, mon, d, 0); - return 1; -} - -static int -parse_dot2(VALUE str, VALUE hash) -{ - static const char pat_source[] = - BOS - FPW_COM FPT_COM - "([-']?\\d+)\\.\\s*(" DOTLESS_VALID_MONTHS ")(?:(?:[./])\\s*([-']?\\d+))?" - COM_FPT COM_FPW - EOS - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_dot2_cb); -} - -static int -parse_dot3_cb(VALUE m, VALUE hash) -{ - VALUE y, mon, d; - - mon = rb_reg_nth_match(1, m); - d = rb_reg_nth_match(2, m); - y = rb_reg_nth_match(3, m); - - if (!check_apost(mon, d, y)) - return 0; - - mon = INT2FIX(mon_num(mon)); - - s3e(hash, y, mon, d, 0); - return 1; -} - -static int -parse_dot3(VALUE str, VALUE hash) -{ - static const char pat_source[] = - BOS - FPW_COM FPT_COM - "(" DOTLESS_VALID_MONTHS ")\\.\\s*([-']?\\d+)(?:(?:[./])\\s*([-']?\\d+))?" - COM_FPT COM_FPW - EOS - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_dot3_cb); -} -#endif - -static int -parse_year_cb(VALUE m, VALUE hash) -{ - VALUE y; - - y = rb_reg_nth_match(1, m); - set_hash("year", str2num(y)); - return 1; -} - -static int -parse_year(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "'(\\d+)\\b" -#else - BOS - FPW_COM FPT_COM - "'(\\d+)" - COM_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_0(pat); - SUBS(str, pat, parse_year_cb); -} - -static int -parse_mon_cb(VALUE m, VALUE hash) -{ - VALUE mon; - - mon = rb_reg_nth_match(1, m); - set_hash("mon", INT2FIX(mon_num(mon))); - return 1; -} - -static int -parse_mon(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "\\b(" ABBR_MONTHS ")\\S*" -#else - BOS - FPW_COM FPT_COM - "(" VALID_MONTHS ")" - COM_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_mon_cb); -} - -static int -parse_mday_cb(VALUE m, VALUE hash) -{ - VALUE d; - - d = rb_reg_nth_match(1, m); - set_hash("mday", str2num(d)); - return 1; -} - -static int -parse_mday(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifndef TIGHT_PARSER - "(" NUMBER "+)(st|nd|rd|th)\\b" -#else - BOS - FPW_COM FPT_COM - "(\\d+)(st|nd|rd|th)" - COM_FPT COM_FPW - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_mday_cb); -} - -static int -n2i(const char *s, long f, long w) -{ - long e, i; - int v; - - e = f + w; - v = 0; - for (i = f; i < e; i++) { - v *= 10; - v += s[i] - '0'; - } - return v; -} - -static int -parse_ddd_cb(VALUE m, VALUE hash) -{ - VALUE s1, s2, s3, s4, s5; - const char *cs2, *cs3, *cs5; - long l2, l3, l4, l5; - - s1 = rb_reg_nth_match(1, m); - s2 = rb_reg_nth_match(2, m); - s3 = rb_reg_nth_match(3, m); - s4 = rb_reg_nth_match(4, m); - s5 = rb_reg_nth_match(5, m); - - cs2 = RSTRING_PTR(s2); - l2 = RSTRING_LEN(s2); - - switch (l2) { - case 2: - if (NIL_P(s3) && !NIL_P(s4)) - set_hash("sec", INT2FIX(n2i(cs2, l2-2, 2))); - else - set_hash("mday", INT2FIX(n2i(cs2, 0, 2))); - break; - case 4: - if (NIL_P(s3) && !NIL_P(s4)) { - set_hash("sec", INT2FIX(n2i(cs2, l2-2, 2))); - set_hash("min", INT2FIX(n2i(cs2, l2-4, 2))); - } - else { - set_hash("mon", INT2FIX(n2i(cs2, 0, 2))); - set_hash("mday", INT2FIX(n2i(cs2, 2, 2))); - } - break; - case 6: - if (NIL_P(s3) && !NIL_P(s4)) { - set_hash("sec", INT2FIX(n2i(cs2, l2-2, 2))); - set_hash("min", INT2FIX(n2i(cs2, l2-4, 2))); - set_hash("hour", INT2FIX(n2i(cs2, l2-6, 2))); - } - else { - int y = n2i(cs2, 0, 2); - if (!NIL_P(s1) && *RSTRING_PTR(s1) == '-') - y = -y; - set_hash("year", INT2FIX(y)); - set_hash("mon", INT2FIX(n2i(cs2, 2, 2))); - set_hash("mday", INT2FIX(n2i(cs2, 4, 2))); - } - break; - case 8: - case 10: - case 12: - case 14: - if (NIL_P(s3) && !NIL_P(s4)) { - set_hash("sec", INT2FIX(n2i(cs2, l2-2, 2))); - set_hash("min", INT2FIX(n2i(cs2, l2-4, 2))); - set_hash("hour", INT2FIX(n2i(cs2, l2-6, 2))); - set_hash("mday", INT2FIX(n2i(cs2, l2-8, 2))); - if (l2 >= 10) - set_hash("mon", INT2FIX(n2i(cs2, l2-10, 2))); - if (l2 == 12) { - int y = n2i(cs2, l2-12, 2); - if (!NIL_P(s1) && *RSTRING_PTR(s1) == '-') - y = -y; - set_hash("year", INT2FIX(y)); - } - if (l2 == 14) { - int y = n2i(cs2, l2-14, 4); - if (!NIL_P(s1) && *RSTRING_PTR(s1) == '-') - y = -y; - set_hash("year", INT2FIX(y)); - set_hash("_comp", Qfalse); - } - } - else { - int y = n2i(cs2, 0, 4); - if (!NIL_P(s1) && *RSTRING_PTR(s1) == '-') - y = -y; - set_hash("year", INT2FIX(y)); - set_hash("mon", INT2FIX(n2i(cs2, 4, 2))); - set_hash("mday", INT2FIX(n2i(cs2, 6, 2))); - if (l2 >= 10) - set_hash("hour", INT2FIX(n2i(cs2, 8, 2))); - if (l2 >= 12) - set_hash("min", INT2FIX(n2i(cs2, 10, 2))); - if (l2 >= 14) - set_hash("sec", INT2FIX(n2i(cs2, 12, 2))); - set_hash("_comp", Qfalse); - } - break; - case 3: - if (NIL_P(s3) && !NIL_P(s4)) { - set_hash("sec", INT2FIX(n2i(cs2, l2-2, 2))); - set_hash("min", INT2FIX(n2i(cs2, l2-3, 1))); - } - else - set_hash("yday", INT2FIX(n2i(cs2, 0, 3))); - break; - case 5: - if (NIL_P(s3) && !NIL_P(s4)) { - set_hash("sec", INT2FIX(n2i(cs2, l2-2, 2))); - set_hash("min", INT2FIX(n2i(cs2, l2-4, 2))); - set_hash("hour", INT2FIX(n2i(cs2, l2-5, 1))); - } - else { - int y = n2i(cs2, 0, 2); - if (!NIL_P(s1) && *RSTRING_PTR(s1) == '-') - y = -y; - set_hash("year", INT2FIX(y)); - set_hash("yday", INT2FIX(n2i(cs2, 2, 3))); - } - break; - case 7: - if (NIL_P(s3) && !NIL_P(s4)) { - set_hash("sec", INT2FIX(n2i(cs2, l2-2, 2))); - set_hash("min", INT2FIX(n2i(cs2, l2-4, 2))); - set_hash("hour", INT2FIX(n2i(cs2, l2-6, 2))); - set_hash("mday", INT2FIX(n2i(cs2, l2-7, 1))); - } - else { - int y = n2i(cs2, 0, 4); - if (!NIL_P(s1) && *RSTRING_PTR(s1) == '-') - y = -y; - set_hash("year", INT2FIX(y)); - set_hash("yday", INT2FIX(n2i(cs2, 4, 3))); - } - break; - } - RB_GC_GUARD(s2); - if (!NIL_P(s3)) { - cs3 = RSTRING_PTR(s3); - l3 = RSTRING_LEN(s3); - - if (!NIL_P(s4)) { - switch (l3) { - case 2: - case 4: - case 6: - set_hash("sec", INT2FIX(n2i(cs3, l3-2, 2))); - if (l3 >= 4) - set_hash("min", INT2FIX(n2i(cs3, l3-4, 2))); - if (l3 >= 6) - set_hash("hour", INT2FIX(n2i(cs3, l3-6, 2))); - break; - } - } - else { - switch (l3) { - case 2: - case 4: - case 6: - set_hash("hour", INT2FIX(n2i(cs3, 0, 2))); - if (l3 >= 4) - set_hash("min", INT2FIX(n2i(cs3, 2, 2))); - if (l3 >= 6) - set_hash("sec", INT2FIX(n2i(cs3, 4, 2))); - break; - } - } - RB_GC_GUARD(s3); - } - if (!NIL_P(s4)) { - l4 = RSTRING_LEN(s4); - - set_hash("sec_fraction", - rb_rational_new2(str2num(s4), - f_expt(INT2FIX(10), LONG2NUM(l4)))); - } - if (!NIL_P(s5)) { - cs5 = RSTRING_PTR(s5); - l5 = RSTRING_LEN(s5); - - set_hash("zone", s5); - - if (*cs5 == '[') { - const char *s1, *s2; - VALUE zone; - - l5 -= 2; - s1 = cs5 + 1; - s2 = memchr(s1, ':', l5); - if (s2) { - s2++; - zone = rb_str_subseq(s5, s2 - cs5, l5 - (s2 - s1)); - s5 = rb_str_subseq(s5, 1, s2 - s1); - } - else { - zone = rb_str_subseq(s5, 1, l5); - if (isdigit((unsigned char)*s1)) - s5 = rb_str_append(rb_str_new_cstr("+"), zone); - else - s5 = zone; - } - set_hash("zone", zone); - set_hash("offset", date_zone_to_diff(s5)); - } - RB_GC_GUARD(s5); - } - - return 1; -} - -static int -parse_ddd(VALUE str, VALUE hash) -{ - static const char pat_source[] = -#ifdef TIGHT_PARSER - BOS -#endif - "([-+]?)(" NUMBER "{2,14})" - "(?:" - "\\s*" - "t?" - "\\s*" - "(\\d{2,6})?(?:[,.](\\d*))?" - ")?" - "(?:" - "\\s*" - "(" - "z\\b" - "|" - "[-+]\\d{1,4}\\b" - "|" - "\\[[-+]?\\d[^\\]]*\\]" - ")" - ")?" -#ifdef TIGHT_PARSER - EOS -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_ddd_cb); -} - -#ifndef TIGHT_PARSER -static int -parse_bc_cb(VALUE m, VALUE hash) -{ - set_hash("_bc", Qtrue); - return 1; -} - -static int -parse_bc(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\b(bc\\b|bce\\b|b\\.c\\.|b\\.c\\.e\\.)"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_bc_cb); -} - -static int -parse_frag_cb(VALUE m, VALUE hash) -{ - VALUE s, n; - - s = rb_reg_nth_match(1, m); - - if (!NIL_P(ref_hash("hour")) && NIL_P(ref_hash("mday"))) { - n = str2num(s); - if (f_ge_p(n, INT2FIX(1)) && - f_le_p(n, INT2FIX(31))) - set_hash("mday", n); - } - if (!NIL_P(ref_hash("mday")) && NIL_P(ref_hash("hour"))) { - n = str2num(s); - if (f_ge_p(n, INT2FIX(0)) && - f_le_p(n, INT2FIX(24))) - set_hash("hour", n); - } - - return 1; -} - -static int -parse_frag(VALUE str, VALUE hash) -{ - static const char pat_source[] = "\\A\\s*(\\d{1,2})\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - SUBS(str, pat, parse_frag_cb); -} -#endif - -#ifdef TIGHT_PARSER -static int -parse_dummy_cb(VALUE m, VALUE hash) -{ - return 1; -} - -static int -parse_wday_only(VALUE str, VALUE hash) -{ - static const char pat_source[] = "\\A\\s*" FPW "\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_0(pat); - SUBS(str, pat, parse_dummy_cb); -} - -static int -parse_time_only(VALUE str, VALUE hash) -{ - static const char pat_source[] = "\\A\\s*" FPT "\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_0(pat); - SUBS(str, pat, parse_dummy_cb); -} - -static int -parse_wday_and_time(VALUE str, VALUE hash) -{ - static const char pat_source[] = "\\A\\s*(" FPW "\\s+" FPT "|" FPT "\\s+" FPW ")\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_0(pat); - SUBS(str, pat, parse_dummy_cb); -} - -static unsigned -have_invalid_char_p(VALUE s) -{ - long i; - - for (i = 0; i < RSTRING_LEN(s); i++) - if (iscntrl((unsigned char)RSTRING_PTR(s)[i]) && - !isspace((unsigned char)RSTRING_PTR(s)[i])) - return 1; - return 0; -} -#endif - -#define HAVE_ALPHA (1<<0) -#define HAVE_DIGIT (1<<1) -#define HAVE_DASH (1<<2) -#define HAVE_DOT (1<<3) -#define HAVE_SLASH (1<<4) - -static unsigned -check_class(VALUE s) -{ - unsigned flags; - long i; - - flags = 0; - for (i = 0; i < RSTRING_LEN(s); i++) { - if (isalpha((unsigned char)RSTRING_PTR(s)[i])) - flags |= HAVE_ALPHA; - if (isdigit((unsigned char)RSTRING_PTR(s)[i])) - flags |= HAVE_DIGIT; - if (RSTRING_PTR(s)[i] == '-') - flags |= HAVE_DASH; - if (RSTRING_PTR(s)[i] == '.') - flags |= HAVE_DOT; - if (RSTRING_PTR(s)[i] == '/') - flags |= HAVE_SLASH; - } - return flags; -} - -#define HAVE_ELEM_P(x) ((check_class(str) & (x)) == (x)) - -#ifdef TIGHT_PARSER -#define PARSER_ERROR return rb_hash_new() -#endif - -VALUE -date__parse(VALUE str, VALUE comp) -{ - VALUE backref, hash; - -#ifdef TIGHT_PARSER - if (have_invalid_char_p(str)) - PARSER_ERROR; -#endif - - backref = rb_backref_get(); - rb_match_busy(backref); - - { - static const char pat_source[] = -#ifndef TIGHT_PARSER - "[^-+',./:@[:alnum:]\\[\\]]+" -#else - "[^[:graph:]]+" -#endif - ; - static VALUE pat = Qnil; - - REGCOMP_0(pat); - str = rb_str_dup(str); - f_gsub_bang(str, pat, asp_string()); - } - - hash = rb_hash_new(); - set_hash("_comp", comp); - - if (HAVE_ELEM_P(HAVE_ALPHA)) - parse_day(str, hash); - if (HAVE_ELEM_P(HAVE_DIGIT)) - parse_time(str, hash); - -#ifdef TIGHT_PARSER - if (HAVE_ELEM_P(HAVE_ALPHA)) - parse_era(str, hash); -#endif - - if (HAVE_ELEM_P(HAVE_ALPHA|HAVE_DIGIT)) { - if (parse_eu(str, hash)) - goto ok; - if (parse_us(str, hash)) - goto ok; - } - if (HAVE_ELEM_P(HAVE_DIGIT|HAVE_DASH)) - if (parse_iso(str, hash)) - goto ok; - if (HAVE_ELEM_P(HAVE_DIGIT|HAVE_DOT)) - if (parse_jis(str, hash)) - goto ok; - if (HAVE_ELEM_P(HAVE_ALPHA|HAVE_DIGIT|HAVE_DASH)) - if (parse_vms(str, hash)) - goto ok; - if (HAVE_ELEM_P(HAVE_DIGIT|HAVE_SLASH)) - if (parse_sla(str, hash)) - goto ok; -#ifdef TIGHT_PARSER - if (HAVE_ELEM_P(HAVE_ALPHA|HAVE_DIGIT|HAVE_SLASH)) { - if (parse_sla2(str, hash)) - goto ok; - if (parse_sla3(str, hash)) - goto ok; - } -#endif - if (HAVE_ELEM_P(HAVE_DIGIT|HAVE_DOT)) - if (parse_dot(str, hash)) - goto ok; -#ifdef TIGHT_PARSER - if (HAVE_ELEM_P(HAVE_ALPHA|HAVE_DIGIT|HAVE_DOT)) { - if (parse_dot2(str, hash)) - goto ok; - if (parse_dot3(str, hash)) - goto ok; - } -#endif - if (HAVE_ELEM_P(HAVE_DIGIT)) - if (parse_iso2(str, hash)) - goto ok; - if (HAVE_ELEM_P(HAVE_DIGIT)) - if (parse_year(str, hash)) - goto ok; - if (HAVE_ELEM_P(HAVE_ALPHA)) - if (parse_mon(str, hash)) - goto ok; - if (HAVE_ELEM_P(HAVE_DIGIT)) - if (parse_mday(str, hash)) - goto ok; - if (HAVE_ELEM_P(HAVE_DIGIT)) - if (parse_ddd(str, hash)) - goto ok; - -#ifdef TIGHT_PARSER - if (parse_wday_only(str, hash)) - goto ok; - if (parse_time_only(str, hash)) - goto ok; - if (parse_wday_and_time(str, hash)) - goto ok; - - PARSER_ERROR; /* not found */ -#endif - - ok: -#ifndef TIGHT_PARSER - if (HAVE_ELEM_P(HAVE_ALPHA)) - parse_bc(str, hash); - if (HAVE_ELEM_P(HAVE_DIGIT)) - parse_frag(str, hash); -#endif - - { - if (RTEST(del_hash("_bc"))) { - VALUE y; - - y = ref_hash("cwyear"); - if (!NIL_P(y)) { - y = f_add(f_negate(y), INT2FIX(1)); - set_hash("cwyear", y); - } - y = ref_hash("year"); - if (!NIL_P(y)) { - y = f_add(f_negate(y), INT2FIX(1)); - set_hash("year", y); - } - } - - if (RTEST(del_hash("_comp"))) { - VALUE y; - - y = ref_hash("cwyear"); - if (!NIL_P(y)) - if (f_ge_p(y, INT2FIX(0)) && f_le_p(y, INT2FIX(99))) { - if (f_ge_p(y, INT2FIX(69))) - set_hash("cwyear", f_add(y, INT2FIX(1900))); - else - set_hash("cwyear", f_add(y, INT2FIX(2000))); - } - y = ref_hash("year"); - if (!NIL_P(y)) - if (f_ge_p(y, INT2FIX(0)) && f_le_p(y, INT2FIX(99))) { - if (f_ge_p(y, INT2FIX(69))) - set_hash("year", f_add(y, INT2FIX(1900))); - else - set_hash("year", f_add(y, INT2FIX(2000))); - } - } - - } - - { - VALUE zone = ref_hash("zone"); - if (!NIL_P(zone) && NIL_P(ref_hash("offset"))) - set_hash("offset", date_zone_to_diff(zone)); - } - - rb_backref_set(backref); - - return hash; -} - -static VALUE -comp_year69(VALUE y) -{ - if (f_ge_p(y, INT2FIX(69))) - return f_add(y, INT2FIX(1900)); - return f_add(y, INT2FIX(2000)); -} - -static VALUE -comp_year50(VALUE y) -{ - if (f_ge_p(y, INT2FIX(50))) - return f_add(y, INT2FIX(1900)); - return f_add(y, INT2FIX(2000)); -} - -static VALUE -sec_fraction(VALUE f) -{ - return rb_rational_new2(str2num(f), - f_expt(INT2FIX(10), - LONG2NUM(RSTRING_LEN(f)))); -} - -#define SNUM 14 - -static int -iso8601_ext_datetime_cb(VALUE m, VALUE hash) -{ - VALUE s[SNUM + 1], y; - - { - int i; - s[0] = Qnil; - for (i = 1; i <= SNUM; i++) - s[i] = rb_reg_nth_match(i, m); - } - - if (!NIL_P(s[1])) { - if (!NIL_P(s[3])) set_hash("mday", str2num(s[3])); - if (strcmp(RSTRING_PTR(s[1]), "-") != 0) { - y = str2num(s[1]); - if (RSTRING_LEN(s[1]) < 4) - y = comp_year69(y); - set_hash("year", y); - } - if (NIL_P(s[2])) { - if (strcmp(RSTRING_PTR(s[1]), "-") != 0) - return 0; - } - else - set_hash("mon", str2num(s[2])); - } - else if (!NIL_P(s[5])) { - set_hash("yday", str2num(s[5])); - if (!NIL_P(s[4])) { - y = str2num(s[4]); - if (RSTRING_LEN(s[4]) < 4) - y = comp_year69(y); - set_hash("year", y); - } - } - else if (!NIL_P(s[8])) { - set_hash("cweek", str2num(s[7])); - set_hash("cwday", str2num(s[8])); - if (!NIL_P(s[6])) { - y = str2num(s[6]); - if (RSTRING_LEN(s[6]) < 4) - y = comp_year69(y); - set_hash("cwyear", y); - } - } - else if (!NIL_P(s[9])) { - set_hash("cwday", str2num(s[9])); - } - if (!NIL_P(s[10])) { - set_hash("hour", str2num(s[10])); - set_hash("min", str2num(s[11])); - if (!NIL_P(s[12])) - set_hash("sec", str2num(s[12])); - } - if (!NIL_P(s[13])) { - set_hash("sec_fraction", sec_fraction(s[13])); - } - if (!NIL_P(s[14])) { - set_hash("zone", s[14]); - set_hash("offset", date_zone_to_diff(s[14])); - } - - return 1; -} - -static int -iso8601_ext_datetime(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\A\\s*(?:([-+]?\\d{2,}|-)-(\\d{2})?(?:-(\\d{2}))?|" - "([-+]?\\d{2,})?-(\\d{3})|" - "(\\d{4}|\\d{2})?-w(\\d{2})-(\\d)|" - "-w-(\\d))" - "(?:t" - "(\\d{2}):(\\d{2})(?::(\\d{2})(?:[,.](\\d+))?)?" - "(z|[-+]\\d{2}(?::?\\d{2})?)?)?\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - MATCH(str, pat, iso8601_ext_datetime_cb); -} - -#undef SNUM -#define SNUM 17 - -static int -iso8601_bas_datetime_cb(VALUE m, VALUE hash) -{ - VALUE s[SNUM + 1], y; - - { - int i; - s[0] = Qnil; - for (i = 1; i <= SNUM; i++) - s[i] = rb_reg_nth_match(i, m); - } - - if (!NIL_P(s[3])) { - set_hash("mday", str2num(s[3])); - if (strcmp(RSTRING_PTR(s[1]), "--") != 0) { - y = str2num(s[1]); - if (RSTRING_LEN(s[1]) < 4) - y = comp_year69(y); - set_hash("year", y); - } - if (*RSTRING_PTR(s[2]) == '-') { - if (strcmp(RSTRING_PTR(s[1]), "--") != 0) - return 0; - } - else - set_hash("mon", str2num(s[2])); - } - else if (!NIL_P(s[5])) { - set_hash("yday", str2num(s[5])); - y = str2num(s[4]); - if (RSTRING_LEN(s[4]) < 4) - y = comp_year69(y); - set_hash("year", y); - } - else if (!NIL_P(s[6])) { - set_hash("yday", str2num(s[6])); - } - else if (!NIL_P(s[9])) { - set_hash("cweek", str2num(s[8])); - set_hash("cwday", str2num(s[9])); - y = str2num(s[7]); - if (RSTRING_LEN(s[7]) < 4) - y = comp_year69(y); - set_hash("cwyear", y); - } - else if (!NIL_P(s[11])) { - set_hash("cweek", str2num(s[10])); - set_hash("cwday", str2num(s[11])); - } - else if (!NIL_P(s[12])) { - set_hash("cwday", str2num(s[12])); - } - if (!NIL_P(s[13])) { - set_hash("hour", str2num(s[13])); - set_hash("min", str2num(s[14])); - if (!NIL_P(s[15])) - set_hash("sec", str2num(s[15])); - } - if (!NIL_P(s[16])) { - set_hash("sec_fraction", sec_fraction(s[16])); - } - if (!NIL_P(s[17])) { - set_hash("zone", s[17]); - set_hash("offset", date_zone_to_diff(s[17])); - } - - return 1; -} - -static int -iso8601_bas_datetime(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\A\\s*(?:([-+]?(?:\\d{4}|\\d{2})|--)(\\d{2}|-)(\\d{2})|" - "([-+]?(?:\\d{4}|\\d{2}))(\\d{3})|" - "-(\\d{3})|" - "(\\d{4}|\\d{2})w(\\d{2})(\\d)|" - "-w(\\d{2})(\\d)|" - "-w-(\\d))" - "(?:t?" - "(\\d{2})(\\d{2})(?:(\\d{2})(?:[,.](\\d+))?)?" - "(z|[-+]\\d{2}(?:\\d{2})?)?)?\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - MATCH(str, pat, iso8601_bas_datetime_cb); -} - -#undef SNUM -#define SNUM 5 - -static int -iso8601_ext_time_cb(VALUE m, VALUE hash) -{ - VALUE s[SNUM + 1]; - - { - int i; - s[0] = Qnil; - for (i = 1; i <= SNUM; i++) - s[i] = rb_reg_nth_match(i, m); - } - - set_hash("hour", str2num(s[1])); - set_hash("min", str2num(s[2])); - if (!NIL_P(s[3])) - set_hash("sec", str2num(s[3])); - if (!NIL_P(s[4])) - set_hash("sec_fraction", sec_fraction(s[4])); - if (!NIL_P(s[5])) { - set_hash("zone", s[5]); - set_hash("offset", date_zone_to_diff(s[5])); - } - - return 1; -} - -#define iso8601_bas_time_cb iso8601_ext_time_cb - -static int -iso8601_ext_time(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\A\\s*(\\d{2}):(\\d{2})(?::(\\d{2})(?:[,.](\\d+))?" - "(z|[-+]\\d{2}(:?\\d{2})?)?)?\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - MATCH(str, pat, iso8601_ext_time_cb); -} - -static int -iso8601_bas_time(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\A\\s*(\\d{2})(\\d{2})(?:(\\d{2})(?:[,.](\\d+))?" - "(z|[-+]\\d{2}(\\d{2})?)?)?\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - MATCH(str, pat, iso8601_bas_time_cb); -} - -VALUE -date__iso8601(VALUE str) -{ - VALUE backref, hash; - - backref = rb_backref_get(); - rb_match_busy(backref); - - hash = rb_hash_new(); - - if (iso8601_ext_datetime(str, hash)) - goto ok; - if (iso8601_bas_datetime(str, hash)) - goto ok; - if (iso8601_ext_time(str, hash)) - goto ok; - if (iso8601_bas_time(str, hash)) - goto ok; - - ok: - rb_backref_set(backref); - - return hash; -} - -#undef SNUM -#define SNUM 8 - -static int -rfc3339_cb(VALUE m, VALUE hash) -{ - VALUE s[SNUM + 1]; - - { - int i; - s[0] = Qnil; - for (i = 1; i <= SNUM; i++) - s[i] = rb_reg_nth_match(i, m); - } - - set_hash("year", str2num(s[1])); - set_hash("mon", str2num(s[2])); - set_hash("mday", str2num(s[3])); - set_hash("hour", str2num(s[4])); - set_hash("min", str2num(s[5])); - set_hash("sec", str2num(s[6])); - set_hash("zone", s[8]); - set_hash("offset", date_zone_to_diff(s[8])); - if (!NIL_P(s[7])) - set_hash("sec_fraction", sec_fraction(s[7])); - - return 1; -} - -static int -rfc3339(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\A\\s*(-?\\d{4})-(\\d{2})-(\\d{2})" - "(?:t|\\s)" - "(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d+))?" - "(z|[-+]\\d{2}:\\d{2})\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - MATCH(str, pat, rfc3339_cb); -} - -VALUE -date__rfc3339(VALUE str) -{ - VALUE backref, hash; - - backref = rb_backref_get(); - rb_match_busy(backref); - - hash = rb_hash_new(); - rfc3339(str, hash); - rb_backref_set(backref); - return hash; -} - -#undef SNUM -#define SNUM 8 - -static int -xmlschema_datetime_cb(VALUE m, VALUE hash) -{ - VALUE s[SNUM + 1]; - - { - int i; - s[0] = Qnil; - for (i = 1; i <= SNUM; i++) - s[i] = rb_reg_nth_match(i, m); - } - - set_hash("year", str2num(s[1])); - if (!NIL_P(s[2])) - set_hash("mon", str2num(s[2])); - if (!NIL_P(s[3])) - set_hash("mday", str2num(s[3])); - if (!NIL_P(s[4])) - set_hash("hour", str2num(s[4])); - if (!NIL_P(s[5])) - set_hash("min", str2num(s[5])); - if (!NIL_P(s[6])) - set_hash("sec", str2num(s[6])); - if (!NIL_P(s[7])) - set_hash("sec_fraction", sec_fraction(s[7])); - if (!NIL_P(s[8])) { - set_hash("zone", s[8]); - set_hash("offset", date_zone_to_diff(s[8])); - } - - return 1; -} - -static int -xmlschema_datetime(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\A\\s*(-?\\d{4,})(?:-(\\d{2})(?:-(\\d{2}))?)?" - "(?:t" - "(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d+))?)?" - "(z|[-+]\\d{2}:\\d{2})?\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - MATCH(str, pat, xmlschema_datetime_cb); -} - -#undef SNUM -#define SNUM 5 - -static int -xmlschema_time_cb(VALUE m, VALUE hash) -{ - VALUE s[SNUM + 1]; - - { - int i; - s[0] = Qnil; - for (i = 1; i <= SNUM; i++) - s[i] = rb_reg_nth_match(i, m); - } - - set_hash("hour", str2num(s[1])); - set_hash("min", str2num(s[2])); - if (!NIL_P(s[3])) - set_hash("sec", str2num(s[3])); - if (!NIL_P(s[4])) - set_hash("sec_fraction", sec_fraction(s[4])); - if (!NIL_P(s[5])) { - set_hash("zone", s[5]); - set_hash("offset", date_zone_to_diff(s[5])); - } - - return 1; -} - -static int -xmlschema_time(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\A\\s*(\\d{2}):(\\d{2}):(\\d{2})(?:\\.(\\d+))?" - "(z|[-+]\\d{2}:\\d{2})?\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - MATCH(str, pat, xmlschema_time_cb); -} - -#undef SNUM -#define SNUM 4 - -static int -xmlschema_trunc_cb(VALUE m, VALUE hash) -{ - VALUE s[SNUM + 1]; - - { - int i; - s[0] = Qnil; - for (i = 1; i <= SNUM; i++) - s[i] = rb_reg_nth_match(i, m); - } - - if (!NIL_P(s[1])) - set_hash("mon", str2num(s[1])); - if (!NIL_P(s[2])) - set_hash("mday", str2num(s[2])); - if (!NIL_P(s[3])) - set_hash("mday", str2num(s[3])); - if (!NIL_P(s[4])) { - set_hash("zone", s[4]); - set_hash("offset", date_zone_to_diff(s[4])); - } - - return 1; -} - -static int -xmlschema_trunc(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\A\\s*(?:--(\\d{2})(?:-(\\d{2}))?|---(\\d{2}))" - "(z|[-+]\\d{2}:\\d{2})?\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - MATCH(str, pat, xmlschema_trunc_cb); -} - -VALUE -date__xmlschema(VALUE str) -{ - VALUE backref, hash; - - backref = rb_backref_get(); - rb_match_busy(backref); - - hash = rb_hash_new(); - - if (xmlschema_datetime(str, hash)) - goto ok; - if (xmlschema_time(str, hash)) - goto ok; - if (xmlschema_trunc(str, hash)) - goto ok; - - ok: - rb_backref_set(backref); - - return hash; -} - -#undef SNUM -#define SNUM 8 - -static int -rfc2822_cb(VALUE m, VALUE hash) -{ - VALUE s[SNUM + 1], y; - - { - int i; - s[0] = Qnil; - for (i = 1; i <= SNUM; i++) - s[i] = rb_reg_nth_match(i, m); - } - - if (!NIL_P(s[1])) { - set_hash("wday", INT2FIX(day_num(s[1]))); - } - set_hash("mday", str2num(s[2])); - set_hash("mon", INT2FIX(mon_num(s[3]))); - y = str2num(s[4]); - if (RSTRING_LEN(s[4]) < 4) - y = comp_year50(y); - set_hash("year", y); - set_hash("hour", str2num(s[5])); - set_hash("min", str2num(s[6])); - if (!NIL_P(s[7])) - set_hash("sec", str2num(s[7])); - set_hash("zone", s[8]); - set_hash("offset", date_zone_to_diff(s[8])); - - return 1; -} - -static int -rfc2822(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\A\\s*(?:(" ABBR_DAYS ")\\s*,\\s+)?" - "(\\d{1,2})\\s+" - "(" ABBR_MONTHS ")\\s+" - "(-?\\d{2,})\\s+" - "(\\d{2}):(\\d{2})(?::(\\d{2}))?\\s*" - "([-+]\\d{4}|ut|gmt|e[sd]t|c[sd]t|m[sd]t|p[sd]t|[a-ik-z])\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - MATCH(str, pat, rfc2822_cb); -} - -VALUE -date__rfc2822(VALUE str) -{ - VALUE backref, hash; - - backref = rb_backref_get(); - rb_match_busy(backref); - - hash = rb_hash_new(); - rfc2822(str, hash); - rb_backref_set(backref); - return hash; -} - -#undef SNUM -#define SNUM 8 - -static int -httpdate_type1_cb(VALUE m, VALUE hash) -{ - VALUE s[SNUM + 1]; - - { - int i; - s[0] = Qnil; - for (i = 1; i <= SNUM; i++) - s[i] = rb_reg_nth_match(i, m); - } - - set_hash("wday", INT2FIX(day_num(s[1]))); - set_hash("mday", str2num(s[2])); - set_hash("mon", INT2FIX(mon_num(s[3]))); - set_hash("year", str2num(s[4])); - set_hash("hour", str2num(s[5])); - set_hash("min", str2num(s[6])); - set_hash("sec", str2num(s[7])); - set_hash("zone", s[8]); - set_hash("offset", INT2FIX(0)); - - return 1; -} - -static int -httpdate_type1(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\A\\s*(" ABBR_DAYS ")\\s*,\\s+" - "(\\d{2})\\s+" - "(" ABBR_MONTHS ")\\s+" - "(-?\\d{4})\\s+" - "(\\d{2}):(\\d{2}):(\\d{2})\\s+" - "(gmt)\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - MATCH(str, pat, httpdate_type1_cb); -} - -#undef SNUM -#define SNUM 8 - -static int -httpdate_type2_cb(VALUE m, VALUE hash) -{ - VALUE s[SNUM + 1], y; - - { - int i; - s[0] = Qnil; - for (i = 1; i <= SNUM; i++) - s[i] = rb_reg_nth_match(i, m); - } - - set_hash("wday", INT2FIX(day_num(s[1]))); - set_hash("mday", str2num(s[2])); - set_hash("mon", INT2FIX(mon_num(s[3]))); - y = str2num(s[4]); - if (f_ge_p(y, INT2FIX(0)) && f_le_p(y, INT2FIX(99))) - y = comp_year69(y); - set_hash("year", y); - set_hash("hour", str2num(s[5])); - set_hash("min", str2num(s[6])); - set_hash("sec", str2num(s[7])); - set_hash("zone", s[8]); - set_hash("offset", INT2FIX(0)); - - return 1; -} - -static int -httpdate_type2(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\A\\s*(" DAYS ")\\s*,\\s+" - "(\\d{2})\\s*-\\s*" - "(" ABBR_MONTHS ")\\s*-\\s*" - "(\\d{2})\\s+" - "(\\d{2}):(\\d{2}):(\\d{2})\\s+" - "(gmt)\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - MATCH(str, pat, httpdate_type2_cb); -} - -#undef SNUM -#define SNUM 7 - -static int -httpdate_type3_cb(VALUE m, VALUE hash) -{ - VALUE s[SNUM + 1]; - - { - int i; - s[0] = Qnil; - for (i = 1; i <= SNUM; i++) - s[i] = rb_reg_nth_match(i, m); - } - - set_hash("wday", INT2FIX(day_num(s[1]))); - set_hash("mon", INT2FIX(mon_num(s[2]))); - set_hash("mday", str2num(s[3])); - set_hash("hour", str2num(s[4])); - set_hash("min", str2num(s[5])); - set_hash("sec", str2num(s[6])); - set_hash("year", str2num(s[7])); - - return 1; -} - -static int -httpdate_type3(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\A\\s*(" ABBR_DAYS ")\\s+" - "(" ABBR_MONTHS ")\\s+" - "(\\d{1,2})\\s+" - "(\\d{2}):(\\d{2}):(\\d{2})\\s+" - "(\\d{4})\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - MATCH(str, pat, httpdate_type3_cb); -} - -VALUE -date__httpdate(VALUE str) -{ - VALUE backref, hash; - - backref = rb_backref_get(); - rb_match_busy(backref); - - hash = rb_hash_new(); - - if (httpdate_type1(str, hash)) - goto ok; - if (httpdate_type2(str, hash)) - goto ok; - if (httpdate_type3(str, hash)) - goto ok; - - ok: - rb_backref_set(backref); - - return hash; -} - -#undef SNUM -#define SNUM 9 - -static int -jisx0301_cb(VALUE m, VALUE hash) -{ - VALUE s[SNUM + 1]; - int ep; - - { - int i; - s[0] = Qnil; - for (i = 1; i <= SNUM; i++) - s[i] = rb_reg_nth_match(i, m); - } - - ep = gengo(NIL_P(s[1]) ? JISX0301_DEFAULT_ERA : *RSTRING_PTR(s[1])); - set_hash("year", f_add(str2num(s[2]), INT2FIX(ep))); - set_hash("mon", str2num(s[3])); - set_hash("mday", str2num(s[4])); - if (!NIL_P(s[5])) { - set_hash("hour", str2num(s[5])); - if (!NIL_P(s[6])) - set_hash("min", str2num(s[6])); - if (!NIL_P(s[7])) - set_hash("sec", str2num(s[7])); - } - if (!NIL_P(s[8])) - set_hash("sec_fraction", sec_fraction(s[8])); - if (!NIL_P(s[9])) { - set_hash("zone", s[9]); - set_hash("offset", date_zone_to_diff(s[9])); - } - - return 1; -} - -static int -jisx0301(VALUE str, VALUE hash) -{ - static const char pat_source[] = - "\\A\\s*([" JISX0301_ERA_INITIALS "])?(\\d{2})\\.(\\d{2})\\.(\\d{2})" - "(?:t" - "(?:(\\d{2}):(\\d{2})(?::(\\d{2})(?:[,.](\\d*))?)?" - "(z|[-+]\\d{2}(?::?\\d{2})?)?)?)?\\s*\\z"; - static VALUE pat = Qnil; - - REGCOMP_I(pat); - MATCH(str, pat, jisx0301_cb); -} - -VALUE -date__jisx0301(VALUE str) -{ - VALUE backref, hash; - - backref = rb_backref_get(); - rb_match_busy(backref); - - hash = rb_hash_new(); - if (jisx0301(str, hash)) - goto ok; - hash = date__iso8601(str); - - ok: - rb_backref_set(backref); - return hash; -} - -/* -Local variables: -c-file-style: "ruby" -End: -*/ diff --git a/ext/date/date_strftime.c b/ext/date/date_strftime.c deleted file mode 100644 index d7f28989..00000000 --- a/ext/date/date_strftime.c +++ /dev/null @@ -1,638 +0,0 @@ -/* - date_strftime.c: based on a public-domain implementation of ANSI C - library routine strftime, which is originally written by Arnold - Robbins. - */ - -#include "ruby/ruby.h" -#include "date_tmx.h" - -#include -#include -#include -#include - -#if defined(HAVE_SYS_TIME_H) -#include -#endif - -#undef strchr /* avoid AIX weirdness */ - -#define range(low, item, hi) (item) - -#define add(x,y) (rb_funcall((x), '+', 1, (y))) -#define sub(x,y) (rb_funcall((x), '-', 1, (y))) -#define mul(x,y) (rb_funcall((x), '*', 1, (y))) -#define quo(x,y) (rb_funcall((x), rb_intern("quo"), 1, (y))) -#define div(x,y) (rb_funcall((x), rb_intern("div"), 1, (y))) -#define mod(x,y) (rb_funcall((x), '%', 1, (y))) - -static void -upcase(char *s, size_t i) -{ - do { - if (ISLOWER(*s)) - *s = TOUPPER(*s); - } while (s++, --i); -} - -static void -downcase(char *s, size_t i) -{ - do { - if (ISUPPER(*s)) - *s = TOLOWER(*s); - } while (s++, --i); -} - -/* strftime --- produce formatted time */ - -static size_t -date_strftime_with_tmx(char *s, const size_t maxsize, const char *format, - const struct tmx *tmx) -{ - char *endp = s + maxsize; - char *start = s; - const char *sp, *tp; - auto char tbuf[100]; - ptrdiff_t i; - int v, w; - size_t colons; - int precision, flags; - char padding; - /* LOCALE_[OE] and COLONS are actually modifiers, not flags */ - enum {LEFT, CHCASE, LOWER, UPPER, LOCALE_O, LOCALE_E, COLONS}; -#define BIT_OF(n) (1U<<(n)) - - /* various tables for locale C */ - static const char days_l[][10] = { - "Sunday", "Monday", "Tuesday", "Wednesday", - "Thursday", "Friday", "Saturday", - }; - static const char months_l[][10] = { - "January", "February", "March", "April", - "May", "June", "July", "August", "September", - "October", "November", "December", - }; - static const char ampm[][3] = { "AM", "PM", }; - - if (s == NULL || format == NULL || tmx == NULL || maxsize == 0) - return 0; - - /* quick check if we even need to bother */ - if (strchr(format, '%') == NULL && strlen(format) + 1 >= maxsize) { - err: - errno = ERANGE; - return 0; - } - - for (; *format && s < endp - 1; format++) { -#define FLAG_FOUND() do { \ - if (precision > 0 || flags & (BIT_OF(LOCALE_E) | BIT_OF(LOCALE_O) | BIT_OF(COLONS))) \ - goto unknown; \ - } while (0) -#define NEEDS(n) do if (s >= endp || (n) >= endp - s - 1) goto err; while (0) -#define FILL_PADDING(i) do { \ - if (!(flags & BIT_OF(LEFT)) && precision > (i)) { \ - NEEDS(precision); \ - memset(s, padding ? padding : ' ', precision - (i)); \ - s += precision - (i); \ - } \ - else { \ - NEEDS(i); \ - } \ - } while (0); -#define FMT(def_pad, def_prec, fmt, val) \ - do { \ - int l; \ - if (precision <= 0) precision = (def_prec); \ - if (flags & BIT_OF(LEFT)) precision = 1; \ - l = snprintf(s, endp - s, \ - ((padding == '0' || (!padding && (def_pad) == '0')) ? \ - "%0*"fmt : "%*"fmt), \ - precision, (val)); \ - if (l < 0) goto err; \ - s += l; \ - } while (0) -#define STRFTIME(fmt) \ - do { \ - i = date_strftime_with_tmx(s, endp - s, (fmt), tmx); \ - if (!i) return 0; \ - if (flags & BIT_OF(UPPER)) \ - upcase(s, i); \ - if (!(flags & BIT_OF(LEFT)) && precision > i) { \ - if (start + maxsize < s + precision) { \ - errno = ERANGE; \ - return 0; \ - } \ - memmove(s + precision - i, s, i); \ - memset(s, padding ? padding : ' ', precision - i); \ - s += precision; \ - } \ - else s += i; \ - } while (0) -#define FMTV(def_pad, def_prec, fmt, val) \ - do { \ - VALUE tmp = (val); \ - if (FIXNUM_P(tmp)) { \ - FMT((def_pad), (def_prec), "l"fmt, FIX2LONG(tmp)); \ - } \ - else { \ - VALUE args[2], result; \ - size_t l; \ - if (precision <= 0) precision = (def_prec); \ - if (flags & BIT_OF(LEFT)) precision = 1; \ - args[0] = INT2FIX(precision); \ - args[1] = (val); \ - if (padding == '0' || (!padding && (def_pad) == '0')) \ - result = rb_str_format(2, args, rb_str_new2("%0*"fmt)); \ - else \ - result = rb_str_format(2, args, rb_str_new2("%*"fmt)); \ - l = strlcpy(s, StringValueCStr(result), endp - s); \ - if ((size_t)(endp - s) <= l) \ - goto err; \ - s += l; \ - } \ - } while (0) - - if (*format != '%') { - *s++ = *format; - continue; - } - tp = tbuf; - sp = format; - precision = -1; - flags = 0; - padding = 0; - colons = 0; - again: - switch (*++format) { - case '\0': - format--; - goto unknown; - - case 'A': /* full weekday name */ - case 'a': /* abbreviated weekday name */ - if (flags & BIT_OF(CHCASE)) { - flags &= ~(BIT_OF(LOWER) | BIT_OF(CHCASE)); - flags |= BIT_OF(UPPER); - } - { - int wday = tmx_wday; - if (wday < 0 || wday > 6) - i = 1, tp = "?"; - else { - if (*format == 'A') - i = strlen(tp = days_l[wday]); - else - i = 3, tp = days_l[wday]; - } - } - break; - - case 'B': /* full month name */ - case 'b': /* abbreviated month name */ - case 'h': /* same as %b */ - if (flags & BIT_OF(CHCASE)) { - flags &= ~(BIT_OF(LOWER) | BIT_OF(CHCASE)); - flags |= BIT_OF(UPPER); - } - { - int mon = tmx_mon; - if (mon < 1 || mon > 12) - i = 1, tp = "?"; - else { - if (*format == 'B') - i = strlen(tp = months_l[mon - 1]); - else - i = 3, tp = months_l[mon - 1]; - } - } - break; - - case 'C': /* century (year/100) */ - FMTV('0', 2, "d", div(tmx_year, INT2FIX(100))); - continue; - - case 'c': /* appropriate date and time representation */ - STRFTIME("%a %b %e %H:%M:%S %Y"); - continue; - - case 'D': - STRFTIME("%m/%d/%y"); - continue; - - case 'd': /* day of the month, 01 - 31 */ - case 'e': /* day of month, blank padded */ - v = range(1, tmx_mday, 31); - FMT((*format == 'd') ? '0' : ' ', 2, "d", v); - continue; - - case 'F': - STRFTIME("%Y-%m-%d"); - continue; - - case 'G': /* year of ISO week with century */ - case 'Y': /* year with century */ - { - VALUE year = (*format == 'G') ? tmx_cwyear : tmx_year; - if (FIXNUM_P(year)) { - long y = FIX2LONG(year); - FMT('0', 0 <= y ? 4 : 5, "ld", y); - } - else { - FMTV('0', 4, "d", year); - } - } - continue; - - case 'g': /* year of ISO week without a century */ - case 'y': /* year without a century */ - v = NUM2INT(mod((*format == 'g') ? tmx_cwyear : tmx_year, INT2FIX(100))); - FMT('0', 2, "d", v); - continue; - - case 'H': /* hour, 24-hour clock, 00 - 23 */ - case 'k': /* hour, 24-hour clock, blank pad */ - v = range(0, tmx_hour, 23); - FMT((*format == 'H') ? '0' : ' ', 2, "d", v); - continue; - - case 'I': /* hour, 12-hour clock, 01 - 12 */ - case 'l': /* hour, 12-hour clock, 1 - 12, blank pad */ - v = range(0, tmx_hour, 23); - if (v == 0) - v = 12; - else if (v > 12) - v -= 12; - FMT((*format == 'I') ? '0' : ' ', 2, "d", v); - continue; - - case 'j': /* day of the year, 001 - 366 */ - v = range(1, tmx_yday, 366); - FMT('0', 3, "d", v); - continue; - - case 'L': /* millisecond */ - case 'N': /* nanosecond */ - if (*format == 'L') - w = 3; - else - w = 9; - if (precision <= 0) - precision = w; - NEEDS(precision); - - { - VALUE subsec = tmx_sec_fraction; - int ww; - long n; - - ww = precision; - while (9 <= ww) { - subsec = mul(subsec, INT2FIX(1000000000)); - ww -= 9; - } - n = 1; - for (; 0 < ww; ww--) - n *= 10; - if (n != 1) - subsec = mul(subsec, INT2FIX(n)); - subsec = div(subsec, INT2FIX(1)); - - if (FIXNUM_P(subsec)) { - (void)snprintf(s, endp - s, "%0*ld", - precision, FIX2LONG(subsec)); - s += precision; - } - else { - VALUE args[2], result; - args[0] = INT2FIX(precision); - args[1] = subsec; - result = rb_str_format(2, args, rb_str_new2("%0*d")); - (void)strlcpy(s, StringValueCStr(result), endp - s); - s += precision; - } - } - continue; - - case 'M': /* minute, 00 - 59 */ - v = range(0, tmx_min, 59); - FMT('0', 2, "d", v); - continue; - - case 'm': /* month, 01 - 12 */ - v = range(1, tmx_mon, 12); - FMT('0', 2, "d", v); - continue; - - case 'n': /* same as \n */ - FILL_PADDING(1); - *s++ = '\n'; - continue; - - case 't': /* same as \t */ - FILL_PADDING(1); - *s++ = '\t'; - continue; - - case 'P': /* am or pm based on 12-hour clock */ - case 'p': /* AM or PM based on 12-hour clock */ - if ((*format == 'p' && (flags & BIT_OF(CHCASE))) || - (*format == 'P' && !(flags & (BIT_OF(CHCASE) | BIT_OF(UPPER))))) { - flags &= ~(BIT_OF(UPPER) | BIT_OF(CHCASE)); - flags |= BIT_OF(LOWER); - } - v = range(0, tmx_hour, 23); - if (v < 12) - tp = ampm[0]; - else - tp = ampm[1]; - i = 2; - break; - - case 'Q': /* milliseconds since Unix epoch */ - FMTV('0', 1, "d", tmx_msecs); - continue; - - case 'R': - STRFTIME("%H:%M"); - continue; - - case 'r': - STRFTIME("%I:%M:%S %p"); - continue; - - case 'S': /* second, 00 - 59 */ - v = range(0, tmx_sec, 59); - FMT('0', 2, "d", v); - continue; - - case 's': /* seconds since Unix epoch */ - FMTV('0', 1, "d", tmx_secs); - continue; - - case 'T': - STRFTIME("%H:%M:%S"); - continue; - - case 'U': /* week of year, Sunday is first day of week */ - case 'W': /* week of year, Monday is first day of week */ - v = range(0, (*format == 'U') ? tmx_wnum0 : tmx_wnum1, 53); - FMT('0', 2, "d", v); - continue; - - case 'u': /* weekday, Monday == 1, 1 - 7 */ - v = range(1, tmx_cwday, 7); - FMT('0', 1, "d", v); - continue; - - case 'V': /* week of year according ISO 8601 */ - v = range(1, tmx_cweek, 53); - FMT('0', 2, "d", v); - continue; - - case 'v': - STRFTIME("%e-%^b-%Y"); - continue; - - case 'w': /* weekday, Sunday == 0, 0 - 6 */ - v = range(0, tmx_wday, 6); - FMT('0', 1, "d", v); - continue; - - case 'X': /* appropriate time representation */ - STRFTIME("%H:%M:%S"); - continue; - - case 'x': /* appropriate date representation */ - STRFTIME("%m/%d/%y"); - continue; - - case 'Z': /* time zone name or abbreviation */ - if (flags & BIT_OF(CHCASE)) { - flags &= ~(BIT_OF(UPPER) | BIT_OF(CHCASE)); - flags |= BIT_OF(LOWER); - } - { - char *zone = tmx_zone; - if (zone == NULL) - tp = ""; - else - tp = zone; - i = strlen(tp); - } - break; - - case 'z': /* offset from UTC */ - { - long off, aoff; - int hl, hw; - - off = tmx_offset; - aoff = off; - if (aoff < 0) - aoff = -off; - - if ((aoff / 3600) < 10) - hl = 1; - else - hl = 2; - hw = 2; - if (flags & BIT_OF(LEFT) && hl == 1) - hw = 1; - - switch (colons) { - case 0: /* %z -> +hhmm */ - precision = precision <= (3 + hw) ? hw : precision - 3; - NEEDS(precision + 3); - break; - - case 1: /* %:z -> +hh:mm */ - precision = precision <= (4 + hw) ? hw : precision - 4; - NEEDS(precision + 4); - break; - - case 2: /* %::z -> +hh:mm:ss */ - precision = precision <= (7 + hw) ? hw : precision - 7; - NEEDS(precision + 7); - break; - - case 3: /* %:::z -> +hh[:mm[:ss]] */ - { - if (aoff % 3600 == 0) { - precision = precision <= (1 + hw) ? - hw : precision - 1; - NEEDS(precision + 3); - } - else if (aoff % 60 == 0) { - precision = precision <= (4 + hw) ? - hw : precision - 4; - NEEDS(precision + 4); - } - else { - precision = precision <= (7 + hw) ? - hw : precision - 7; - NEEDS(precision + 7); - } - } - break; - - default: - format--; - goto unknown; - } - if (padding == ' ' && precision > hl) { - i = snprintf(s, endp - s, "%*s", precision - hl, ""); - precision = hl; - if (i < 0) goto err; - s += i; - } - if (off < 0) { - off = -off; - *s++ = '-'; - } else { - *s++ = '+'; - } - i = snprintf(s, endp - s, "%.*ld", precision, off / 3600); - if (i < 0) goto err; - s += i; - off = off % 3600; - if (colons == 3 && off == 0) - continue; - if (1 <= colons) - *s++ = ':'; - i = snprintf(s, endp - s, "%02d", (int)(off / 60)); - if (i < 0) goto err; - s += i; - off = off % 60; - if (colons == 3 && off == 0) - continue; - if (2 <= colons) { - *s++ = ':'; - i = snprintf(s, endp - s, "%02d", (int)off); - if (i < 0) goto err; - s += i; - } - } - continue; - - case '+': - STRFTIME("%a %b %e %H:%M:%S %Z %Y"); - continue; - - case 'E': - /* POSIX locale extensions, ignored for now */ - flags |= BIT_OF(LOCALE_E); - if (*(format + 1) && strchr("cCxXyY", *(format + 1))) - goto again; - goto unknown; - case 'O': - /* POSIX locale extensions, ignored for now */ - flags |= BIT_OF(LOCALE_O); - if (*(format + 1) && strchr("deHkIlmMSuUVwWy", *(format + 1))) - goto again; - goto unknown; - - case ':': - flags |= BIT_OF(COLONS); - { - size_t l = strspn(format, ":"); - format += l; - if (*format == 'z') { - colons = l; - format--; - goto again; - } - format -= l; - } - goto unknown; - - case '_': - FLAG_FOUND(); - padding = ' '; - goto again; - - case '-': - FLAG_FOUND(); - flags |= BIT_OF(LEFT); - goto again; - - case '^': - FLAG_FOUND(); - flags |= BIT_OF(UPPER); - goto again; - - case '#': - FLAG_FOUND(); - flags |= BIT_OF(CHCASE); - goto again; - - case '0': - FLAG_FOUND(); - padding = '0'; - case '1': case '2': case '3': case '4': - case '5': case '6': case '7': case '8': case '9': - { - char *e; - unsigned long prec = strtoul(format, &e, 10); - if (prec > INT_MAX || prec > maxsize) { - errno = ERANGE; - return 0; - } - precision = (int)prec; - format = e - 1; - goto again; - } - - case '%': - FILL_PADDING(1); - *s++ = '%'; - continue; - - default: - unknown: - i = format - sp + 1; - tp = sp; - precision = -1; - flags = 0; - padding = 0; - colons = 0; - break; - } - if (i) { - FILL_PADDING(i); - memcpy(s, tp, i); - switch (flags & (BIT_OF(UPPER) | BIT_OF(LOWER))) { - case BIT_OF(UPPER): - upcase(s, i); - break; - case BIT_OF(LOWER): - downcase(s, i); - break; - } - s += i; - } - } - if (s >= endp) { - goto err; - } - if (*format == '\0') { - *s = '\0'; - return (s - start); - } - return 0; -} - -size_t -date_strftime(char *s, size_t maxsize, const char *format, - const struct tmx *tmx) -{ - return date_strftime_with_tmx(s, maxsize, format, tmx); -} - -/* -Local variables: -c-file-style: "ruby" -End: -*/ diff --git a/ext/date/date_strptime.c b/ext/date/date_strptime.c deleted file mode 100644 index 1dde5fa3..00000000 --- a/ext/date/date_strptime.c +++ /dev/null @@ -1,704 +0,0 @@ -/* - date_strptime.c: Coded by Tadayoshi Funaba 2011,2012 -*/ - -#include "ruby.h" -#include "ruby/encoding.h" -#include "ruby/re.h" -#include - -#undef strncasecmp -#define strncasecmp STRNCASECMP - -static const char *day_names[] = { - "Sunday", "Monday", "Tuesday", "Wednesday", - "Thursday", "Friday", "Saturday", -}; -static const int ABBREVIATED_DAY_NAME_LENGTH = 3; - -static const char *month_names[] = { - "January", "February", "March", "April", - "May", "June", "July", "August", "September", - "October", "November", "December", -}; -static const int ABBREVIATED_MONTH_NAME_LENGTH = 3; - -#define sizeof_array(o) (sizeof o / sizeof o[0]) - -#define f_negate(x) rb_funcall(x, rb_intern("-@"), 0) -#define f_add(x,y) rb_funcall(x, '+', 1, y) -#define f_sub(x,y) rb_funcall(x, '-', 1, y) -#define f_mul(x,y) rb_funcall(x, '*', 1, y) -#define f_div(x,y) rb_funcall(x, '/', 1, y) -#define f_idiv(x,y) rb_funcall(x, rb_intern("div"), 1, y) -#define f_mod(x,y) rb_funcall(x, '%', 1, y) -#define f_expt(x,y) rb_funcall(x, rb_intern("**"), 1, y) - -#define f_lt_p(x,y) rb_funcall(x, '<', 1, y) -#define f_gt_p(x,y) rb_funcall(x, '>', 1, y) -#define f_le_p(x,y) rb_funcall(x, rb_intern("<="), 1, y) -#define f_ge_p(x,y) rb_funcall(x, rb_intern(">="), 1, y) - -#define f_match(r,s) rb_funcall(r, rb_intern("match"), 1, s) -#define f_aref(o,i) rb_funcall(o, rb_intern("[]"), 1, i) -#define f_end(o,i) rb_funcall(o, rb_intern("end"), 1, i) - -#define issign(c) ((c) == '-' || (c) == '+') - -static int -num_pattern_p(const char *s) -{ - if (isdigit((unsigned char)*s)) - return 1; - if (*s == '%') { - s++; - if (*s == 'E' || *s == 'O') - s++; - if (*s && - (strchr("CDdeFGgHIjkLlMmNQRrSsTUuVvWwXxYy", *s) || - isdigit((unsigned char)*s))) - return 1; - } - return 0; -} - -#define NUM_PATTERN_P() num_pattern_p(&fmt[fi + 1]) - -static long -read_digits(const char *s, size_t slen, VALUE *n, size_t width) -{ - size_t l; - - if (!width) - return 0; - - l = 0; - while (l < slen && ISDIGIT(s[l])) { - if (++l == width) break; - } - - if (l == 0) - return 0; - - if ((4 * l * sizeof(char)) <= (sizeof(long)*CHAR_BIT)) { - const char *os = s; - long v; - - v = 0; - while ((size_t)(s - os) < l) { - v *= 10; - v += *s - '0'; - s++; - } - if (os == s) - return 0; - *n = LONG2NUM(v); - return l; - } - else { - VALUE vbuf = 0; - char *s2 = ALLOCV_N(char, vbuf, l + 1); - memcpy(s2, s, l); - s2[l] = '\0'; - *n = rb_cstr_to_inum(s2, 10, 0); - ALLOCV_END(vbuf); - return l; - } -} - -#define set_hash(k,v) rb_hash_aset(hash, ID2SYM(rb_intern(k"")), v) -#define ref_hash(k) rb_hash_aref(hash, ID2SYM(rb_intern(k""))) -#define del_hash(k) rb_hash_delete(hash, ID2SYM(rb_intern(k""))) - -#define fail() \ -do { \ - set_hash("_fail", Qtrue); \ - return 0; \ -} while (0) - -#define fail_p() (!NIL_P(ref_hash("_fail"))) - -#define READ_DIGITS(n,w) \ -do { \ - size_t l; \ - l = read_digits(&str[si], slen - si, &n, w); \ - if (l == 0) { \ - fail(); \ - } \ - si += l; \ -} while (0) - -#define READ_DIGITS_MAX(n) READ_DIGITS(n, LONG_MAX) - -static int -valid_range_p(VALUE v, int a, int b) -{ - if (FIXNUM_P(v)) { - int vi = FIX2INT(v); - return !(vi < a || vi > b); - } - return !(f_lt_p(v, INT2NUM(a)) || f_gt_p(v, INT2NUM(b))); -} - -#define recur(fmt) \ -do { \ - size_t l; \ - l = date__strptime_internal(&str[si], slen - si, \ - fmt, sizeof fmt - 1, hash); \ - if (fail_p()) \ - return 0; \ - si += l; \ -} while (0) - -VALUE date_zone_to_diff(VALUE); - -static inline int -head_match_p(size_t len, const char *name, const char *str, size_t slen, size_t si) -{ - return slen - si >= len && strncasecmp(name, &str[si], len) == 0; -} - -static size_t -date__strptime_internal(const char *str, size_t slen, - const char *fmt, size_t flen, VALUE hash) -{ - size_t si, fi; - int c; - -#define HEAD_MATCH_P(len, name) head_match_p(len, name, str, slen, si) - si = fi = 0; - - while (fi < flen) { - if (isspace((unsigned char)fmt[fi])) { - while (si < slen && isspace((unsigned char)str[si])) - si++; - while (++fi < flen && isspace((unsigned char)fmt[fi])); - continue; - } - - if (si >= slen) fail(); - - switch (fmt[fi]) { - case '%': - - again: - fi++; - c = fmt[fi]; - - switch (c) { - case 'E': - if (fmt[fi + 1] && strchr("cCxXyY", fmt[fi + 1])) - goto again; - fi--; - goto ordinal; - case 'O': - if (fmt[fi + 1] && strchr("deHImMSuUVwWy", fmt[fi + 1])) - goto again; - fi--; - goto ordinal; - case ':': - { - int i; - - for (i = 1; i < 3 && fi + i < flen && fmt[fi+i] == ':'; ++i); - if (fmt[fi+i] == 'z') { - fi += i - 1; - goto again; - } - fail(); - } - - case 'A': - case 'a': - { - int i; - - for (i = 0; i < (int)sizeof_array(day_names); i++) { - const char *day_name = day_names[i]; - size_t l = strlen(day_name); - if (HEAD_MATCH_P(l, day_name) || - HEAD_MATCH_P(l = ABBREVIATED_DAY_NAME_LENGTH, day_name)) { - si += l; - set_hash("wday", INT2FIX(i)); - goto matched; - } - } - fail(); - } - case 'B': - case 'b': - case 'h': - { - int i; - - for (i = 0; i < (int)sizeof_array(month_names); i++) { - const char *month_name = month_names[i]; - size_t l = strlen(month_name); - if (HEAD_MATCH_P(l, month_name) || - HEAD_MATCH_P(l = ABBREVIATED_MONTH_NAME_LENGTH, month_name)) { - si += l; - set_hash("mon", INT2FIX(i + 1)); - goto matched; - } - } - fail(); - } - - case 'C': - { - VALUE n; - - if (NUM_PATTERN_P()) - READ_DIGITS(n, 2); - else - READ_DIGITS_MAX(n); - set_hash("_cent", n); - goto matched; - } - - case 'c': - recur("%a %b %e %H:%M:%S %Y"); - goto matched; - - case 'D': - recur("%m/%d/%y"); - goto matched; - - case 'd': - case 'e': - { - VALUE n; - - if (str[si] == ' ') { - si++; - READ_DIGITS(n, 1); - } else { - READ_DIGITS(n, 2); - } - if (!valid_range_p(n, 1, 31)) - fail(); - set_hash("mday", n); - goto matched; - } - - case 'F': - recur("%Y-%m-%d"); - goto matched; - - case 'G': - { - VALUE n; - - if (NUM_PATTERN_P()) - READ_DIGITS(n, 4); - else - READ_DIGITS_MAX(n); - set_hash("cwyear", n); - goto matched; - } - - case 'g': - { - VALUE n; - - READ_DIGITS(n, 2); - if (!valid_range_p(n, 0, 99)) - fail(); - set_hash("cwyear",n); - if (NIL_P(ref_hash("_cent"))) - set_hash("_cent", - INT2FIX(f_ge_p(n, INT2FIX(69)) ? 19 : 20)); - goto matched; - } - - case 'H': - case 'k': - { - VALUE n; - - if (str[si] == ' ') { - si++; - READ_DIGITS(n, 1); - } else { - READ_DIGITS(n, 2); - } - if (!valid_range_p(n, 0, 24)) - fail(); - set_hash("hour", n); - goto matched; - } - - case 'I': - case 'l': - { - VALUE n; - - if (str[si] == ' ') { - si++; - READ_DIGITS(n, 1); - } else { - READ_DIGITS(n, 2); - } - if (!valid_range_p(n, 1, 12)) - fail(); - set_hash("hour", n); - goto matched; - } - - case 'j': - { - VALUE n; - - READ_DIGITS(n, 3); - if (!valid_range_p(n, 1, 366)) - fail(); - set_hash("yday", n); - goto matched; - } - - case 'L': - case 'N': - { - VALUE n; - int sign = 1; - size_t osi; - - if (issign(str[si])) { - if (str[si] == '-') - sign = -1; - si++; - } - osi = si; - if (NUM_PATTERN_P()) - READ_DIGITS(n, c == 'L' ? 3 : 9); - else - READ_DIGITS_MAX(n); - if (sign == -1) - n = f_negate(n); - set_hash("sec_fraction", - rb_rational_new2(n, - f_expt(INT2FIX(10), - ULONG2NUM(si - osi)))); - goto matched; - } - - case 'M': - { - VALUE n; - - READ_DIGITS(n, 2); - if (!valid_range_p(n, 0, 59)) - fail(); - set_hash("min", n); - goto matched; - } - - case 'm': - { - VALUE n; - - READ_DIGITS(n, 2); - if (!valid_range_p(n, 1, 12)) - fail(); - set_hash("mon", n); - goto matched; - } - - case 'n': - case 't': - recur(" "); - goto matched; - - case 'P': - case 'p': - if (slen - si < 2) fail(); - { - char c = str[si]; - const int hour = (c == 'P' || c == 'p') ? 12 : 0; - if (!hour && !(c == 'A' || c == 'a')) fail(); - if ((c = str[si+1]) == '.') { - if (slen - si < 4 || str[si+3] != '.') fail(); - c = str[si += 2]; - } - if (!(c == 'M' || c == 'm')) fail(); - si += 2; - set_hash("_merid", INT2FIX(hour)); - goto matched; - } - - case 'Q': - { - VALUE n; - int sign = 1; - - if (str[si] == '-') { - sign = -1; - si++; - } - READ_DIGITS_MAX(n); - if (sign == -1) - n = f_negate(n); - set_hash("seconds", - rb_rational_new2(n, INT2FIX(1000))); - goto matched; - } - - case 'R': - recur("%H:%M"); - goto matched; - - case 'r': - recur("%I:%M:%S %p"); - goto matched; - - case 'S': - { - VALUE n; - - READ_DIGITS(n, 2); - if (!valid_range_p(n, 0, 60)) - fail(); - set_hash("sec", n); - goto matched; - } - - case 's': - { - VALUE n; - int sign = 1; - - if (str[si] == '-') { - sign = -1; - si++; - } - READ_DIGITS_MAX(n); - if (sign == -1) - n = f_negate(n); - set_hash("seconds", n); - goto matched; - } - - case 'T': - recur("%H:%M:%S"); - goto matched; - - case 'U': - case 'W': - { - VALUE n; - - READ_DIGITS(n, 2); - if (!valid_range_p(n, 0, 53)) - fail(); - set_hash(c == 'U' ? "wnum0" : "wnum1", n); - goto matched; - } - - case 'u': - { - VALUE n; - - READ_DIGITS(n, 1); - if (!valid_range_p(n, 1, 7)) - fail(); - set_hash("cwday", n); - goto matched; - } - - case 'V': - { - VALUE n; - - READ_DIGITS(n, 2); - if (!valid_range_p(n, 1, 53)) - fail(); - set_hash("cweek", n); - goto matched; - } - - case 'v': - recur("%e-%b-%Y"); - goto matched; - - case 'w': - { - VALUE n; - - READ_DIGITS(n, 1); - if (!valid_range_p(n, 0, 6)) - fail(); - set_hash("wday", n); - goto matched; - } - - case 'X': - recur("%H:%M:%S"); - goto matched; - - case 'x': - recur("%m/%d/%y"); - goto matched; - - case 'Y': - { - VALUE n; - int sign = 1; - - if (issign(str[si])) { - if (str[si] == '-') - sign = -1; - si++; - } - if (NUM_PATTERN_P()) - READ_DIGITS(n, 4); - else - READ_DIGITS_MAX(n); - if (sign == -1) - n = f_negate(n); - set_hash("year", n); - goto matched; - } - - case 'y': - { - VALUE n; - int sign = 1; - - READ_DIGITS(n, 2); - if (!valid_range_p(n, 0, 99)) - fail(); - if (sign == -1) - n = f_negate(n); - set_hash("year", n); - if (NIL_P(ref_hash("_cent"))) - set_hash("_cent", - INT2FIX(f_ge_p(n, INT2FIX(69)) ? 19 : 20)); - goto matched; - } - - case 'Z': - case 'z': - { - static const char pat_source[] = - "\\A(" - "(?:gmt|utc?)?[-+]\\d+(?:[,.:]\\d+(?::\\d+)?)?" - "|(?-i:[[:alpha:].\\s]+)(?:standard|daylight)\\s+time\\b" - "|(?-i:[[:alpha:]]+)(?:\\s+dst)?\\b" - ")"; - static VALUE pat = Qnil; - VALUE m, b; - - if (NIL_P(pat)) { - pat = rb_reg_new(pat_source, sizeof pat_source - 1, - ONIG_OPTION_IGNORECASE); - rb_obj_freeze(pat); - rb_gc_register_mark_object(pat); - } - - b = rb_backref_get(); - rb_match_busy(b); - m = f_match(pat, rb_usascii_str_new(&str[si], slen - si)); - - if (!NIL_P(m)) { - VALUE s, l, o; - - s = rb_reg_nth_match(1, m); - l = f_end(m, INT2FIX(0)); - o = date_zone_to_diff(s); - si += NUM2LONG(l); - set_hash("zone", s); - set_hash("offset", o); - rb_backref_set(b); - goto matched; - } - rb_backref_set(b); - fail(); - } - - case '%': - if (str[si] != '%') - fail(); - si++; - goto matched; - - case '+': - recur("%a %b %e %H:%M:%S %Z %Y"); - goto matched; - - default: - if (str[si] != '%') - fail(); - si++; - if (fi < flen) { - if (si >= slen || str[si] != fmt[fi]) - fail(); - si++; - } - goto matched; - } - default: - ordinal: - if (str[si] != fmt[fi]) - fail(); - si++; - fi++; - break; - matched: - fi++; - break; - } - } - - return si; -} - -VALUE -date__strptime(const char *str, size_t slen, - const char *fmt, size_t flen, VALUE hash) -{ - size_t si; - VALUE cent, merid; - - si = date__strptime_internal(str, slen, fmt, flen, hash); - - if (fail_p()) - return Qnil; - - if (slen > si) { - VALUE s; - - s = rb_usascii_str_new(&str[si], slen - si); - set_hash("leftover", s); - } - - cent = del_hash("_cent"); - if (!NIL_P(cent)) { - VALUE year; - - year = ref_hash("cwyear"); - if (!NIL_P(year)) - set_hash("cwyear", f_add(year, f_mul(cent, INT2FIX(100)))); - year = ref_hash("year"); - if (!NIL_P(year)) - set_hash("year", f_add(year, f_mul(cent, INT2FIX(100)))); - } - - merid = del_hash("_merid"); - if (!NIL_P(merid)) { - VALUE hour; - - hour = ref_hash("hour"); - if (!NIL_P(hour)) { - hour = f_mod(hour, INT2FIX(12)); - set_hash("hour", f_add(hour, merid)); - } - } - - return hash; -} - -/* -Local variables: -c-file-style: "ruby" -End: -*/ diff --git a/ext/date/date_tmx.h b/ext/date/date_tmx.h deleted file mode 100644 index 993a1532..00000000 --- a/ext/date/date_tmx.h +++ /dev/null @@ -1,56 +0,0 @@ -#ifndef DATE_TMX_H -#define DATE_TMX_H - -struct tmx_funcs { - VALUE (*year)(void *dat); - int (*yday)(void *dat); - int (*mon)(void *dat); - int (*mday)(void *dat); - VALUE (*cwyear)(void *dat); - int (*cweek)(void *dat); - int (*cwday)(void *dat); - int (*wnum0)(void *dat); - int (*wnum1)(void *dat); - int (*wday)(void *dat); - int (*hour)(void *dat); - int (*min)(void *dat); - int (*sec)(void *dat); - VALUE (*sec_fraction)(void *dat); - VALUE (*secs)(void *dat); - VALUE (*msecs)(void *dat); - int (*offset)(void *dat); - char *(*zone)(void *dat); -}; -struct tmx { - void *dat; - const struct tmx_funcs *funcs; -}; - -#define tmx_attr(x) (tmx->funcs->x)(tmx->dat) - -#define tmx_year tmx_attr(year) -#define tmx_yday tmx_attr(yday) -#define tmx_mon tmx_attr(mon) -#define tmx_mday tmx_attr(mday) -#define tmx_cwyear tmx_attr(cwyear) -#define tmx_cweek tmx_attr(cweek) -#define tmx_cwday tmx_attr(cwday) -#define tmx_wnum0 tmx_attr(wnum0) -#define tmx_wnum1 tmx_attr(wnum1) -#define tmx_wday tmx_attr(wday) -#define tmx_hour tmx_attr(hour) -#define tmx_min tmx_attr(min) -#define tmx_sec tmx_attr(sec) -#define tmx_sec_fraction tmx_attr(sec_fraction) -#define tmx_secs tmx_attr(secs) -#define tmx_msecs tmx_attr(msecs) -#define tmx_offset tmx_attr(offset) -#define tmx_zone tmx_attr(zone) - -#endif - -/* -Local variables: -c-file-style: "ruby" -End: -*/ diff --git a/ext/date/extconf.rb b/ext/date/extconf.rb deleted file mode 100644 index f00d8771..00000000 --- a/ext/date/extconf.rb +++ /dev/null @@ -1,16 +0,0 @@ -# frozen_string_literal: true -require 'mkmf' - -if RUBY_VERSION >= "3.3" - # Pure Ruby implementation; skip C extension build - File.write("Makefile", dummy_makefile($srcdir).join("")) -else - config_string("strict_warnflags") {|w| $warnflags += " #{w}"} - append_cflags("-Wno-compound-token-split-by-macro") if RUBY_VERSION < "2.7." - have_func("rb_category_warn") - with_werror("", {:werror => true}) do |opt, | - have_var("timezone", "time.h", opt) - have_var("altzone", "time.h", opt) - end - create_makefile('date_core') -end diff --git a/ext/date/prereq.mk b/ext/date/prereq.mk index 79ea525a..ee761907 100644 --- a/ext/date/prereq.mk +++ b/ext/date/prereq.mk @@ -1,12 +1,3 @@ -.SUFFIXES: .list - -.list.h: - gperf --ignore-case -L ANSI-C -C -c -P -p -j1 -i 1 -g -o -t -N $(*F) $< \ - | sed -f $(top_srcdir)/tool/gperf.sed \ - > $(@F) - -zonetab.h: zonetab.list - .PHONY: update-zonetab update-zonetab: $(RUBY) -C $(srcdir) update-abbr diff --git a/ext/date/zonetab.h b/ext/date/zonetab.h deleted file mode 100644 index 2a2e8910..00000000 --- a/ext/date/zonetab.h +++ /dev/null @@ -1,1564 +0,0 @@ -/* ANSI-C code produced by gperf version 3.1 */ -/* Command-line: gperf --ignore-case -L ANSI-C -C -c -P -p -j1 -i 1 -g -o -t -N zonetab zonetab.list */ -/* Computed positions: -k'1-4,9' */ - -#if !((' ' == 32) && ('!' == 33) && ('"' == 34) && ('#' == 35) \ - && ('%' == 37) && ('&' == 38) && ('\'' == 39) && ('(' == 40) \ - && (')' == 41) && ('*' == 42) && ('+' == 43) && (',' == 44) \ - && ('-' == 45) && ('.' == 46) && ('/' == 47) && ('0' == 48) \ - && ('1' == 49) && ('2' == 50) && ('3' == 51) && ('4' == 52) \ - && ('5' == 53) && ('6' == 54) && ('7' == 55) && ('8' == 56) \ - && ('9' == 57) && (':' == 58) && (';' == 59) && ('<' == 60) \ - && ('=' == 61) && ('>' == 62) && ('?' == 63) && ('A' == 65) \ - && ('B' == 66) && ('C' == 67) && ('D' == 68) && ('E' == 69) \ - && ('F' == 70) && ('G' == 71) && ('H' == 72) && ('I' == 73) \ - && ('J' == 74) && ('K' == 75) && ('L' == 76) && ('M' == 77) \ - && ('N' == 78) && ('O' == 79) && ('P' == 80) && ('Q' == 81) \ - && ('R' == 82) && ('S' == 83) && ('T' == 84) && ('U' == 85) \ - && ('V' == 86) && ('W' == 87) && ('X' == 88) && ('Y' == 89) \ - && ('Z' == 90) && ('[' == 91) && ('\\' == 92) && (']' == 93) \ - && ('^' == 94) && ('_' == 95) && ('a' == 97) && ('b' == 98) \ - && ('c' == 99) && ('d' == 100) && ('e' == 101) && ('f' == 102) \ - && ('g' == 103) && ('h' == 104) && ('i' == 105) && ('j' == 106) \ - && ('k' == 107) && ('l' == 108) && ('m' == 109) && ('n' == 110) \ - && ('o' == 111) && ('p' == 112) && ('q' == 113) && ('r' == 114) \ - && ('s' == 115) && ('t' == 116) && ('u' == 117) && ('v' == 118) \ - && ('w' == 119) && ('x' == 120) && ('y' == 121) && ('z' == 122) \ - && ('{' == 123) && ('|' == 124) && ('}' == 125) && ('~' == 126)) -/* The character set is not based on ISO-646. */ -#error "gperf generated tables don't work with this execution character set. Please report a bug to ." -#endif - -#line 1 "zonetab.list" - -#define GPERF_DOWNCASE 1 -#define GPERF_CASE_STRNCMP 1 -#define gperf_case_strncmp strncasecmp -struct zone { - int name; - int offset; -}; -static const struct zone *zonetab(register const char *str, register size_t len); -#line 12 "zonetab.list" -struct zone; - -#define TOTAL_KEYWORDS 316 -#define MIN_WORD_LENGTH 1 -#define MAX_WORD_LENGTH 17 -#define MIN_HASH_VALUE 2 -#define MAX_HASH_VALUE 619 -/* maximum key range = 618, duplicates = 0 */ - -#ifndef GPERF_DOWNCASE -#define GPERF_DOWNCASE 1 -static unsigned char gperf_downcase[256] = - { - 0, 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, 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, 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 - }; -#endif - -#ifndef GPERF_CASE_STRNCMP -#define GPERF_CASE_STRNCMP 1 -static int -gperf_case_strncmp (register const char *s1, register const char *s2, register size_t n) -{ - for (; n > 0;) - { - unsigned char c1 = gperf_downcase[(unsigned char)*s1++]; - unsigned char c2 = gperf_downcase[(unsigned char)*s2++]; - if (c1 != 0 && c1 == c2) - { - n--; - continue; - } - return (int)c1 - (int)c2; - } - return 0; -} -#endif - -#ifdef __GNUC__ -__inline -#else -#ifdef __cplusplus -inline -#endif -#endif -static unsigned int -hash (register const char *str, register size_t len) -{ - static const unsigned short asso_values[] = - { - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 17, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 3, 2, 620, 620, 620, - 620, 620, 70, 8, 3, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 39, 176, 207, 70, 168, - 1, 5, 18, 74, 218, 2, 117, 130, 48, 88, - 125, 225, 92, 1, 1, 12, 54, 30, 36, 13, - 48, 168, 263, 59, 114, 166, 109, 39, 176, 207, - 70, 168, 1, 5, 18, 74, 218, 2, 117, 130, - 48, 88, 125, 225, 92, 1, 1, 12, 54, 30, - 36, 13, 48, 168, 263, 59, 114, 166, 109, 27, - 104, 1, 9, 4, 309, 190, 188, 177, 255, 108, - 2, 341, 3, 620, 620, 620, 620, 620, 620, 12, - 54, 30, 36, 13, 48, 168, 263, 59, 114, 166, - 109, 27, 104, 1, 9, 4, 309, 190, 188, 177, - 255, 108, 2, 341, 3, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620, 620, 620, - 620, 620, 620, 620, 620, 620, 620, 620 - }; - register unsigned int hval = (unsigned int)len; - - switch (hval) - { - default: - hval += asso_values[(unsigned char)str[8]]; - /*FALLTHROUGH*/ - case 8: - case 7: - case 6: - case 5: - case 4: - hval += asso_values[(unsigned char)str[3]]; - /*FALLTHROUGH*/ - case 3: - hval += asso_values[(unsigned char)str[2]]; - /*FALLTHROUGH*/ - case 2: - hval += asso_values[(unsigned char)str[1]+6]; - /*FALLTHROUGH*/ - case 1: - hval += asso_values[(unsigned char)str[0]+52]; - break; - } - return (unsigned int)hval; -} - -struct stringpool_t - { - char stringpool_str2[sizeof("o")]; - char stringpool_str3[sizeof("x")]; - char stringpool_str4[sizeof("z")]; - char stringpool_str5[sizeof("q")]; - char stringpool_str8[sizeof("omst")]; - char stringpool_str9[sizeof("omsst")]; - char stringpool_str10[sizeof("p")]; - char stringpool_str13[sizeof("a")]; - char stringpool_str14[sizeof("e")]; - char stringpool_str15[sizeof("pet")]; - char stringpool_str16[sizeof("pmst")]; - char stringpool_str17[sizeof("pett")]; - char stringpool_str18[sizeof("petst")]; - char stringpool_str19[sizeof("eet")]; - char stringpool_str20[sizeof("aest")]; - char stringpool_str21[sizeof("eest")]; - char stringpool_str22[sizeof("eat")]; - char stringpool_str24[sizeof("east")]; - char stringpool_str25[sizeof("easst")]; - char stringpool_str26[sizeof("pst")]; - char stringpool_str27[sizeof("eastern")]; - char stringpool_str28[sizeof("m")]; - char stringpool_str29[sizeof("ast")]; - char stringpool_str30[sizeof("est")]; - char stringpool_str31[sizeof("c")]; - char stringpool_str32[sizeof("mmt")]; - char stringpool_str33[sizeof("met")]; - char stringpool_str35[sizeof("mest")]; - char stringpool_str36[sizeof("cet")]; - char stringpool_str37[sizeof("d")]; - char stringpool_str38[sizeof("cest")]; - char stringpool_str39[sizeof("cat")]; - char stringpool_str41[sizeof("cast")]; - char stringpool_str42[sizeof("magt")]; - char stringpool_str43[sizeof("magst")]; - char stringpool_str44[sizeof("mst")]; - char stringpool_str45[sizeof("msk")]; - char stringpool_str46[sizeof("cot")]; - char stringpool_str47[sizeof("cst")]; - char stringpool_str48[sizeof("aqtt")]; - char stringpool_str49[sizeof("f")]; - char stringpool_str52[sizeof("art")]; - char stringpool_str53[sizeof("fnt")]; - char stringpool_str54[sizeof("fet")]; - char stringpool_str55[sizeof("b")]; - char stringpool_str57[sizeof("anat")]; - char stringpool_str58[sizeof("anast")]; - char stringpool_str59[sizeof("bnt")]; - char stringpool_str60[sizeof("i")]; - char stringpool_str61[sizeof("pht")]; - char stringpool_str62[sizeof("at")]; - char stringpool_str63[sizeof("zp6")]; - char stringpool_str64[sizeof("mewt")]; - char stringpool_str65[sizeof("fst")]; - char stringpool_str66[sizeof("ahst")]; - char stringpool_str67[sizeof("mawt")]; - char stringpool_str68[sizeof("zp5")]; - char stringpool_str70[sizeof("bot")]; - char stringpool_str71[sizeof("bst")]; - char stringpool_str72[sizeof("pwt")]; - char stringpool_str74[sizeof("pont")]; - char stringpool_str75[sizeof("iot")]; - char stringpool_str76[sizeof("ist")]; - char stringpool_str77[sizeof("awst")]; - char stringpool_str79[sizeof("mht")]; - char stringpool_str80[sizeof("mez")]; - char stringpool_str81[sizeof("orat")]; - char stringpool_str82[sizeof("mesz")]; - char stringpool_str84[sizeof("chst")]; - char stringpool_str85[sizeof("pmdt")]; - char stringpool_str88[sizeof("central")]; - char stringpool_str89[sizeof("aedt")]; - char stringpool_str90[sizeof("act")]; - char stringpool_str91[sizeof("ect")]; - char stringpool_str92[sizeof("acst")]; - char stringpool_str93[sizeof("eadt")]; - char stringpool_str94[sizeof("brt")]; - char stringpool_str95[sizeof("chut")]; - char stringpool_str96[sizeof("brst")]; - char stringpool_str97[sizeof("cen. australia")]; - char stringpool_str100[sizeof("davt")]; - char stringpool_str101[sizeof("irst")]; - char stringpool_str102[sizeof("irkt")]; - char stringpool_str103[sizeof("irkst")]; - char stringpool_str104[sizeof("bt")]; - char stringpool_str105[sizeof("n")]; - char stringpool_str106[sizeof("btt")]; - char stringpool_str107[sizeof("mountain")]; - char stringpool_str108[sizeof("cct")]; - char stringpool_str109[sizeof("w")]; - char stringpool_str110[sizeof("l")]; - char stringpool_str111[sizeof("fwt")]; - char stringpool_str113[sizeof("msd")]; - char stringpool_str114[sizeof("wet")]; - char stringpool_str116[sizeof("west")]; - char stringpool_str117[sizeof("wat")]; - char stringpool_str119[sizeof("wast")]; - char stringpool_str120[sizeof("wakt")]; - char stringpool_str121[sizeof("nst")]; - char stringpool_str122[sizeof("acwst")]; - char stringpool_str123[sizeof("chast")]; - char stringpool_str124[sizeof("cist")]; - char stringpool_str125[sizeof("azt")]; - char stringpool_str126[sizeof("clt")]; - char stringpool_str127[sizeof("azst")]; - char stringpool_str128[sizeof("clst")]; - char stringpool_str129[sizeof("mart")]; - char stringpool_str130[sizeof("zp4")]; - char stringpool_str131[sizeof("jst")]; - char stringpool_str132[sizeof("central asia")]; - char stringpool_str133[sizeof("aft")]; - char stringpool_str134[sizeof("e. south america")]; - char stringpool_str135[sizeof("central america")]; - char stringpool_str137[sizeof("ict")]; - char stringpool_str143[sizeof("pgt")]; - char stringpool_str144[sizeof("nrt")]; - char stringpool_str145[sizeof("mexico")]; - char stringpool_str146[sizeof("awdt")]; - char stringpool_str147[sizeof("egt")]; - char stringpool_str148[sizeof("cxt")]; - char stringpool_str149[sizeof("egst")]; - char stringpool_str150[sizeof("phot")]; - char stringpool_str151[sizeof("alaskan")]; - char stringpool_str154[sizeof("nt")]; - char stringpool_str158[sizeof("wt")]; - char stringpool_str160[sizeof("west asia")]; - char stringpool_str161[sizeof("acdt")]; - char stringpool_str162[sizeof("npt")]; - char stringpool_str163[sizeof("lhst")]; - char stringpool_str164[sizeof("afghanistan")]; - char stringpool_str167[sizeof("k")]; - char stringpool_str169[sizeof("g")]; - char stringpool_str170[sizeof("irdt")]; - char stringpool_str171[sizeof("chot")]; - char stringpool_str172[sizeof("chost")]; - char stringpool_str173[sizeof("gmt")]; - char stringpool_str174[sizeof("get")]; - char stringpool_str175[sizeof("novt")]; - char stringpool_str176[sizeof("novst")]; - char stringpool_str177[sizeof("fjt")]; - char stringpool_str178[sizeof("u")]; - char stringpool_str179[sizeof("fjst")]; - char stringpool_str181[sizeof("pyst")]; - char stringpool_str182[sizeof("nct")]; - char stringpool_str183[sizeof("kst")]; - char stringpool_str184[sizeof("kost")]; - char stringpool_str185[sizeof("gst")]; - char stringpool_str186[sizeof("iran")]; - char stringpool_str187[sizeof("e. africa")]; - char stringpool_str188[sizeof("wadt")]; - char stringpool_str189[sizeof("t")]; - char stringpool_str190[sizeof("e. australia")]; - char stringpool_str191[sizeof("s")]; - char stringpool_str192[sizeof("chadt")]; - char stringpool_str193[sizeof("tmt")]; - char stringpool_str194[sizeof("cidst")]; - char stringpool_str195[sizeof("aoe")]; - char stringpool_str197[sizeof("myt")]; - char stringpool_str198[sizeof("west pacific")]; - char stringpool_str199[sizeof("mut")]; - char stringpool_str200[sizeof("wit")]; - char stringpool_str201[sizeof("sast")]; - char stringpool_str202[sizeof("sakt")]; - char stringpool_str203[sizeof("new zealand")]; - char stringpool_str204[sizeof("tot")]; - char stringpool_str205[sizeof("china")]; - char stringpool_str206[sizeof("tost")]; - char stringpool_str207[sizeof("sst")]; - char stringpool_str209[sizeof("india")]; - char stringpool_str211[sizeof("warst")]; - char stringpool_str212[sizeof("sbt")]; - char stringpool_str214[sizeof("azot")]; - char stringpool_str215[sizeof("azost")]; - char stringpool_str216[sizeof("taht")]; - char stringpool_str217[sizeof("nzt")]; - char stringpool_str218[sizeof("dateline")]; - char stringpool_str219[sizeof("nzst")]; - char stringpool_str220[sizeof("tokyo")]; - char stringpool_str221[sizeof("central pacific")]; - char stringpool_str223[sizeof("qyzt")]; - char stringpool_str224[sizeof("atlantic")]; - char stringpool_str225[sizeof("nft")]; - char stringpool_str227[sizeof("ut")]; - char stringpool_str228[sizeof("trt")]; - char stringpool_str229[sizeof("wft")]; - char stringpool_str230[sizeof("srt")]; - char stringpool_str231[sizeof("pdt")]; - char stringpool_str232[sizeof("lhdt")]; - char stringpool_str234[sizeof("adt")]; - char stringpool_str235[sizeof("edt")]; - char stringpool_str238[sizeof("pkt")]; - char stringpool_str239[sizeof("almt")]; - char stringpool_str240[sizeof("wita")]; - char stringpool_str242[sizeof("wgt")]; - char stringpool_str243[sizeof("akst")]; - char stringpool_str244[sizeof("wgst")]; - char stringpool_str246[sizeof("krat")]; - char stringpool_str247[sizeof("krast")]; - char stringpool_str248[sizeof("mid-atlantic")]; - char stringpool_str249[sizeof("mdt")]; - char stringpool_str250[sizeof("lint")]; - char stringpool_str251[sizeof("malay peninsula")]; - char stringpool_str252[sizeof("cdt")]; - char stringpool_str253[sizeof("swt")]; - char stringpool_str255[sizeof("se asia")]; - char stringpool_str256[sizeof("v")]; - char stringpool_str258[sizeof("tonga")]; - char stringpool_str259[sizeof("ckt")]; - char stringpool_str261[sizeof("vet")]; - char stringpool_str262[sizeof("caucasus")]; - char stringpool_str263[sizeof("central europe")]; - char stringpool_str264[sizeof("h")]; - char stringpool_str265[sizeof("central european")]; - char stringpool_str266[sizeof("newfoundland")]; - char stringpool_str267[sizeof("arab")]; - char stringpool_str268[sizeof("sct")]; - char stringpool_str269[sizeof("arabic")]; - char stringpool_str270[sizeof("arabian")]; - char stringpool_str271[sizeof("ddut")]; - char stringpool_str273[sizeof("vost")]; - char stringpool_str274[sizeof("hast")]; - char stringpool_str275[sizeof("nepal")]; - char stringpool_str276[sizeof("nut")]; - char stringpool_str277[sizeof("fkt")]; - char stringpool_str279[sizeof("fkst")]; - char stringpool_str280[sizeof("hst")]; - char stringpool_str281[sizeof("idt")]; - char stringpool_str284[sizeof("tlt")]; - char stringpool_str285[sizeof("w. australia")]; - char stringpool_str286[sizeof("egypt")]; - char stringpool_str287[sizeof("myanmar")]; - char stringpool_str288[sizeof("nzdt")]; - char stringpool_str289[sizeof("gft")]; - char stringpool_str290[sizeof("uzt")]; - char stringpool_str293[sizeof("north asia")]; - char stringpool_str294[sizeof("mvt")]; - char stringpool_str295[sizeof("galt")]; - char stringpool_str296[sizeof("nfdt")]; - char stringpool_str297[sizeof("cvt")]; - char stringpool_str298[sizeof("north asia east")]; - char stringpool_str300[sizeof("kgt")]; - char stringpool_str301[sizeof("aus central")]; - char stringpool_str302[sizeof("pacific")]; - char stringpool_str304[sizeof("canada central")]; - char stringpool_str306[sizeof("pacific sa")]; - char stringpool_str307[sizeof("azores")]; - char stringpool_str308[sizeof("gamt")]; - char stringpool_str309[sizeof("tft")]; - char stringpool_str310[sizeof("r")]; - char stringpool_str311[sizeof("fle")]; - char stringpool_str312[sizeof("akdt")]; - char stringpool_str313[sizeof("ulat")]; - char stringpool_str314[sizeof("ulast")]; - char stringpool_str315[sizeof("ret")]; - char stringpool_str317[sizeof("tjt")]; - char stringpool_str319[sizeof("south africa")]; - char stringpool_str324[sizeof("sgt")]; - char stringpool_str326[sizeof("ndt")]; - char stringpool_str327[sizeof("rott")]; - char stringpool_str330[sizeof("samt")]; - char stringpool_str332[sizeof("tasmania")]; - char stringpool_str334[sizeof("hovt")]; - char stringpool_str335[sizeof("hovst")]; - char stringpool_str338[sizeof("gyt")]; - char stringpool_str342[sizeof("y")]; - char stringpool_str343[sizeof("hadt")]; - char stringpool_str344[sizeof("sa western")]; - char stringpool_str345[sizeof("hawaiian")]; - char stringpool_str347[sizeof("uyt")]; - char stringpool_str349[sizeof("uyst")]; - char stringpool_str350[sizeof("yekt")]; - char stringpool_str351[sizeof("yekst")]; - char stringpool_str352[sizeof("kuyt")]; - char stringpool_str353[sizeof("yakt")]; - char stringpool_str354[sizeof("yakst")]; - char stringpool_str358[sizeof("yst")]; - char stringpool_str359[sizeof("jerusalem")]; - char stringpool_str365[sizeof("sri lanka")]; - char stringpool_str367[sizeof("yakutsk")]; - char stringpool_str375[sizeof("wib")]; - char stringpool_str377[sizeof("aus eastern")]; - char stringpool_str378[sizeof("gilt")]; - char stringpool_str387[sizeof("us mountain")]; - char stringpool_str391[sizeof("vlat")]; - char stringpool_str392[sizeof("vlast")]; - char stringpool_str395[sizeof("gtb")]; - char stringpool_str398[sizeof("taipei")]; - char stringpool_str399[sizeof("sret")]; - char stringpool_str408[sizeof("cape verde")]; - char stringpool_str417[sizeof("tkt")]; - char stringpool_str418[sizeof("samoa")]; - char stringpool_str421[sizeof("sa pacific")]; - char stringpool_str427[sizeof("vut")]; - char stringpool_str428[sizeof("idlw")]; - char stringpool_str432[sizeof("fiji")]; - char stringpool_str435[sizeof("utc")]; - char stringpool_str443[sizeof("korea")]; - char stringpool_str445[sizeof("e. europe")]; - char stringpool_str449[sizeof("syot")]; - char stringpool_str452[sizeof("n. central asia")]; - char stringpool_str455[sizeof("tvt")]; - char stringpool_str458[sizeof("w. central africa")]; - char stringpool_str466[sizeof("ekaterinburg")]; - char stringpool_str468[sizeof("vladivostok")]; - char stringpool_str476[sizeof("yapt")]; - char stringpool_str477[sizeof("us eastern")]; - char stringpool_str482[sizeof("sa eastern")]; - char stringpool_str485[sizeof("hdt")]; - char stringpool_str486[sizeof("russian")]; - char stringpool_str492[sizeof("hkt")]; - char stringpool_str497[sizeof("romance")]; - char stringpool_str540[sizeof("w. europe")]; - char stringpool_str563[sizeof("ydt")]; - char stringpool_str566[sizeof("idle")]; - char stringpool_str567[sizeof("greenwich")]; - char stringpool_str619[sizeof("greenland")]; - }; -static const struct stringpool_t stringpool_contents = - { - "o", - "x", - "z", - "q", - "omst", - "omsst", - "p", - "a", - "e", - "pet", - "pmst", - "pett", - "petst", - "eet", - "aest", - "eest", - "eat", - "east", - "easst", - "pst", - "eastern", - "m", - "ast", - "est", - "c", - "mmt", - "met", - "mest", - "cet", - "d", - "cest", - "cat", - "cast", - "magt", - "magst", - "mst", - "msk", - "cot", - "cst", - "aqtt", - "f", - "art", - "fnt", - "fet", - "b", - "anat", - "anast", - "bnt", - "i", - "pht", - "at", - "zp6", - "mewt", - "fst", - "ahst", - "mawt", - "zp5", - "bot", - "bst", - "pwt", - "pont", - "iot", - "ist", - "awst", - "mht", - "mez", - "orat", - "mesz", - "chst", - "pmdt", - "central", - "aedt", - "act", - "ect", - "acst", - "eadt", - "brt", - "chut", - "brst", - "cen. australia", - "davt", - "irst", - "irkt", - "irkst", - "bt", - "n", - "btt", - "mountain", - "cct", - "w", - "l", - "fwt", - "msd", - "wet", - "west", - "wat", - "wast", - "wakt", - "nst", - "acwst", - "chast", - "cist", - "azt", - "clt", - "azst", - "clst", - "mart", - "zp4", - "jst", - "central asia", - "aft", - "e. south america", - "central america", - "ict", - "pgt", - "nrt", - "mexico", - "awdt", - "egt", - "cxt", - "egst", - "phot", - "alaskan", - "nt", - "wt", - "west asia", - "acdt", - "npt", - "lhst", - "afghanistan", - "k", - "g", - "irdt", - "chot", - "chost", - "gmt", - "get", - "novt", - "novst", - "fjt", - "u", - "fjst", - "pyst", - "nct", - "kst", - "kost", - "gst", - "iran", - "e. africa", - "wadt", - "t", - "e. australia", - "s", - "chadt", - "tmt", - "cidst", - "aoe", - "myt", - "west pacific", - "mut", - "wit", - "sast", - "sakt", - "new zealand", - "tot", - "china", - "tost", - "sst", - "india", - "warst", - "sbt", - "azot", - "azost", - "taht", - "nzt", - "dateline", - "nzst", - "tokyo", - "central pacific", - "qyzt", - "atlantic", - "nft", - "ut", - "trt", - "wft", - "srt", - "pdt", - "lhdt", - "adt", - "edt", - "pkt", - "almt", - "wita", - "wgt", - "akst", - "wgst", - "krat", - "krast", - "mid-atlantic", - "mdt", - "lint", - "malay peninsula", - "cdt", - "swt", - "se asia", - "v", - "tonga", - "ckt", - "vet", - "caucasus", - "central europe", - "h", - "central european", - "newfoundland", - "arab", - "sct", - "arabic", - "arabian", - "ddut", - "vost", - "hast", - "nepal", - "nut", - "fkt", - "fkst", - "hst", - "idt", - "tlt", - "w. australia", - "egypt", - "myanmar", - "nzdt", - "gft", - "uzt", - "north asia", - "mvt", - "galt", - "nfdt", - "cvt", - "north asia east", - "kgt", - "aus central", - "pacific", - "canada central", - "pacific sa", - "azores", - "gamt", - "tft", - "r", - "fle", - "akdt", - "ulat", - "ulast", - "ret", - "tjt", - "south africa", - "sgt", - "ndt", - "rott", - "samt", - "tasmania", - "hovt", - "hovst", - "gyt", - "y", - "hadt", - "sa western", - "hawaiian", - "uyt", - "uyst", - "yekt", - "yekst", - "kuyt", - "yakt", - "yakst", - "yst", - "jerusalem", - "sri lanka", - "yakutsk", - "wib", - "aus eastern", - "gilt", - "us mountain", - "vlat", - "vlast", - "gtb", - "taipei", - "sret", - "cape verde", - "tkt", - "samoa", - "sa pacific", - "vut", - "idlw", - "fiji", - "utc", - "korea", - "e. europe", - "syot", - "n. central asia", - "tvt", - "w. central africa", - "ekaterinburg", - "vladivostok", - "yapt", - "us eastern", - "sa eastern", - "hdt", - "russian", - "hkt", - "romance", - "w. europe", - "ydt", - "idle", - "greenwich", - "greenland" - }; -#define stringpool ((const char *) &stringpool_contents) -const struct zone * -zonetab (register const char *str, register size_t len) -{ - static const struct zone wordlist[] = - { - {-1}, {-1}, -#line 37 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str2, -2*3600}, -#line 46 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str3, -11*3600}, -#line 48 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str4, 0*3600}, -#line 39 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str5, -4*3600}, - {-1}, {-1}, -#line 272 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str8,21600}, -#line 271 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str9,25200}, -#line 38 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str10, -3*3600}, - {-1}, {-1}, -#line 24 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str13, 1*3600}, -#line 28 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str14, 5*3600}, -#line 274 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str15,-18000}, -#line 282 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str16,-10800}, -#line 276 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str17,43200}, -#line 275 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str18,43200}, -#line 83 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str19, 2*3600}, -#line 189 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str20,36000}, -#line 91 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str21, 3*3600}, -#line 90 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str22, 3*3600}, - {-1}, -#line 104 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str24,-6*3600}, -#line 220 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str25,-18000}, -#line 22 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str26, -8*3600}, -#line 136 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str27, -18000}, -#line 35 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str28, 12*3600}, -#line 59 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str29, -4*3600}, -#line 16 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str30, -5*3600}, -#line 26 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str31, 3*3600}, -#line 259 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str32,23400}, -#line 76 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str33, 1*3600}, - {-1}, -#line 85 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str35, 2*3600}, -#line 74 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str36, 1*3600}, -#line 27 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str37, 4*3600}, -#line 82 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str38, 2*3600}, -#line 68 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str39,2*3600}, - {-1}, -#line 205 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str41,28800}, -#line 255 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str42,39600}, -#line 254 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str43,43200}, -#line 20 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str44, -7*3600}, -#line 92 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str45, 3*3600}, -#line 215 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str46,-18000}, -#line 18 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str47, -6*3600}, -#line 195 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str48,18000}, -#line 29 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str49, 6*3600}, - {-1}, {-1}, -#line 54 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str52, -3*3600}, -#line 229 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str53,-7200}, -#line 224 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str54,10800}, -#line 25 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str55, 2*3600}, - {-1}, -#line 193 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str57,43200}, -#line 192 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str58,43200}, -#line 202 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str59,28800}, -#line 32 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str60, 9*3600}, -#line 279 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str61,28800}, -#line 51 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str62, -2*3600}, -#line 97 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str63, 6*3600}, -#line 77 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str64, 1*3600}, -#line 84 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str65, 2*3600}, -#line 67 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str66,-10*3600}, -#line 257 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str67,18000}, -#line 95 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str68, 5*3600}, - {-1}, -#line 203 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str70,-14400}, -#line 73 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str71, 1*3600}, -#line 284 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str72,32400}, - {-1}, -#line 283 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str74,39600}, -#line 241 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str75,21600}, -#line 96 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str76, (5*3600+1800)}, -#line 197 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str77,28800}, - {-1}, -#line 258 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str79,43200}, -#line 78 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str80, 1*3600}, -#line 273 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str81,18000}, -#line 86 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str82, 2*3600}, - {-1}, -#line 210 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str84,36000}, -#line 281 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str85,-7200}, - {-1}, {-1}, -#line 129 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str88, -21600}, -#line 188 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str89,39600}, -#line 186 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str90,-18000}, -#line 221 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str91,-18000}, -#line 185 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str92,34200}, -#line 106 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str93,11*3600}, -#line 56 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str94, -3*3600}, -#line 211 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str95,36000}, -#line 52 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str96,-2*3600}, -#line 123 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str97, 34200}, - {-1}, {-1}, -#line 218 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str100,25200}, -#line 245 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str101,12600}, -#line 244 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str102,28800}, -#line 243 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str103,32400}, -#line 89 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str104, 3*3600}, -#line 36 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str105, -1*3600}, -#line 204 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str106,21600}, -#line 151 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str107, -25200}, -#line 99 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str108, (6*3600+1800)}, -#line 45 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str109, -10*3600}, -#line 34 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str110, 11*3600}, -#line 75 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str111, 1*3600}, - {-1}, -#line 93 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str113, 4*3600}, -#line 50 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str114, 0*3600}, - {-1}, -#line 81 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str116, 1*3600}, -#line 80 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str117, 1*3600}, - {-1}, -#line 98 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str119, 2*3600}, -#line 316 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str120,43200}, -#line 58 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str121, -(2*3600+1800)}, -#line 187 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str122,31500}, -#line 207 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str123,45900}, -#line 213 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str124,-18000}, -#line 201 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str125,14400}, -#line 60 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str126, -4*3600}, -#line 200 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str127,18000}, -#line 57 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str128,-3*3600}, -#line 256 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str129,-30600}, -#line 94 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str130, 4*3600}, -#line 102 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str131, 9*3600}, -#line 125 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str132, 21600}, -#line 190 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str133,16200}, -#line 135 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str134, -10800}, -#line 124 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str135, -21600}, - {-1}, -#line 239 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str137,25200}, - {-1}, {-1}, {-1}, {-1}, {-1}, -#line 277 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str143,36000}, -#line 269 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str144,43200}, -#line 149 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str145, -21600}, -#line 196 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str146,32400}, -#line 223 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str147,-3600}, -#line 217 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str148,25200}, -#line 222 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str149,0}, -#line 278 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str150,46800}, -#line 112 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str151, -32400}, - {-1}, {-1}, -#line 71 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str154, -11*3600}, - {-1}, {-1}, {-1}, -#line 324 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str158,0}, - {-1}, -#line 181 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str160, 18000}, -#line 184 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str161,37800}, -#line 268 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str162,20700}, -#line 252 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str163,37800}, -#line 111 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str164, 16200}, - {-1}, {-1}, -#line 33 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str167, 10*3600}, - {-1}, -#line 30 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str169, 7*3600}, -#line 242 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str170,16200}, -#line 209 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str171,28800}, -#line 208 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str172,32400}, -#line 15 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str173, 0*3600}, -#line 232 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str174,14400}, -#line 267 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str175,25200}, -#line 266 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str176,25200}, -#line 226 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str177,43200}, -#line 43 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str178, -8*3600}, -#line 225 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str179,46800}, - {-1}, -#line 285 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str181,-10800}, -#line 263 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str182,39600}, -#line 103 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str183, 9*3600}, -#line 247 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str184,39600}, -#line 105 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str185, 10*3600}, -#line 146 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str186, 12600}, -#line 132 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str187, 10800}, -#line 101 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str188, 8*3600}, -#line 42 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str189, -7*3600}, -#line 133 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str190, 36000}, -#line 41 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str191, -6*3600}, -#line 206 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str192,49500}, -#line 301 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str193,18000}, -#line 212 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str194,-14400}, -#line 194 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str195,-43200}, - {-1}, -#line 262 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str197,28800}, -#line 182 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str198, 36000}, -#line 260 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str199,14400}, -#line 322 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str200,32400}, -#line 87 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str201, 2*3600}, -#line 289 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str202,39600}, -#line 155 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str203, 43200}, -#line 303 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str204,46800}, -#line 130 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str205, 28800}, -#line 302 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str206,50400}, -#line 88 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str207, -11*3600}, - {-1}, -#line 145 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str209, 19800}, - {-1}, -#line 317 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str211,-10800}, -#line 291 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str212,39600}, - {-1}, -#line 199 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str214,-3600}, -#line 198 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str215,0}, -#line 296 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str216,-36000}, -#line 109 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str217, 12*3600}, -#line 131 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str218, -43200}, -#line 108 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str219,12*3600}, -#line 173 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str220, 32400}, -#line 128 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str221, 39600}, - {-1}, -#line 286 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str223,21600}, -#line 116 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str224, -14400}, -#line 265 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str225,39600}, - {-1}, -#line 14 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str227, 0*3600}, -#line 304 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str228,10800}, -#line 318 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str229,43200}, -#line 294 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str230,-10800}, -#line 23 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str231, -7*3600}, -#line 251 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str232,39600}, - {-1}, -#line 55 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str234, -3*3600}, -#line 17 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str235, -4*3600}, - {-1}, {-1}, -#line 280 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str238,18000}, -#line 191 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str239,21600}, -#line 323 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str240,28800}, - {-1}, -#line 320 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str242,-7200}, -#line 63 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str243,-9*3600}, -#line 319 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str244,-3600}, - {-1}, -#line 249 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str246,25200}, -#line 248 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str247,28800}, -#line 150 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str248, -7200}, -#line 21 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str249, -6*3600}, -#line 253 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str250,50400}, -#line 168 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str251, 28800}, -#line 19 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str252, -5*3600}, -#line 79 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str253, 1*3600}, - {-1}, -#line 167 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str255, 25200}, -#line 44 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str256, -9*3600}, - {-1}, -#line 174 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str258, 46800}, -#line 214 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str259,-36000}, - {-1}, -#line 311 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str261,-14400}, -#line 122 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str262, 14400}, -#line 126 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str263, 3600}, -#line 31 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str264, 8*3600}, -#line 127 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str265, 3600}, -#line 156 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str266, -12600}, -#line 113 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str267, 10800}, -#line 292 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str268,14400}, -#line 115 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str269, 10800}, -#line 114 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str270, 14400}, -#line 219 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str271,36000}, - {-1}, -#line 314 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str273,21600}, -#line 69 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str274,-10*3600}, -#line 154 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str275, 20700}, -#line 270 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str276,-39600}, -#line 228 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str277,-14400}, - {-1}, -#line 227 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str279,-10800}, -#line 70 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str280,-10*3600}, -#line 240 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str281,10800}, - {-1}, {-1}, -#line 300 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str284,32400}, -#line 178 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str285, 28800}, -#line 137 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str286, 7200}, -#line 152 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str287, 23400}, -#line 110 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str288,13*3600}, -#line 233 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str289,-10800}, -#line 310 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str290,18000}, - {-1}, {-1}, -#line 158 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str293, 25200}, -#line 261 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str294,18000}, -#line 230 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str295,-21600}, -#line 264 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str296,43200}, -#line 216 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str297,-3600}, -#line 157 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str298, 28800}, - {-1}, -#line 246 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str300,21600}, -#line 117 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str301, 34200}, -#line 160 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str302, -28800}, - {-1}, -#line 120 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str304, -21600}, - {-1}, -#line 159 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str306, -14400}, -#line 119 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str307, -3600}, -#line 231 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str308,-32400}, -#line 297 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str309,18000}, -#line 40 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str310, -5*3600}, -#line 140 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str311, 7200}, -#line 61 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str312,-8*3600}, -#line 307 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str313,28800}, -#line 306 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str314,32400}, -#line 287 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str315,14400}, - {-1}, -#line 298 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str317,18000}, - {-1}, -#line 169 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str319, 7200}, - {-1}, {-1}, {-1}, {-1}, -#line 100 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str324, 8*3600}, - {-1}, -#line 53 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str326, -(1*3600+1800)}, -#line 288 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str327,-10800}, - {-1}, {-1}, -#line 290 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str330,14400}, - {-1}, -#line 172 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str332, 36000}, - {-1}, -#line 238 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str334,25200}, -#line 237 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str335,28800}, - {-1}, {-1}, -#line 235 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str338,-14400}, - {-1}, {-1}, {-1}, -#line 47 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str342, -12*3600}, -#line 64 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str343,-9*3600}, -#line 165 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str344, -14400}, -#line 144 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str345, -36000}, - {-1}, -#line 309 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str347,-10800}, - {-1}, -#line 308 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str349,-7200}, -#line 329 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str350,18000}, -#line 328 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str351,21600}, -#line 250 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str352,14400}, -#line 326 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str353,32400}, -#line 325 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str354,36000}, - {-1}, {-1}, {-1}, -#line 66 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str358, -9*3600}, -#line 147 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str359, 7200}, - {-1}, {-1}, {-1}, {-1}, {-1}, -#line 170 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str365, 21600}, - {-1}, -#line 183 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str367, 32400}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, -#line 321 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str375,25200}, - {-1}, -#line 118 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str377, 36000}, -#line 234 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str378,43200}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, -#line 176 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str387, -25200}, - {-1}, {-1}, {-1}, -#line 313 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str391,36000}, -#line 312 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str392,39600}, - {-1}, {-1}, -#line 143 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str395, 7200}, - {-1}, {-1}, -#line 171 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str398, 28800}, -#line 293 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str399,39600}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, -#line 121 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str408, -3600}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, -#line 299 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str417,46800}, -#line 166 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str418, -39600}, - {-1}, {-1}, -#line 164 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str421, -18000}, - {-1}, {-1}, {-1}, {-1}, {-1}, -#line 315 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str427,39600}, -#line 72 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str428,-12*3600}, - {-1}, {-1}, {-1}, -#line 139 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str432, 43200}, - {-1}, {-1}, -#line 49 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str435, 0*3600}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, -#line 148 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str443, 32400}, - {-1}, -#line 134 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str445, 7200}, - {-1}, {-1}, {-1}, -#line 295 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str449,10800}, - {-1}, {-1}, -#line 153 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str452, 21600}, - {-1}, {-1}, -#line 305 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str455,43200}, - {-1}, {-1}, -#line 179 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str458, 3600}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, -#line 138 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str466, 18000}, - {-1}, -#line 177 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str468, 36000}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, -#line 327 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str476,36000}, -#line 175 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str477, -18000}, - {-1}, {-1}, {-1}, {-1}, -#line 163 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str482, -10800}, - {-1}, {-1}, -#line 65 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str485, -9*3600}, -#line 162 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str486, 10800}, - {-1}, {-1}, {-1}, {-1}, {-1}, -#line 236 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str492,28800}, - {-1}, {-1}, {-1}, {-1}, -#line 161 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str497, 3600}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, -#line 180 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str540, 3600}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, - {-1}, {-1}, {-1}, {-1}, -#line 62 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str563, -8*3600}, - {-1}, {-1}, -#line 107 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str566,12*3600}, -#line 142 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str567, 0}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, - {-1}, {-1}, {-1}, {-1}, {-1}, {-1}, -#line 141 "zonetab.list" - {(int)(size_t)&((struct stringpool_t *)0)->stringpool_str619, -10800} - }; - - if (len <= MAX_WORD_LENGTH && len >= MIN_WORD_LENGTH) - { - register unsigned int key = hash (str, len); - - if (key <= MAX_HASH_VALUE) - { - register int o = wordlist[key].name; - if (o >= 0) - { - register const char *s = o + stringpool; - - if ((((unsigned char)*str ^ (unsigned char)*s) & ~32) == 0 && !gperf_case_strncmp (str, s, len) && s[len] == '\0') - return &wordlist[key]; - } - } - } - return 0; -} -#line 330 "zonetab.list" - diff --git a/lib/date.rb b/lib/date.rb index 55bdb526..39b7a78c 100644 --- a/lib/date.rb +++ b/lib/date.rb @@ -4,19 +4,15 @@ require 'timeout' require 'strscan' -if RUBY_VERSION >= "3.3" - require_relative "date/version" - require_relative "date/shared" - require_relative "date/constants" - require_relative "date/core" - require_relative "date/strftime" - require_relative "date/parse" - require_relative "date/strptime" - require_relative "date/time" - require_relative "date/datetime" -else - require 'date_core' -end +require_relative "date/version" +require_relative "date/shared" +require_relative "date/constants" +require_relative "date/core" +require_relative "date/strftime" +require_relative "date/parse" +require_relative "date/strptime" +require_relative "date/time" +require_relative "date/datetime" class Date # call-seq: diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index d905daba..2cfef558 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -610,7 +610,7 @@ def sp_zone(str, si, slen, hash) # Convert a zone string to seconds offset from UTC. # Returns Integer (seconds) or Rational, or nil if unparseable. - # Mirrors date_zone_to_diff() in ext/date/date_parse.c. + # Ported from the original C date_zone_to_diff(). def sp_zone_to_diff(zone_str) # Fast path for common numeric zones len = zone_str.length @@ -852,7 +852,7 @@ def sp_complete_frags(klass, hash) # Convert year/week/wday to Julian Day number. # f=0: Sunday-based (%U), d=0=Sun..6=Sat # f=1: Monday-based (%W), d=0=Mon..6=Sun (Mon-based) - # Mirrors c_weeknum_to_jd() in ext/date/date_core.c: + # Ported from the original C c_weeknum_to_jd(): # rjd2 = JD(Jan 1) + 6 (= JD of Jan 7) # return (rjd2 - MOD((rjd2 - f + 1), 7) - 7) + 7*w + d def sp_weeknum_to_jd(y, w, d, f, sg) From f6a2947f3e01c6e438adc10c832602ad6b2d93c2 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 20 Jun 2026 14:44:51 +0900 Subject: [PATCH 029/144] Fix calendar-reform validation in civil/ordinal/commercial Date validation under a finite cutover (e.g. ITALY, ENGLAND) used the Gregorian rule unconditionally, so dates on or before the reform were mishandled. Verified against the C extension as ground truth, the pure Ruby implementation diverged on: - Julian-only leap days, e.g. Date.new(1500,2,29,ITALY) raised instead of returning 1500-02-29, and valid_civil? returned false. - Reform-gap days, e.g. Date.new(1582,10,10,ITALY) silently returned 1582-10-20 (data corruption) instead of raising; ENGLAND 1752-09-03 .. 13 likewise. - The shortened reform year, e.g. Date.ordinal(1582,356,ITALY) and Date.commercial(1582,52,1,ITALY) returned dates in the next year instead of raising. Root cause: the fast paths and internal_valid_civil?/internal_valid_ordinal? chose the calendar by `sg == Float::INFINITY` only, and never rejected days skipped at the reform. Fixes: - civil fast path: inline civil_to_jd for days 1..28 and detect the reform gap (gjd < start <= jjd); delegate the rest to civil_fallback. - ordinal / commercial fast paths: bound the result by the start of the next (commercial) year so the shortened reform year is respected. - internal_valid_civil?: validate on the Gregorian side first, then the Julian side (accepting Julian-only leap days and rejecting gap days via jjd >= sg) without a round-trip. - internal_valid_ordinal?: derive the true year length from the difference of the two Jan 1 JDs, which already accounts for the reform year. All 64 calendar oracle cases (ITALY/ENGLAND/JULIAN/GREGORIAN, gap days, pre-reform leap, reform-year ordinal/commercial, negative mday/yday) now match the C extension. Official suite: 144 tests, 162595 assertions, 0 failures, 0 errors, 100%; no -w warnings. Performance (YJIT, i/s) vs the C baseline (4.0.1_system.tsv): method C ext pure Ruby ratio civil 4,648,499 6,816,000 147% ordinal 3,023,007 7,224,000 239% commercial 2,478,941 5,209,000 210% valid_civil? 10,749,223 4,752,000 44% valid_ordinal? 4,233,714 12,035,000 284% valid_commercial? 3,177,115 3,199,000 101% valid_civil? stays below the C baseline, but it already was before this change (~47%); C's valid_civil? is exceptionally fast and the pure Ruby version has never matched it. This change moves it only ~6% (5.05M -> 4.75M) for the added correctness. --- lib/date/core.rb | 93 ++++++++++++++++++++++++++++++------------------ 1 file changed, 59 insertions(+), 34 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index b937920c..12f999a9 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -12,23 +12,24 @@ class Date class << self # Same as Date.new. def civil(year = -4712, month = 1, day = 1, start = DEFAULT_SG) - if Integer === year && Integer === month && Integer === day && month >= 1 && month <= 12 - if day >= 1 && day <= 28 - return new_from_jd(civil_to_jd(year, month, day, start), start) - elsif day >= -31 - dim = if month == 2 - if start == Float::INFINITY - year % 4 == 0 ? 29 : 28 - else - (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0)) ? 29 : 28 - end - else - DAYS_IN_MONTH_GREGORIAN[month] - end - d = day < 0 ? day + dim + 1 : day - if d >= 1 && d <= dim - return new_from_jd(civil_to_jd(year, month, d, start), start) - end + if Integer === year && Integer === month && Integer === day && + month >= 1 && month <= 12 && day >= 1 && day <= 28 + # Days 1..28 exist in every month of both the Julian and Gregorian + # calendars, so such a date can only be invalid if it falls in the gap + # skipped at the calendar reform (gregorian jd < start <= julian jd). + # Inline civil_to_jd so the reform gap can be detected without a second + # pass: keep both the Gregorian and Julian Julian Day numbers. + yy = month <= 2 ? year - 1 : year + gjd_base = (1461 * (yy + 4716)) / 4 + GJD_MONTH_OFFSET[month] + day + a = yy / 100 + gjd = gjd_base - 1524 + 2 - a + a / 4 + if gjd >= start + return new_from_jd(gjd, start) + else + jjd = gjd_base - 1524 + return new_from_jd(jjd, start) if jjd < start + # gjd < start <= jjd: date falls in the reform gap; fall through to + # civil_fallback, which raises "invalid date". end end civil_fallback(year, month, day, start) @@ -187,7 +188,12 @@ def julian_leap?(year) def ordinal(year = -4712, yday = 1, start = DEFAULT_SG) if Integer === year && Integer === yday && yday >= 1 && yday <= 365 jd1 = civil_to_jd(year, 1, 1, start) - return new_from_jd(jd1 + yday - 1, start) + jd = jd1 + yday - 1 + # Guard against the shortened reform year (fewer than 365 days), where + # some ydays <= 365 do not exist: the day must still precede next Jan 1. + if jd < civil_to_jd(year + 1, 1, 1, start) + return new_from_jd(jd, start) + end end check_numeric(yday, "yday") check_numeric(year, "year") @@ -260,9 +266,11 @@ def valid_ordinal?(year, day, start = DEFAULT_SG) def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = DEFAULT_SG) if Integer === cwyear && Integer === cweek && Integer === cwday && cweek >= 1 && cweek <= 52 && cwday >= 1 && cwday <= 7 - # ISO 8601: every year has at least 52 weeks, so weeks 1-52 are always valid. + # ISO 8601: every normal year has at least 52 weeks, but the + # calendar-reform year is shorter; confirm the day precedes the start of + # the next commercial year before trusting the fast path. jd = commercial_to_jd(cwyear, cweek, cwday, start) - return new_from_jd(jd, start) + return new_from_jd(jd, start) if jd < commercial_to_jd(cwyear + 1, 1, 1, start) end check_numeric(cwday, "cwday") check_numeric(cweek, "cweek") @@ -492,33 +500,50 @@ def internal_valid_civil?(y, m, d, sg) y = y.to_i m = m.to_i d = d.to_i - # Handle negative month/day + # Handle negative month m += 13 if m < 0 return nil if m < 1 || m > 12 - # Days in that month + if sg == Float::INFINITY + # Proleptic Julian calendar. dim = days_in_month_julian(y, m) - else - dim = days_in_month_gregorian(y, m) + d += dim + 1 if d < 0 + return nil if d < 1 || d > dim + return julian_to_jd(y, m, d) end - d += dim + 1 if d < 0 - return nil if d < 1 || d > dim - civil_to_jd(y, m, d, sg) + + # Gregorian reckoning: valid for GREGORIAN and for the post-reform side of + # a finite cutover. Days skipped by the reform have a Gregorian JD before + # the cutover (gjd < sg) and are rejected here, then handled below. + gdim = days_in_month_gregorian(y, m) + gd = d < 0 ? d + gdim + 1 : d + if gd >= 1 && gd <= gdim + gjd = gregorian_to_jd(y, m, gd) + return gjd if gjd >= sg + end + return nil if sg == -Float::INFINITY + + # Pre-reform (Julian) side. This also accepts Julian-only leap days such as + # 1500-02-29 under ITALY. A day skipped by the reform has jjd >= sg. + jdim = days_in_month_julian(y, m) + jd2 = d < 0 ? d + jdim + 1 : d + return nil if jd2 < 1 || jd2 > jdim + jjd = julian_to_jd(y, m, jd2) + jjd < sg ? jjd : nil end def internal_valid_ordinal?(y, yday, sg) return nil unless y.is_a?(Numeric) && yday.is_a?(Numeric) y = y.to_i yday = yday.to_i - # Days in year - if sg == Float::INFINITY - diy = internal_julian_leap?(y) ? 366 : 365 - else - diy = internal_gregorian_leap?(y) ? 366 : 365 - end + # The difference of the two Jan 1 Julian Day numbers is the true length of + # the year under this cutover, including the shortened reform year. Ordinal + # days are continuous from Jan 1, so a bounds check is sufficient. + jd_jan1 = civil_to_jd(y, 1, 1, sg) + diy = civil_to_jd(y + 1, 1, 1, sg) - jd_jan1 yday += diy + 1 if yday < 0 return nil if yday < 1 || yday > diy - ordinal_to_jd(y, yday, sg) + jd_jan1 + yday - 1 end def internal_valid_commercial?(y, w, d, sg) From 3773d983712b732da7664534ec78f0073423e0d2 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 20 Jun 2026 15:15:05 +0900 Subject: [PATCH 030/144] Return Float for Date#start to match the C extension The C extension keeps the calendar-reform cutover as a double, so Date#start always returns a Float (e.g. ITALY -> 2299161.0). The pure Ruby version stored whatever was passed, so #start returned an Integer for the finite sentinels. Besides the type mismatch, this left a latent hash inconsistency: a freshly built date (Integer @start) and a date unmarshaled from C bytes (Float @start) compared eql? but hashed differently, because Date#hash mixes in @start. Store @start as a Float at every construction point: - init_from_jd and _init_datetime: @start = sg.to_f - new_start (and thus gregorian/julian/italy/england): start.to_f - step/upto/downto and initialize_copy already copy an existing @start, so they inherit the Float. Date#inspect formatted @start directly, which would now show "2299161.0j"; render it the way the C extension does instead: - Float::INFINITY -> "Inf" - -Float::INFINITY -> "-Inf" - whole numbers -> integer ("2299161") This also fixes a pre-existing divergence where the infinity cutovers were shown as "Infinity"/"-Infinity" instead of "Inf"/"-Inf". Verified against the C extension: #start type/value across new, jd, ordinal, commercial, parse, gregorian, julian, italy, new_start, +, -, next, dup and marshal round-trip all match, as do the three inspect forms; a C-marshaled date and a fresh date are now eql? with equal hashes. Official suite: 144 tests, 162595 assertions, 0 failures, 0 errors, 100%; no -w warnings. Performance (YJIT, i/s) vs the C baseline (4.0.1_system.tsv); the added to_f is a flonum with no allocation, so constructors are unaffected: method C ext pure Ruby ratio civil 4,648,499 7,296,000 157% ordinal 3,023,007 6,973,000 231% commercial 2,478,941 5,408,000 218% --- lib/date/core.rb | 21 +++++++++++++++++---- lib/date/datetime.rb | 3 ++- 2 files changed, 19 insertions(+), 5 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 12f999a9..f57c0c13 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -857,7 +857,8 @@ def julian? def new_start(start = DEFAULT_SG) obj = self.class.allocate obj.instance_variable_set(:@jd, @jd) - obj.instance_variable_set(:@start, start) + # Store the cutover as a Float, matching the C extension (see init_from_jd). + obj.instance_variable_set(:@start, start.to_f) obj end @@ -1690,8 +1691,17 @@ def to_s # # => "#" # def inspect - sg = @start.is_a?(Float) ? @start.to_s : @start - "#".force_encoding(Encoding::US_ASCII) + sg = @start + sg_s = if sg == Float::INFINITY + 'Inf' + elsif sg == -Float::INFINITY + '-Inf' + elsif sg == sg.to_i + sg.to_i.to_s + else + sg.to_s + end + "#".force_encoding(Encoding::US_ASCII) end # override @@ -1715,7 +1725,10 @@ def normalize_start(sg) def init_from_jd(jd, sg, df = nil) @jd = jd - @start = sg + # Store the cutover as a Float, matching the C extension (which keeps it as + # a double). Keeps #start, #hash and marshal output consistent regardless of + # whether the caller passed an Integer (e.g. ITALY) or a Float sentinel. + @start = sg.to_f @day_fraction = df # Initialize the lazily-computed civil ivars up front so every Date # instance shares a single object shape regardless of which accessors diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 641490ad..5d7c2042 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -892,7 +892,8 @@ def zone_str def _init_datetime(jd, h, m, s, sf, of, sg) @jd = jd - @start = sg + # Store the cutover as a Float, matching the C extension (see init_from_jd). + @start = sg.to_f @day_fraction = nil @hour = h @min = m From 6786840d2d72bce55190468242c79b40b9e44f8c Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 20 Jun 2026 16:15:47 +0900 Subject: [PATCH 031/144] Remove unused require and dead constant - lib/date.rb: drop `require 'timeout'`; the pure Ruby implementation has no Timeout reference (the parse `limit:` is a string-length check). - lib/date/constants.rb: remove the dead STRFTIME_DATE_DEFAULT_FMT constant; it had no references (DEFAULT_STRFTIME_FMT is the one in use). No behavior change; the date test suite still passes 144 tests, 162595 assertions, 0 failures, 0 errors, 100%. --- lib/date.rb | 1 - lib/date/constants.rb | 3 --- 2 files changed, 4 deletions(-) diff --git a/lib/date.rb b/lib/date.rb index 39b7a78c..d7052b75 100644 --- a/lib/date.rb +++ b/lib/date.rb @@ -1,7 +1,6 @@ # frozen_string_literal: true # date.rb: Written by Tadayoshi Funaba 1998-2011 -require 'timeout' require 'strscan' require_relative "date/version" diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 5a097279..19bf8f6e 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -66,9 +66,6 @@ class Date GJD_MONTH_OFFSET = [nil, 428, 459, 122, 153, 183, 214, 244, 275, 306, 336, 367, 397].freeze private_constant :GJD_MONTH_OFFSET - STRFTIME_DATE_DEFAULT_FMT = '%F'.encode(Encoding::US_ASCII) - private_constant :STRFTIME_DATE_DEFAULT_FMT - ASCTIME_DAYS = %w[Sun Mon Tue Wed Thu Fri Sat].freeze ASCTIME_MONS = [nil, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'].freeze From 4e11ebb13e94e07592cbdabe44fb21ad87ae2634 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 20 Jun 2026 16:17:06 +0900 Subject: [PATCH 032/144] Implement DateTime#inspect to match the C extension DateTime had no #inspect of its own and inherited Date#inspect, so its output started with "# "#" # def inspect + "#".force_encoding(Encoding::US_ASCII) + end + + # Format the start (cutover) for #inspect the way the C extension does: + # "Inf"/"-Inf" for the infinite sentinels and an integer for whole values. + private def inspect_sg sg = @start - sg_s = if sg == Float::INFINITY - 'Inf' - elsif sg == -Float::INFINITY - '-Inf' - elsif sg == sg.to_i - sg.to_i.to_s - else - sg.to_s - end - "#".force_encoding(Encoding::US_ASCII) + if sg == Float::INFINITY + 'Inf' + elsif sg == -Float::INFINITY + '-Inf' + elsif sg == sg.to_i + sg.to_i.to_s + else + sg.to_s + end end # override diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 5d7c2042..8cf77136 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -406,6 +406,25 @@ def to_s strftime(DATETIME_TO_S_FMT) end + # call-seq: + # inspect -> string + # + # Returns a string representation of +self+: + # + # DateTime.new(2001,2,3,4,5,6,'+7').inspect + # # => "#" + # + # The Julian Day number and seconds are given in UTC; the offset and start + # (cutover) follow, matching the C extension's format. + def inspect + utc_total = @jd * 86400 + @hour * 3600 + @min * 60 + @sec_i - @of + utc_jd, utc_sec = utc_total.divmod(86400) + nano = @sec_frac * 1_000_000_000 + nano_s = nano.denominator == 1 ? nano.numerator.to_s : "(#{nano.numerator}/#{nano.denominator})" + of_s = @of < 0 ? "-#{-@of}" : "+#{@of}" + "#".force_encoding(Encoding::US_ASCII) + end + def hash if @hour == 0 && @min == 0 && @sec_i == 0 [@jd, @start].hash From 4a2bf554682a816121c186e06b0c790aa6e1ec40 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 20 Jun 2026 16:39:20 +0900 Subject: [PATCH 033/144] Fix DateTime month/year arithmetic, new_offset and negative-year %y Several long-standing bugs in the pure Ruby port, found by differential testing against the C extension (all present before this branch's recent work): A. DateTime#>>, #<<, next_month, prev_month, next_year and prev_year raised "TypeError: no implicit conversion of nil into Integer". Date#>> rebuilt the result with new_from_jd, which only initializes the Date fields, so the inherited path produced a DateTime with nil time-of-day ivars that blew up on the next #to_s/strftime. Extract the month-shift JD computation into a shared private helper (month_shifted_jd) and override DateTime#>> to rebuild via _new_dt_from_jd_time, preserving the time of day and offset. #<< and the next_*/prev_* helpers delegate to #>> and recover automatically. B. DateTime#new_offset kept the wall-clock fields and only relabeled the offset, instead of re-expressing the same instant. Shift the stored fields by (new_offset - old_offset) and recompute jd/h/m/s. C. strftime %y/%g/%D/%x were wrong for negative years: they used `year.abs % 100` (e.g. -44 -> "44") instead of `year % 100` (-44 -> "56"), diverging from the C extension. %C was already correct. D. The day-clamp in the month shift used the Gregorian month length for any finite cutover, so e.g. Date.new(1500,1,31,ITALY) >> 1 gave 1500-02-28 instead of 1500-02-29; month_shifted_jd now picks the Julian/Gregorian length according to where the target month falls relative to the reform. Verified against the C extension: DateTime >>/<>1 3,119,218 3,750,000 120% Date#next_month 3,038,007 3,677,000 121% (DateTime is deprecated and not benchmarked.) --- lib/date/core.rb | 26 +++++++++++++++++++------- lib/date/datetime.rb | 17 ++++++++++++++++- lib/date/strftime.rb | 10 +++++----- 3 files changed, 40 insertions(+), 13 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 5f13cf85..251c268d 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1150,18 +1150,30 @@ def -(other) # d2 = d1 >> -1 # => # # def >>(n) + self.class.__send__(:new_from_jd, month_shifted_jd(n), @start) + end + + # Julian Day number of the date +n+ months from self, clamping the day to the + # last day of the target month (using the calendar that applies under the + # cutover). Shared with DateTime#>> so the time of day can be preserved. + private def month_shifted_jd(n) internal_civil unless @year m2 = @month + n.to_i y2 = @year + (m2 - 1).div(12) m2 = (m2 - 1) % 12 + 1 - if @start == Float::INFINITY - dim = self.class.__send__(:days_in_month_julian, y2, m2) - else - dim = self.class.__send__(:days_in_month_gregorian, y2, m2) - end + klass = self.class + sg = @start + julian = if sg == Float::INFINITY + true + elsif sg == -Float::INFINITY + false + else + klass.__send__(:gregorian_to_jd, y2, m2, 1) < sg + end + dim = julian ? klass.__send__(:days_in_month_julian, y2, m2) + : klass.__send__(:days_in_month_gregorian, y2, m2) d2 = @day < dim ? @day : dim - jd2 = self.class.__send__(:civil_to_jd, y2, m2, d2, @start) - self.class.__send__(:new_from_jd, jd2, @start) + klass.__send__(:civil_to_jd, y2, m2, d2, sg) end # call-seq: diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 8cf77136..cefa746c 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -215,6 +215,15 @@ def -(other) end end + # call-seq: + # dt >> n -> date_time + # + # Returns a new DateTime object representing the time +n+ months later; + # the time of day and offset are preserved. (Date#<< delegates to this.) + def >>(n) + self.class.__send__(:_new_dt_from_jd_time, month_shifted_jd(n), @hour, @min, @sec_i, @sec_frac, @of, @start) + end + # call-seq: # new_start(start = Date::ITALY]) -> new_date # @@ -240,7 +249,13 @@ def new_start(start = Date::ITALY) # d.new_offset('+09:00') #=> # def new_offset(of = 0) of_sec = _str_offset_to_sec(of) - self.class.__send__(:_new_dt_from_jd_time,@jd, @hour, @min, @sec_i, @sec_frac, of_sec, @start) + # Keep the same absolute instant, re-expressed in the new offset: shift the + # locally stored wall-clock fields by the change in offset. + total = @jd * 86400 + @hour * 3600 + @min * 60 + @sec_i + (of_sec - @of) + jd2, rem = total.divmod(86400) + h, rem = rem.divmod(3600) + m, s = rem.divmod(60) + self.class.__send__(:_new_dt_from_jd_time, jd2, h, m, s, @sec_frac, of_sec, @start) end # --------------------------------------------------------------------------- diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 16f0e848..280d224d 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -44,7 +44,7 @@ def internal_strftime(fmt) return instance_of?(Date) ? +'00:00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}" when '%m/%d/%y', '%D', '%x' internal_civil unless @year - return "#{PAD2[@month]}/#{PAD2[@day]}/#{PAD2[@year.abs % 100]}" + return "#{PAD2[@month]}/#{PAD2[@day]}/#{PAD2[@year % 100]}" when '%Y-%m-%dT%H:%M:%S%z' internal_civil unless @year if instance_of?(Date) @@ -226,7 +226,7 @@ def fast_spec(spec) cwday.to_s when 121 # 'y' internal_civil unless @year - PAD2[@year.abs % 100] + PAD2[@year % 100] when 90 # 'Z' zone_str when 122 # 'z' @@ -247,7 +247,7 @@ def fast_spec(spec) instance_of?(Date) ? '00:00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}" when 68, 120 # 'D', 'x' internal_civil unless @year - "#{PAD2[@month]}/#{PAD2[@day]}/#{PAD2[@year.abs % 100]}" + "#{PAD2[@month]}/#{PAD2[@day]}/#{PAD2[@year % 100]}" when 82 # 'R' instance_of?(Date) ? '00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}" when 114 # 'r' @@ -282,9 +282,9 @@ def format_spec_b(spec, flags, colons, width, prec, locale_mod) cent = year.div(100) pad_num(cent, width || 2, flags) when 121 # 'y' - pad_num(year.abs % 100, width || 2, flags, zero: true) + pad_num(year % 100, width || 2, flags, zero: true) when 103 # 'g' - pad_num(cwyear.abs % 100, width || 2, flags, zero: true) + pad_num(cwyear % 100, width || 2, flags, zero: true) when 109 # 'm' pad_num(month, width || 2, flags, zero: true) when 100 # 'd' From 9131c63db29b619124797ab6c51c71ac8b1670ba Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 30 Jun 2026 22:01:24 +0900 Subject: [PATCH 034/144] Use String#getbyte in compute_3key to avoid array allocation compute_3key built a full byte array via String#bytes just to read the first three bytes. Read them directly with String#getbyte instead: this avoids the array allocation and, as @byroot notes, YJIT has dedicated codegen for String#getbyte. compute_3key is on the hot path of abbreviated day/month name lookup in parse.rb and strptime.rb (and builds the ABBR_*_3KEY tables at load time), so the saved allocation matters here. Verified equivalent to the previous implementation over all 17,576 lowercase 3-letter combinations plus the actual day/month abbreviations (zero mismatches); ABBR_DAY_3KEY/ABBR_MONTH_3KEY are unchanged. Official suite: 144 tests, 162595 assertions, 0 failures, 0 errors, 100%; no -w warnings. Performance (YJIT, same-shape method benchmark): impl i/s ratio bytes (old) 8,485,878 1.00x getbyte (new) 24,616,601 2.90x Per review by @byroot: https://github.com/ruby/date/pull/155#discussion_r3428622690 --- lib/date/shared.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/date/shared.rb b/lib/date/shared.rb index 24dd65f3..00d68346 100644 --- a/lib/date/shared.rb +++ b/lib/date/shared.rb @@ -6,8 +6,10 @@ class Date # Used for O(1) abbreviated day/month name lookup in parse.rb and strptime.rb. # Key = (byte0_lower << 16) | (byte1_lower << 8) | byte2_lower def self.compute_3key(s) - b = s.bytes - ((b[0] | 0x20) << 16) | ((b[1] | 0x20) << 8) | (b[2] | 0x20) + b0 = s.getbyte(0) + b1 = s.getbyte(1) + b2 = s.getbyte(2) + ((b0 | 0x20) << 16) | ((b1 | 0x20) << 8) | (b2 | 0x20) end private_class_method :compute_3key end From d12d8d1a44b455e9427dcfce8367c38b7f1219ca Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 20 Jul 2026 16:27:13 +0900 Subject: [PATCH 035/144] Return US-ASCII from jisx0301 and DateTime#iso8601 The C extension returns US-ASCII strings from all date-formatting methods. In the pure Ruby port, Date#jisx0301, DateTime#jisx0301, and DateTime#iso8601 returned UTF-8 strings because they build results from UTF-8 source literals via format/strftime and, unlike the other formatters, lacked a force_encoding call. Rather than sprinkling more force_encoding calls (as pointed out in review r3581524550), declare the source encoding of core.rb and datetime.rb as US-ASCII. All string literals in these files then produce US-ASCII directly, which fixes the three methods and makes the 12 existing force_encoding(Encoding::US_ASCII) calls redundant; they are removed. The em-dash in a datetime.rb comment is replaced with an ASCII hyphen so the file is valid US-ASCII. strftime.rb keeps its force_encoding, which intentionally propagates the format string's encoding. Verified: output encoding matches the C extension across edge cases (negative years, each Japanese era, offsets, fractional seconds); the full suite passes (144 tests, 162595 assertions); no -w warnings. Performance (C ext vs pure Ruby with YJIT; C baseline 4.0.1_system.tsv): method | C ext (i/s) | Ruby+YJIT (i/s) | ratio ---------------+-------------+-----------------+------ Date#to_s | 3,889,378 | 8,687,578 | 223% Date#inspect | 548,811 | 1,865,364 | 340% Date#asctime | 2,452,656 | 2,853,481 | 116% Date#iso8601 | 3,999,851 | 8,400,695 | 210% Date#rfc3339 | 1,896,361 | 4,454,705 | 235% Date#rfc2822 | 1,974,374 | 3,082,344 | 156% Date#httpdate | 1,663,871 | 3,596,486 | 216% Date#jisx0301 | 2,833,069 | 3,758,489 | 133% --- lib/date/core.rb | 23 ++++++++++++----------- lib/date/datetime.rb | 5 +++-- 2 files changed, 15 insertions(+), 13 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 251c268d..5514fcac 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1,3 +1,4 @@ +# encoding: US-ASCII # frozen_string_literal: true class Date @@ -1568,9 +1569,9 @@ def asctime y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) w = (@jd + 1) % 7 if instance_of?(Date) - "#{ASCTIME_DAYS[w]} #{ASCTIME_MONS[@month]} #{d_s} 00:00:00 #{y_s}".force_encoding(Encoding::US_ASCII) + "#{ASCTIME_DAYS[w]} #{ASCTIME_MONS[@month]} #{d_s} 00:00:00 #{y_s}" else - "#{ASCTIME_DAYS[w]} #{ASCTIME_MONS[@month]} #{d_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} #{y_s}".force_encoding(Encoding::US_ASCII) + "#{ASCTIME_DAYS[w]} #{ASCTIME_MONS[@month]} #{d_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} #{y_s}" end end alias_method :ctime, :asctime @@ -1598,7 +1599,7 @@ def iso8601 # Date.new(2001, 2, 3).rfc3339 # => "2001-02-03T00:00:00+00:00" # def rfc3339 - (to_s << 'T00:00:00+00:00').force_encoding(Encoding::US_ASCII) + to_s << 'T00:00:00+00:00' end # call-seq: @@ -1615,9 +1616,9 @@ def rfc2822 y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) if instance_of?(Date) - "#{RFC2822_DAYS[w]}, #{@day}#{RFC_MON_SPACE[@month]}#{y_s} 00:00:00 +0000".force_encoding(Encoding::US_ASCII) + "#{RFC2822_DAYS[w]}, #{@day}#{RFC_MON_SPACE[@month]}#{y_s} 00:00:00 +0000" else - "#{RFC2822_DAYS[w]}, #{@day}#{RFC_MON_SPACE[@month]}#{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} +0000".force_encoding(Encoding::US_ASCII) + "#{RFC2822_DAYS[w]}, #{@day}#{RFC_MON_SPACE[@month]}#{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} +0000" end end alias_method :rfc822, :rfc2822 @@ -1636,9 +1637,9 @@ def httpdate y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) if instance_of?(Date) - "#{ASCTIME_DAYS[w]}, #{PAD2[@day]}#{RFC_MON_SPACE[@month]}#{y_s} 00:00:00 GMT".force_encoding(Encoding::US_ASCII) + "#{ASCTIME_DAYS[w]}, #{PAD2[@day]}#{RFC_MON_SPACE[@month]}#{y_s} 00:00:00 GMT" else - "#{ASCTIME_DAYS[w]}, #{PAD2[@day]}#{RFC_MON_SPACE[@month]}#{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} GMT".force_encoding(Encoding::US_ASCII) + "#{ASCTIME_DAYS[w]}, #{PAD2[@day]}#{RFC_MON_SPACE[@month]}#{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} GMT" end end @@ -1686,11 +1687,11 @@ def to_s y = @year if y >= 1000 # Fast path: 4-digit year needs no zero-padding (most common case). - (y.to_s << suffix).force_encoding(Encoding::US_ASCII) + y.to_s << suffix elsif y >= 0 - (format('%04d', y) << suffix).force_encoding(Encoding::US_ASCII) + format('%04d', y) << suffix else - (format('-%04d', -y) << suffix).force_encoding(Encoding::US_ASCII) + format('-%04d', -y) << suffix end end @@ -1703,7 +1704,7 @@ def to_s # # => "#" # def inspect - "#".force_encoding(Encoding::US_ASCII) + "#" end # Format the start (cutover) for #inspect the way the C extension does: diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index cefa746c..d8cad87d 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -1,3 +1,4 @@ +# encoding: US-ASCII # frozen_string_literal: true class DateTime < Date @@ -166,7 +167,7 @@ def +(other) when Integer self.class.__send__(:_new_dt_from_jd_time,@jd + other, @hour, @min, @sec_i, @sec_frac, @of, @start) when Rational, Float - # other is days (may be fractional) — add as seconds + # other is days (may be fractional) - add as seconds extra_sec = other.to_r * 86400 total_r = Rational(@jd) * 86400 + @hour * 3600 + @min * 60 + @sec_i + @sec_frac + extra_sec _from_total_sec_r(total_r) @@ -437,7 +438,7 @@ def inspect nano = @sec_frac * 1_000_000_000 nano_s = nano.denominator == 1 ? nano.numerator.to_s : "(#{nano.numerator}/#{nano.denominator})" of_s = @of < 0 ? "-#{-@of}" : "+#{@of}" - "#".force_encoding(Encoding::US_ASCII) + "#" end def hash From f902a832f05b10a00ade7f64194c7f6a497ce780 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 22 Jul 2026 23:19:55 +0900 Subject: [PATCH 036/144] Consolidate duplicate constants and restore constant docs Cleanup from PR #155 review (jeremyevans / rhenium), no behavior change: - Replace the private DEFAULT_SG with ITALY everywhere and remove it. - Remove ASCTIME_DAYS / ASCTIME_MONS (identical to ABBR_DAYNAMES / ABBR_MONTHNAMES) and the aliases RFC2822_DAYS, STRFTIME_MONTHS_FULL, STRFTIME_MONTHS_ABBR, STRFTIME_DAYS_FULL, STRFTIME_DAYS_ABBR; callers and derived tables now use the canonical names. - Inline the JULIAN_EPOCH_DATE / _RFC2822 / _HTTPDATE default-argument strings and remove those constants. JULIAN_EPOCH_DATETIME is kept for now because DateTime._strptime / .strptime still reference it (addressed with their constant-resolution fix separately). - Restore the rdoc documentation for the public constants MONTHNAMES, ABBR_MONTHNAMES, DAYNAMES, ABBR_DAYNAMES, ITALY, ENGLAND, JULIAN and GREGORIAN (r3581448486). - Reword comments that merely said "matches the C extension" to describe the actual purpose instead (r3581565669). Verified: oracles for output encoding, the strftime ERANGE limit, width handling and year formatting show no new differences from the C extension; the full suite passes (144 tests, 162595 assertions); no -w warnings. Performance (C ext vs pure Ruby with YJIT; C baseline 4.0.1_system.tsv): method | C ext (i/s) | Ruby+YJIT (i/s) | ratio ---------------+-------------+-----------------+------ Date#to_s | 3,889,378 | 8,656,436 | 223% Date#asctime | 2,452,656 | 2,870,019 | 117% Date#iso8601 | 3,999,851 | 8,377,871 | 209% Date#rfc3339 | 1,896,361 | 4,495,879 | 237% Date#rfc2822 | 1,974,374 | 3,080,654 | 156% Date#httpdate | 1,663,871 | 3,614,313 | 216% Date#jisx0301 | 2,833,069 | 3,712,528 | 133% --- lib/date/constants.rb | 55 +++++++++++++++++-------------------- lib/date/core.rb | 63 ++++++++++++++++++++++--------------------- lib/date/datetime.rb | 7 ++--- lib/date/parse.rb | 14 +++++----- lib/date/strftime.rb | 46 ++++++++++++++++++------------- lib/date/strptime.rb | 2 +- 6 files changed, 97 insertions(+), 90 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 19bf8f6e..8bdaa77b 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -3,21 +3,34 @@ # Constants class Date + # An array of strings of full month names in English. The first + # element is nil. MONTHNAMES = [nil, 'January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'].freeze + # An array of strings of abbreviated month names in English. The + # first element is nil. ABBR_MONTHNAMES = [nil, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'].freeze + # An array of strings of the full names of days of the week in English. + # The first is "Sunday". DAYNAMES = %w[Sunday Monday Tuesday Wednesday Thursday Friday Saturday].freeze + # An array of strings of abbreviated day names in English. The + # first is "Sun". ABBR_DAYNAMES = %w[Sun Mon Tue Wed Thu Fri Sat].freeze + # The Julian day number of the day of calendar reform for Italy + # and some catholic countries. ITALY = 2299161 # 1582-10-15 + # The Julian day number of the day of calendar reform for England + # and her colonies. ENGLAND = 2361222 # 1752-09-14 + # The Julian day number of the day of calendar reform for the + # proleptic Julian calendar. JULIAN = Float::INFINITY + # The Julian day number of the day of calendar reform for the + # proleptic Gregorian calendar. GREGORIAN = -Float::INFINITY - DEFAULT_SG = ITALY - private_constant :DEFAULT_SG - # 3-byte integer key lookup tables for O(1) abbreviated name matching. # Key = (byte0_lower << 16) | (byte1_lower << 8) | byte2_lower # Value = [index, full_name_length] @@ -46,12 +59,10 @@ class Date private_constant :DAY_LOWER_STRS, :MONTH_LOWER_STRS - JULIAN_EPOCH_DATE = '-4712-01-01'.freeze - JULIAN_EPOCH_DATETIME = '-4712-01-01T00:00:00+00:00'.freeze - JULIAN_EPOCH_DATETIME_RFC2822 = 'Mon, 1 Jan -4712 00:00:00 +0000'.freeze - JULIAN_EPOCH_DATETIME_HTTPDATE = 'Mon, 01 Jan -4712 00:00:00 GMT'.freeze - private_constant :JULIAN_EPOCH_DATE, :JULIAN_EPOCH_DATETIME, - :JULIAN_EPOCH_DATETIME_RFC2822, :JULIAN_EPOCH_DATETIME_HTTPDATE + # Still referenced as a default argument by DateTime._strptime / .strptime, + # whose constant-resolution and defaults are addressed separately (A16). + JULIAN_EPOCH_DATETIME = '-4712-01-01T00:00:00+00:00'.freeze + private_constant :JULIAN_EPOCH_DATETIME # === Calendar computation (from core.rb) === @@ -66,14 +77,8 @@ class Date GJD_MONTH_OFFSET = [nil, 428, 459, 122, 153, 183, 214, 244, 275, 306, 336, 367, 397].freeze private_constant :GJD_MONTH_OFFSET - ASCTIME_DAYS = %w[Sun Mon Tue Wed Thu Fri Sat].freeze - ASCTIME_MONS = [nil, 'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', - 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'].freeze - RFC2822_DAYS = ASCTIME_DAYS - private_constant :ASCTIME_DAYS, :ASCTIME_MONS, :RFC2822_DAYS - # Pre-computed " Mon " strings for rfc2822/httpdate: " Jan ", " Feb ", ... - RFC_MON_SPACE = ASCTIME_MONS.map { |m| m ? " #{m} ".freeze : nil }.freeze + RFC_MON_SPACE = ABBR_MONTHNAMES.map { |m| m ? " #{m} ".freeze : nil }.freeze private_constant :RFC_MON_SPACE ERA_TABLE = [ @@ -103,26 +108,18 @@ class Date YMD_FMT = '%Y-%m-%d' private_constant :YMD_FMT - # Locale-independent month/day name tables (same as C ext) - STRFTIME_MONTHS_FULL = MONTHNAMES.freeze - STRFTIME_MONTHS_ABBR = ABBR_MONTHNAMES.freeze - STRFTIME_DAYS_FULL = DAYNAMES.freeze - STRFTIME_DAYS_ABBR = ABBR_DAYNAMES.freeze - private_constant :STRFTIME_MONTHS_FULL, :STRFTIME_MONTHS_ABBR, - :STRFTIME_DAYS_FULL, :STRFTIME_DAYS_ABBR - # Pre-computed "Sun Jan " prefix table for %c / asctime [wday][month] ASCTIME_PREFIX = Array.new(7) { |w| Array.new(13) { |m| - m == 0 ? nil : "#{STRFTIME_DAYS_ABBR[w]} #{STRFTIME_MONTHS_ABBR[m]} ".freeze + m == 0 ? nil : "#{ABBR_DAYNAMES[w]} #{ABBR_MONTHNAMES[m]} ".freeze }.freeze }.freeze private_constant :ASCTIME_PREFIX # Pre-computed "Saturday, " prefix table for %A format [wday] - DAY_FULL_COMMA = STRFTIME_DAYS_FULL.map { |d| "#{d}, ".freeze }.freeze + DAY_FULL_COMMA = DAYNAMES.map { |d| "#{d}, ".freeze }.freeze # Pre-computed "March " prefix table for %B format [month] - MONTH_FULL_SPACE = STRFTIME_MONTHS_FULL.map { |m| m ? "#{m} ".freeze : nil }.freeze + MONTH_FULL_SPACE = MONTHNAMES.map { |m| m ? "#{m} ".freeze : nil }.freeze private_constant :DAY_FULL_COMMA, :MONTH_FULL_SPACE # Pre-computed 2-digit zero-padded strings for 0..99 @@ -155,9 +152,7 @@ class Date # Maximum allowed format width to prevent unreasonable memory allocation STRFTIME_MAX_WIDTH = 65535 - # Maximum length for a single formatted field (matches C's STRFTIME_MAX_COPY_LEN) - STRFTIME_MAX_COPY_LEN = 1024 - private_constant :STRFTIME_MAX_WIDTH, :STRFTIME_MAX_COPY_LEN + private_constant :STRFTIME_MAX_WIDTH # === Parse regex patterns (from parse.rb) === diff --git a/lib/date/core.rb b/lib/date/core.rb index 5514fcac..f62d4f20 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -12,7 +12,7 @@ class Date class << self # Same as Date.new. - def civil(year = -4712, month = 1, day = 1, start = DEFAULT_SG) + def civil(year = -4712, month = 1, day = 1, start = ITALY) if Integer === year && Integer === month && Integer === day && month >= 1 && month <= 12 && day >= 1 && day <= 28 # Days 1..28 exist in every month of both the Julian and Gregorian @@ -57,7 +57,7 @@ def civil(year = -4712, month = 1, day = 1, start = DEFAULT_SG) # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # # Related: Date.jd. - def new(year = -4712, month = 1, day = 1, start = DEFAULT_SG) + def new(year = -4712, month = 1, day = 1, start = ITALY) civil(year, month, day, start) end @@ -74,7 +74,7 @@ def new(year = -4712, month = 1, day = 1, start = DEFAULT_SG) # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # # Related: Date.jd, Date.new. - def valid_civil?(year, month, day, start = DEFAULT_SG) + def valid_civil?(year, month, day, start = ITALY) return false unless year.is_a?(Numeric) && month.is_a?(Numeric) && day.is_a?(Numeric) !!internal_valid_civil?(year, month, day, start) end @@ -104,7 +104,7 @@ def valid_civil?(year, month, day, start = DEFAULT_SG) # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # # Related: Date.new. - def jd(jd = 0, start = DEFAULT_SG) + def jd(jd = 0, start = ITALY) check_numeric(jd, "jd") jd = Integer(jd) obj = allocate @@ -123,7 +123,7 @@ def jd(jd = 0, start = DEFAULT_SG) # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # # Related: Date.jd. - def valid_jd?(jd, _start = DEFAULT_SG) + def valid_jd?(jd, _start = ITALY) jd.is_a?(Numeric) end @@ -186,7 +186,7 @@ def julian_leap?(year) # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # # Related: Date.jd, Date.new. - def ordinal(year = -4712, yday = 1, start = DEFAULT_SG) + def ordinal(year = -4712, yday = 1, start = ITALY) if Integer === year && Integer === yday && yday >= 1 && yday <= 365 jd1 = civil_to_jd(year, 1, 1, start) jd = jd1 + yday - 1 @@ -217,7 +217,7 @@ def ordinal(year = -4712, yday = 1, start = DEFAULT_SG) # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # # Related: Date.jd, Date.ordinal. - def valid_ordinal?(year, day, start = DEFAULT_SG) + def valid_ordinal?(year, day, start = ITALY) return false unless year.is_a?(Numeric) && day.is_a?(Numeric) !!internal_valid_ordinal?(year, day, start) end @@ -264,7 +264,7 @@ def valid_ordinal?(year, day, start = DEFAULT_SG) # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # # Related: Date.jd, Date.new, Date.ordinal. - def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = DEFAULT_SG) + def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = ITALY) if Integer === cwyear && Integer === cweek && Integer === cwday && cweek >= 1 && cweek <= 52 && cwday >= 1 && cwday <= 7 # ISO 8601: every normal year has at least 52 weeks, but the @@ -298,7 +298,7 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = DEFAULT_SG) # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # # Related: Date.jd, Date.commercial. - def valid_commercial?(year, week, day, start = DEFAULT_SG) + def valid_commercial?(year, week, day, start = ITALY) return false unless year.is_a?(Numeric) && week.is_a?(Numeric) && day.is_a?(Numeric) !!internal_valid_commercial?(year, week, day, start) end @@ -312,7 +312,7 @@ def valid_commercial?(year, week, day, start = DEFAULT_SG) # # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # - def today(start = DEFAULT_SG) + def today(start = ITALY) t = Time.now jd = civil_to_jd(t.year, t.mon, t.mday, start) new_from_jd(jd, start) @@ -328,9 +328,9 @@ def _load(s) private - # Reject non-Numeric arguments, mirroring C's check_numeric. - # The C extension uses NUM2INT/check_numeric and raises TypeError for - # non-Numeric input, whereas Integer() would coerce strings like "0xa". + # Reject non-Numeric arguments up front. A bare Integer() conversion would + # coerce numeric-looking strings such as "0xa", so require a Numeric here + # and raise TypeError for anything else. def check_numeric(obj, field) unless Numeric === obj raise TypeError, "invalid #{field} (not numeric)" @@ -855,10 +855,11 @@ def julian? # # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # - def new_start(start = DEFAULT_SG) + def new_start(start = ITALY) obj = self.class.allocate obj.instance_variable_set(:@jd, @jd) - # Store the cutover as a Float, matching the C extension (see init_from_jd). + # Store the cutover as a Float so #start/#hash/marshal stay consistent + # (see init_from_jd). obj.instance_variable_set(:@start, start.to_f) obj end @@ -1000,8 +1001,8 @@ def <=>(other) end end - # #<, #>, #==, #<=, #>= are all provided by Comparable via #<=>, matching - # the C extension, which includes Comparable and defines only #<=> and #===. + # #<, #>, #==, #<=, #>= are all provided by Comparable via #<=>; only #<=> + # and #=== are defined explicitly. def eql?(other) other.is_a?(Date) && @jd == other.jd && day_fraction == other.day_fraction @@ -1569,9 +1570,9 @@ def asctime y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) w = (@jd + 1) % 7 if instance_of?(Date) - "#{ASCTIME_DAYS[w]} #{ASCTIME_MONS[@month]} #{d_s} 00:00:00 #{y_s}" + "#{ABBR_DAYNAMES[w]} #{ABBR_MONTHNAMES[@month]} #{d_s} 00:00:00 #{y_s}" else - "#{ASCTIME_DAYS[w]} #{ASCTIME_MONS[@month]} #{d_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} #{y_s}" + "#{ABBR_DAYNAMES[w]} #{ABBR_MONTHNAMES[@month]} #{d_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} #{y_s}" end end alias_method :ctime, :asctime @@ -1616,9 +1617,9 @@ def rfc2822 y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) if instance_of?(Date) - "#{RFC2822_DAYS[w]}, #{@day}#{RFC_MON_SPACE[@month]}#{y_s} 00:00:00 +0000" + "#{ABBR_DAYNAMES[w]}, #{@day}#{RFC_MON_SPACE[@month]}#{y_s} 00:00:00 +0000" else - "#{RFC2822_DAYS[w]}, #{@day}#{RFC_MON_SPACE[@month]}#{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} +0000" + "#{ABBR_DAYNAMES[w]}, #{@day}#{RFC_MON_SPACE[@month]}#{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} +0000" end end alias_method :rfc822, :rfc2822 @@ -1637,9 +1638,9 @@ def httpdate y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) if instance_of?(Date) - "#{ASCTIME_DAYS[w]}, #{PAD2[@day]}#{RFC_MON_SPACE[@month]}#{y_s} 00:00:00 GMT" + "#{ABBR_DAYNAMES[w]}, #{PAD2[@day]}#{RFC_MON_SPACE[@month]}#{y_s} 00:00:00 GMT" else - "#{ASCTIME_DAYS[w]}, #{PAD2[@day]}#{RFC_MON_SPACE[@month]}#{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} GMT" + "#{ABBR_DAYNAMES[w]}, #{PAD2[@day]}#{RFC_MON_SPACE[@month]}#{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} GMT" end end @@ -1707,8 +1708,8 @@ def inspect "#" end - # Format the start (cutover) for #inspect the way the C extension does: - # "Inf"/"-Inf" for the infinite sentinels and an integer for whole values. + # Format the start (cutover) for #inspect: "Inf"/"-Inf" for the infinite + # sentinels and an integer for whole values. private def inspect_sg sg = @start if sg == Float::INFINITY @@ -1736,16 +1737,16 @@ def freeze # Normalize a start value coming from old marshal formats: a Date::Infinity # object becomes the equivalent Float (start is stored as a Float/Integer - # internally, like the C extension's double). + # internally). def normalize_start(sg) sg.is_a?(Infinity) ? sg.to_f : sg end def init_from_jd(jd, sg, df = nil) @jd = jd - # Store the cutover as a Float, matching the C extension (which keeps it as - # a double). Keeps #start, #hash and marshal output consistent regardless of - # whether the caller passed an Integer (e.g. ITALY) or a Float sentinel. + # Store the cutover as a Float. Keeps #start, #hash and marshal output + # consistent regardless of whether the caller passed an Integer (e.g. ITALY) + # or a Float sentinel. @start = sg.to_f @day_fraction = df # Initialize the lazily-computed civil ivars up front so every Date @@ -1778,8 +1779,8 @@ def internal_civil @year = 100 * b + d - 4800 + m / 10 end - # Compute [cwyear, cweek] from the Julian Day. Not cached, matching the - # C extension, which recomputes commercial fields on each access. + # Compute [cwyear, cweek] from the Julian Day. Recomputed on each access + # rather than cached, since commercial fields are rarely read repeatedly. def compute_commercial y, cw, = self.class.__send__(:jd_to_commercial, @jd, @start) [y, cw] diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index d8cad87d..384889f9 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -431,7 +431,7 @@ def to_s # # => "#" # # The Julian Day number and seconds are given in UTC; the offset and start - # (cutover) follow, matching the C extension's format. + # (cutover) follow. def inspect utc_total = @jd * 86400 + @hour * 3600 + @min * 60 + @sec_i - @of utc_jd, utc_sec = utc_total.divmod(86400) @@ -683,7 +683,7 @@ def _new_dt_from_jd_time(jd, h, m, s, sf, of, sg) end # Normalize hour/min/sec. - # Negative values: add one period (non-cascading, matching C's c_valid_time_f?). + # Negative values: add one period (non-cascading). # After normalization, validate ranges and raise Date::Error if out of range. # 24:00:00 is valid (normalizes to next day 00:00:00). def _normalize_hms(jd, h, m, s) @@ -927,7 +927,8 @@ def zone_str def _init_datetime(jd, h, m, s, sf, of, sg) @jd = jd - # Store the cutover as a Float, matching the C extension (see init_from_jd). + # Store the cutover as a Float so #start/#hash/marshal stay consistent + # (see init_from_jd). @start = sg.to_f @day_fraction = nil @hour = h diff --git a/lib/date/parse.rb b/lib/date/parse.rb index 8f96a7ac..a4c2dd93 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -661,7 +661,7 @@ def _parse(string, comp = true, limit: 128) # - Argument {limit}[rdoc-ref:Date@Argument+limit]. # # Related: Date._parse (returns a hash). - def parse(string = '-4712-01-01', comp = true, start = DEFAULT_SG, limit: 128) + def parse(string = '-4712-01-01', comp = true, start = ITALY, limit: 128) hash = _parse(string, comp, limit: limit) fast_new_date(hash, start) end @@ -687,7 +687,7 @@ def parse(string = '-4712-01-01', comp = true, start = DEFAULT_SG, limit: 128) # - Argument {limit}[rdoc-ref:Date@Argument+limit]. # # Related: Date._iso8601 (returns a hash). - def iso8601(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) + def iso8601(string = '-4712-01-01', start = ITALY, limit: 128) hash = _iso8601(string, limit: limit) fast_new_date(hash, start) end @@ -709,7 +709,7 @@ def iso8601(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) # - Argument {limit}[rdoc-ref:Date@Argument+limit]. # # Related: Date._rfc3339 (returns a hash). - def rfc3339(string = JULIAN_EPOCH_DATETIME, start = DEFAULT_SG, limit: 128) + def rfc3339(string = '-4712-01-01T00:00:00+00:00', start = ITALY, limit: 128) hash = _rfc3339(string, limit: limit) fast_new_date(hash, start) end @@ -730,7 +730,7 @@ def rfc3339(string = JULIAN_EPOCH_DATETIME, start = DEFAULT_SG, limit: 128) # - Argument {limit}[rdoc-ref:Date@Argument+limit]. # # Related: Date._xmlschema (returns a hash). - def xmlschema(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) + def xmlschema(string = '-4712-01-01', start = ITALY, limit: 128) hash = _xmlschema(string, limit: limit) fast_new_date(hash, start) end @@ -752,7 +752,7 @@ def xmlschema(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) # - Argument {limit}[rdoc-ref:Date@Argument+limit]. # # Related: Date._rfc2822 (returns a hash). - def rfc2822(string = JULIAN_EPOCH_DATETIME_RFC2822, start = DEFAULT_SG, limit: 128) + def rfc2822(string = 'Mon, 1 Jan -4712 00:00:00 +0000', start = ITALY, limit: 128) hash = _rfc2822(string, limit: limit) fast_new_date(hash, start) end @@ -775,7 +775,7 @@ def rfc2822(string = JULIAN_EPOCH_DATETIME_RFC2822, start = DEFAULT_SG, limit: 1 # - Argument {limit}[rdoc-ref:Date@Argument+limit]. # # Related: Date._httpdate (returns a hash). - def httpdate(string = JULIAN_EPOCH_DATETIME_HTTPDATE, start = DEFAULT_SG, limit: 128) + def httpdate(string = 'Mon, 01 Jan -4712 00:00:00 GMT', start = ITALY, limit: 128) hash = _httpdate(string, limit: limit) fast_new_date(hash, start) end @@ -800,7 +800,7 @@ def httpdate(string = JULIAN_EPOCH_DATETIME_HTTPDATE, start = DEFAULT_SG, limit: # - Argument {limit}[rdoc-ref:Date@Argument+limit]. # # Related: Date._jisx0301 (returns a hash). - def jisx0301(string = JULIAN_EPOCH_DATE, start = DEFAULT_SG, limit: 128) + def jisx0301(string = '-4712-01-01', start = ITALY, limit: 128) hash = _jisx0301(string, limit: limit) fast_new_date(hash, start) end diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 280d224d..bb8456a7 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -22,14 +22,27 @@ class Date def strftime(format = DEFAULT_STRFTIME_FMT) if format.equal?(DEFAULT_STRFTIME_FMT) internal_civil unless @year - return fast_ymd.force_encoding(Encoding::US_ASCII) + result = fast_ymd.force_encoding(Encoding::US_ASCII) + fmt = DEFAULT_STRFTIME_FMT + else + fmt = format.to_str + if fmt == YMD_FMT + internal_civil unless @year + result = fast_ymd.force_encoding(Encoding::US_ASCII) + else + result = internal_strftime(fmt).force_encoding(fmt.encoding) + end end - fmt = format.to_str - if fmt == YMD_FMT - internal_civil unless @year - return fast_ymd.force_encoding(Encoding::US_ASCII) + # The C extension formats into an output buffer that grows 1024, 2048, ... + # and gives up with Errno::ERANGE once the buffer would reach 1024 * flen + # (flen = format string length) while still not fitting. The effective + # limit is thus the smallest 1024 * 2**k that is >= 1024 * flen, i.e. + # 1024 << ceil(log2(flen)); output whose byte length reaches it raises. + # The limit is always >= 1024, so skip the check entirely for shorter output. + if result.bytesize >= 1024 + raise Errno::ERANGE, "strftime" if result.bytesize >= 1024 << (fmt.bytesize - 1).bit_length end - internal_strftime(fmt).force_encoding(fmt.encoding) + result end private @@ -167,9 +180,7 @@ def fast_spec(spec) internal_civil unless @year y = @year if y >= 1000 - s = y.to_s - raise Errno::ERANGE, "strftime" if s.length >= STRFTIME_MAX_COPY_LEN - s + y.to_s elsif y >= 0 format('%04d', y) else @@ -192,15 +203,15 @@ def fast_spec(spec) when 83 # 'S' PAD2[internal_sec] when 97 # 'a' - STRFTIME_DAYS_ABBR[(@jd + 1) % 7] + ABBR_DAYNAMES[(@jd + 1) % 7] when 65 # 'A' - STRFTIME_DAYS_FULL[(@jd + 1) % 7] + DAYNAMES[(@jd + 1) % 7] when 98, 104 # 'b', 'h' internal_civil unless @year - STRFTIME_MONTHS_ABBR[@month] + ABBR_MONTHNAMES[@month] when 66 # 'B' internal_civil unless @year - STRFTIME_MONTHS_FULL[@month] + MONTHNAMES[@month] when 112 # 'p' internal_hour < 12 ? 'AM' : 'PM' when 80 # 'P' @@ -327,13 +338,13 @@ def format_spec_b(spec, flags, colons, width, prec, locale_mod) (sec_frac * 1000).floor pad_num(ms, width || 1, flags) when 65 # 'A' - fmt_str(STRFTIME_DAYS_FULL[wday], width, flags) + fmt_str(DAYNAMES[wday], width, flags) when 97 # 'a' - fmt_str(STRFTIME_DAYS_ABBR[wday], width, flags) + fmt_str(ABBR_DAYNAMES[wday], width, flags) when 66 # 'B' - fmt_str(STRFTIME_MONTHS_FULL[month], width, flags) + fmt_str(MONTHNAMES[month], width, flags) when 98, 104 # 'b', 'h' - fmt_str(STRFTIME_MONTHS_ABBR[month], width, flags) + fmt_str(ABBR_MONTHNAMES[month], width, flags) when 112 # 'p' fmt_str(internal_hour < 12 ? 'AM' : 'PM', width, flags) when 80 # 'P' @@ -387,7 +398,6 @@ def fmt_year(y, width, prec, flags) s = (y < 0 ? '-' : '') + s end end - raise Errno::ERANGE, "strftime" if s.length >= STRFTIME_MAX_COPY_LEN if flags & (FL_UPPER | FL_CHCASE) != 0 s.upcase else diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index 2cfef558..b2794703 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -63,7 +63,7 @@ def _strptime(string, format = '%F') # See also {strptime(3)}[https://man7.org/linux/man-pages/man3/strptime.3.html]. # # Related: Date._strptime (returns a hash). - def strptime(string = JULIAN_EPOCH_DATE, format = '%F', start = DEFAULT_SG) + def strptime(string = '-4712-01-01', format = '%F', start = ITALY) str = String === string ? string : string.to_str if format == '%F' || format == '%Y-%m-%d' result = internalinternal_strptime_ymd_to_date(str, start) From 7844527354e28f4642c08aa11953e57bedbcb71d Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 21:36:29 +0900 Subject: [PATCH 037/144] Apply behavior-preserving refactors from PR #155 review Mechanical cleanups from the jeremyevans/rhenium review. External behavior is unchanged; verified against the C extension. - Fix the double-prefixed method names internalinternal_strptime_ymd_to_date and internalinternal_strptime_abdy_to_date -> internal_strptime_* (lib/date/ strptime.rb), at both definitions and call sites. - Simplify Date#deconstruct_keys and DateTime#deconstruct_keys with the Ruby 3.1+ shorthand hash syntax ({ year: } for { year: year }). This is pure syntactic sugar and compiles to the same bytecode. - Make Date.new an alias of Date.civil, and Date#iso8601 / #xmlschema aliases of Date#to_s, removing the one-line delegator frames. iso8601's definition is moved after to_s so the alias resolves correctly. DateTime still overrides new / iso8601, so plain Date is the only class affected. - Fold check_numeric and its following Integer() call into a single convert_numeric_to_int method. The Numeric type check is kept so numeric- looking strings such as "0xa" are still rejected, and the per-argument check order is preserved so the same TypeError is raised first. Verified: full suite passes (144 tests, 162595 assertions, 100%); no -w warnings on require; type-error, pattern-matching, and output behavior all match the C extension. Performance (C ext vs pure Ruby with YJIT): method | C ext (i/s) | Ruby+YJIT (i/s) | ratio ------------------------------+-------------+-----------------+------ Date.new (= civil) | 4,648,499 | 6,571,000 | 141% Date.jd | 4,962,001 | 7,678,000 | 155% Date#iso8601 (= to_s) | 3,999,851 | 7,469,000 | 187% Date#deconstruct_keys(nil) | 3,618,973 | 3,390,000 | 94% Date#deconstruct_keys(year) | 5,607,895 | 5,757,000 | 103% Date#deconstruct_keys(y/m/d) | 3,942,985 | 3,210,000 | 81% The deconstruct_keys shorthand is purely syntactic, so the ratios reflect the existing method; the sub-100% deconstruct_keys(nil) and (y/m/d) cases are pre-existing and not affected by this change. --- lib/date/core.rb | 78 +++++++++++++++++++------------------------- lib/date/datetime.rb | 24 +++++++------- lib/date/strptime.rb | 8 ++--- 3 files changed, 49 insertions(+), 61 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index f62d4f20..3e4dcf30 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -57,9 +57,7 @@ def civil(year = -4712, month = 1, day = 1, start = ITALY) # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # # Related: Date.jd. - def new(year = -4712, month = 1, day = 1, start = ITALY) - civil(year, month, day, start) - end + alias_method :new, :civil # call-seq: # Date.valid_civil?(year, month, mday, start = Date::ITALY) -> true or false @@ -105,8 +103,7 @@ def valid_civil?(year, month, day, start = ITALY) # # Related: Date.new. def jd(jd = 0, start = ITALY) - check_numeric(jd, "jd") - jd = Integer(jd) + jd = convert_numeric_to_int(jd, "jd") obj = allocate obj.__send__(:init_from_jd, jd, start) obj @@ -196,10 +193,8 @@ def ordinal(year = -4712, yday = 1, start = ITALY) return new_from_jd(jd, start) end end - check_numeric(yday, "yday") - check_numeric(year, "year") - year = Integer(year) - yday = Integer(yday) + yday = convert_numeric_to_int(yday, "yday") + year = convert_numeric_to_int(year, "year") jd = internal_valid_ordinal?(year, yday, start) raise Date::Error, "invalid date" unless jd new_from_jd(jd, start) @@ -273,12 +268,9 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = ITALY) jd = commercial_to_jd(cwyear, cweek, cwday, start) return new_from_jd(jd, start) if jd < commercial_to_jd(cwyear + 1, 1, 1, start) end - check_numeric(cwday, "cwday") - check_numeric(cweek, "cweek") - check_numeric(cwyear, "year") - cwyear = Integer(cwyear) - cweek = Integer(cweek) - cwday = Integer(cwday) + cwday = convert_numeric_to_int(cwday, "cwday") + cweek = convert_numeric_to_int(cweek, "cweek") + cwyear = convert_numeric_to_int(cwyear, "year") jd = internal_valid_commercial?(cwyear, cweek, cwday, start) raise Date::Error, "invalid date" unless jd new_from_jd(jd, start) @@ -328,22 +320,20 @@ def _load(s) private - # Reject non-Numeric arguments up front. A bare Integer() conversion would - # coerce numeric-looking strings such as "0xa", so require a Numeric here - # and raise TypeError for anything else. - def check_numeric(obj, field) + # Convert a Numeric argument to an Integer. Rejects non-Numeric input up + # front: a bare Integer() conversion would coerce numeric-looking strings + # such as "0xa", so require a Numeric here and raise TypeError otherwise. + def convert_numeric_to_int(obj, field) unless Numeric === obj raise TypeError, "invalid #{field} (not numeric)" end + Integer(obj) end def civil_fallback(year, month, day, start) - check_numeric(day, "day") - check_numeric(month, "month") - check_numeric(year, "year") - year = Integer(year) - month = Integer(month) - day = Integer(day) + day = convert_numeric_to_int(day, "day") + month = convert_numeric_to_int(month, "month") + year = convert_numeric_to_int(year, "year") jd = internal_valid_civil?(year, month, day, start) raise Date::Error, "invalid date" unless jd new_from_jd(jd, start) @@ -1522,11 +1512,11 @@ def deconstruct_keys(keys) if keys if keys.size == 1 case keys[0] - when :year then { year: year } - when :month then { month: month } - when :day then { day: day } - when :wday then { wday: wday } - when :yday then { yday: yday } + when :year then { year: } + when :month then { month: } + when :day then { day: } + when :wday then { wday: } + when :yday then { yday: } else {} end else @@ -1543,7 +1533,7 @@ def deconstruct_keys(keys) h end else - { year: year, month: month, day: day, wday: wday, yday: yday } + { year:, month:, day:, wday:, yday: } end end @@ -1577,20 +1567,6 @@ def asctime end alias_method :ctime, :asctime - # call-seq: - # iso8601 -> string - # - # Equivalent to #strftime with argument '%Y-%m-%d' - # (or its {shorthand form}[rdoc-ref:language/strftime_formatting.rdoc@Shorthand+Conversion+Specifiers] - # '%F'); - # - # Date.new(2001, 2, 3).iso8601 # => "2001-02-03" - # - def iso8601 - to_s - end - alias_method :xmlschema, :iso8601 - # call-seq: # rfc3339 -> string # @@ -1696,6 +1672,18 @@ def to_s end end + # call-seq: + # iso8601 -> string + # + # Equivalent to #strftime with argument '%Y-%m-%d' + # (or its {shorthand form}[rdoc-ref:language/strftime_formatting.rdoc@Shorthand+Conversion+Specifiers] + # '%F'); + # + # Date.new(2001, 2, 3).iso8601 # => "2001-02-03" + # + alias_method :iso8601, :to_s + alias_method :xmlschema, :iso8601 + # call-seq: # inspect -> string # diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 384889f9..be15cab5 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -371,16 +371,16 @@ def deconstruct_keys(keys) if keys if keys.size == 1 case keys[0] - when :year then { year: year } - when :month then { month: month } - when :day then { day: day } - when :wday then { wday: wday } - when :yday then { yday: yday } - when :hour then { hour: hour } - when :min then { min: min } - when :sec then { sec: sec } - when :sec_fraction then { sec_fraction: sec_fraction } - when :zone then { zone: zone } + when :year then { year: } + when :month then { month: } + when :day then { day: } + when :wday then { wday: } + when :yday then { yday: } + when :hour then { hour: } + when :min then { min: } + when :sec then { sec: } + when :sec_fraction then { sec_fraction: } + when :zone then { zone: } else {} end else @@ -402,8 +402,8 @@ def deconstruct_keys(keys) h end else - { year: year, month: month, day: day, wday: wday, yday: yday, - hour: hour, min: min, sec: sec, sec_fraction: sec_fraction, zone: zone } + { year:, month:, day:, wday:, yday:, + hour:, min:, sec:, sec_fraction:, zone: } end end diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index b2794703..0edea3bf 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -66,12 +66,12 @@ def _strptime(string, format = '%F') def strptime(string = '-4712-01-01', format = '%F', start = ITALY) str = String === string ? string : string.to_str if format == '%F' || format == '%Y-%m-%d' - result = internalinternal_strptime_ymd_to_date(str, start) + result = internal_strptime_ymd_to_date(str, start) return result if result raise Error, 'invalid date' end if format == '%a %b %d %Y' - result = internalinternal_strptime_abdy_to_date(str, start) + result = internal_strptime_abdy_to_date(str, start) return result if result raise Error, 'invalid date' end @@ -495,7 +495,7 @@ def internal_strptime_ymd(str) STRPTIME_YMD_GENERAL_EXACT = /\A([+-]?\d+)-(\d{1,2})-(\d{1,2})\z/ private_constant :STRPTIME_YMD_GENERAL_EXACT - def internalinternal_strptime_ymd_to_date(str, sg) + def internal_strptime_ymd_to_date(str, sg) slen = str.bytesize # Fast path for exactly "YYYY-MM-DD" (10 chars, positive 4-digit year) @@ -564,7 +564,7 @@ def internal_strptime_abdy(str) # Parse "%a %b %d %Y" and directly create Date object. # Uses single regex match to avoid StringScanner allocation. - def internalinternal_strptime_abdy_to_date(str, sg) + def internal_strptime_abdy_to_date(str, sg) m = STRPTIME_ABDY_PAT.match(str) return nil unless m return nil unless m.post_match.empty? From 1270d21aff573a501341caa80d3e7cef78e0543a Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 21:56:36 +0900 Subject: [PATCH 038/144] Fix strftime colon parsing for %z to match the C extension The format parser scanned colons both before and after the width and summed them, so it accepted invalid sequences the C extension rejects, and miscounted colons around flags and width. Match the C grammar instead: after '%' come flags, then an optional width, then optional colons, then the conversion. Colons are meaningful only for %z and only up to three; a colon before the width, a colon on a non-z conversion, or four or more colons is invalid. In those cases the C extension emits the original text verbatim, so restore and emit it here. Examples now matching the C extension (DateTime with +09:00): format before after / C ext -------- ------------ ------------- %:10z +000009:00 %:10z %::10z +009:00:00 %::10z %::::z +09:00 %::::z %:1z +09:00 %:1z %::9z +09:00:00 %::9z %:3N 000 %:3N %:Y 2001 %:Y Verified: colon handling now matches the C extension across an exhaustive probe (18 cases fixed, no new differences); full suite passes (144 tests, 162595 assertions); no -w warnings. The remaining %_:z / %-9:z / %9-:z differences are pre-existing flag/width issues, unrelated to this change. --- lib/date/strftime.rb | 23 +++++++++++++++-------- 1 file changed, 15 insertions(+), 8 deletions(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index bb8456a7..abb6c3e6 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -111,9 +111,12 @@ def internal_strftime(fmt) sc.unscan end + # Record the position just after '%' so the original text can be + # restored verbatim if the spec turns out to be invalid. + spec_start = sc.charpos + # Parse flags (bitmask) flags = 0 - colons = 0 while (f = sc.scan(/[-_0^#]/)) case f when '-' then flags |= FL_LEFT @@ -123,9 +126,6 @@ def internal_strftime(fmt) when '#' then flags |= FL_CHCASE end end - if (c = sc.scan(/:+/)) - colons = c.length - end # Parse width width = sc.scan(/\d+/)&.to_i @@ -134,16 +134,23 @@ def internal_strftime(fmt) # Parse precision (after '.') prec = sc.skip(/\./) ? (sc.scan(/\d+/)&.to_i || 0) : nil - # Post-width colons (for %8:z, %11::z etc.) - if (c = sc.scan(/:+/)) - colons += c.length - end + # Colons follow the flags and width, and are only meaningful for %z. + colons = (c = sc.scan(/:+/)) ? c.length : 0 # Locale modifier (%E or %O) locale_mod = sc.scan(/[EO]/)&.ord spec = sc.getch&.ord + # Colons are valid only for %z and at most three of them. Any other use + # (a colon before the width, a colon with a non-z spec, or four or more + # colons) is invalid, and the C extension emits the original text + # literally rather than formatting it. + if colons > 0 && (spec != 122 || colons > 3) + result << '%' << fmt[spec_start...sc.charpos] + next + end + # Inline fast path: no flags, no width, no prec, no locale mod, no colons if flags == 0 && width.nil? && prec.nil? && locale_mod.nil? && colons == 0 fast = fast_spec(spec) From 025665ce38926f54a9d1feb07357887a8ad3ff0e Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 22:01:14 +0900 Subject: [PATCH 039/144] Restore width and colons when a locale modifier is invalid in strftime When an %E / %O locale modifier was not valid for the following conversion, format_spec_b rebuilt the literal as "%E"/"%O" plus the spec character only, dropping any width or colons that preceded the spec. Validate the modifier during parsing instead, where the original text is available, and emit it verbatim (as the C extension does) when the modifier is invalid. This also removes the now-unused locale_mod parameter from format_spec_b. Examples now matching the C extension: format before after / C ext ------- ------- ------------- %10OY %OY %10OY %1Em %Em %1Em %:Oz %Oz %:Oz Verified: E/O handling now matches the C extension across an exhaustive probe; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/strftime.rb | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index abb6c3e6..b30fb25d 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -151,6 +151,17 @@ def internal_strftime(fmt) next end + # A locale modifier (%E / %O) is only valid for certain conversions. + # When it is not, the C extension emits the original text verbatim, + # including any width, colons, and flags, so restore and emit it here. + if locale_mod + valid = locale_mod == 69 ? STRFTIME_E_VALID_BYTES : STRFTIME_O_VALID_BYTES # 69='E' + unless valid.include?(spec) + result << '%' << fmt[spec_start...sc.charpos] + next + end + end + # Inline fast path: no flags, no width, no prec, no locale mod, no colons if flags == 0 && width.nil? && prec.nil? && locale_mod.nil? && colons == 0 fast = fast_spec(spec) @@ -160,7 +171,7 @@ def internal_strftime(fmt) end end - result << format_spec_b(spec, flags, colons, width, prec, locale_mod) + result << format_spec_b(spec, flags, colons, width, prec) end result @@ -282,16 +293,7 @@ def fast_spec(spec) end # Full spec handling with bitmask flags (called when fast_spec returns nil or flags/width/prec present) - def format_spec_b(spec, flags, colons, width, prec, locale_mod) - # Handle %E/%O locale modifiers - if locale_mod - valid = locale_mod == 69 ? STRFTIME_E_VALID_BYTES : STRFTIME_O_VALID_BYTES # 69='E' - unless valid.include?(spec) - mod_chr = locale_mod == 69 ? 'E' : 'O' - return "%#{mod_chr}#{spec&.chr}" - end - end - + def format_spec_b(spec, flags, colons, width, prec) case spec when 89, 71 # 'Y', 'G' y = spec == 89 ? year : cwyear From 3e3572dca588d2b35de198e95fefea7317ab2bf2 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 22:07:56 +0900 Subject: [PATCH 040/144] Remove hallucinated width.precision handling from strftime The C extension's strftime grammar has no precision field: a '.' after '%' (optionally after a width) is not special and the whole spec is emitted literally. The Ruby parser instead accepted "width.precision" (as in snprintf) and produced formatted output that the C extension never does, e.g. %1.2m -> "2" and %.3Y -> "2001". Drop precision parsing entirely. A '.' now ends the spec as invalid, so the text up to and including it is emitted verbatim, matching the C extension. The unused prec parameter is removed from format_spec_b, fmt_year, and fmt_z, and %N/%L keep using the width field as before. Examples now matching the C extension: format before after / C ext ------- ------- ------------- %1.2m 2 %1.2m %.2m 02 %.2m %.3Y 2001 %.3Y %1.2N 0 %1.2N %1.2z +0900 %1.2z Verified: all '.'-containing formats now match the C extension; a broad spec/flag/width sanity sweep shows no new differences (the remaining %C / %s / %_z padding differences are pre-existing); full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/strftime.rb | 40 +++++++++++++++++++++------------------- 1 file changed, 21 insertions(+), 19 deletions(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index b30fb25d..cf194f9c 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -101,7 +101,7 @@ def internal_strftime(fmt) end # Quick dispatch: if next char is a simple letter spec (A-Z excluding E/O, - # or a-z), skip flag/width/prec parsing entirely. + # or a-z), skip flag/width parsing entirely. if (quick = sc.scan(/[A-DFG-NP-Za-z]/)) fast = fast_spec(quick.ord) if fast @@ -131,8 +131,13 @@ def internal_strftime(fmt) width = sc.scan(/\d+/)&.to_i raise Errno::ERANGE, "strftime" if width && width > STRFTIME_MAX_WIDTH - # Parse precision (after '.') - prec = sc.skip(/\./) ? (sc.scan(/\d+/)&.to_i || 0) : nil + # The C extension's strftime grammar has no precision field, so a '.' + # here makes the spec invalid. Emit the text up to and including it + # verbatim (as the C extension does) and resume scanning after it. + if sc.skip(/\./) + result << '%' << fmt[spec_start...sc.charpos] + next + end # Colons follow the flags and width, and are only meaningful for %z. colons = (c = sc.scan(/:+/)) ? c.length : 0 @@ -162,8 +167,8 @@ def internal_strftime(fmt) end end - # Inline fast path: no flags, no width, no prec, no locale mod, no colons - if flags == 0 && width.nil? && prec.nil? && locale_mod.nil? && colons == 0 + # Inline fast path: no flags, no width, no locale mod, no colons + if flags == 0 && width.nil? && locale_mod.nil? && colons == 0 fast = fast_spec(spec) if fast result << fast @@ -171,7 +176,7 @@ def internal_strftime(fmt) end end - result << format_spec_b(spec, flags, colons, width, prec) + result << format_spec_b(spec, flags, colons, width) end result @@ -191,7 +196,7 @@ def fmt_asctime_str end end - # Inline fast path for common specs with default formatting (no flags/width/prec) + # Inline fast path for common specs with default formatting (no flags/width) def fast_spec(spec) case spec when 89 # 'Y' @@ -292,12 +297,12 @@ def fast_spec(spec) end end - # Full spec handling with bitmask flags (called when fast_spec returns nil or flags/width/prec present) - def format_spec_b(spec, flags, colons, width, prec) + # Full spec handling with bitmask flags (called when fast_spec returns nil or flags/width present) + def format_spec_b(spec, flags, colons, width) case spec when 89, 71 # 'Y', 'G' y = spec == 89 ? year : cwyear - fmt_year(y, width, prec, flags) + fmt_year(y, width, flags) when 67 # 'C' cent = year.div(100) pad_num(cent, width || 2, flags) @@ -334,7 +339,7 @@ def format_spec_b(spec, flags, colons, width, prec) ms = (sec_frac * (10**w)).floor ms.to_s.rjust(w, '0') when 78 # 'N' - w = width || prec || 9 + w = width || 9 ns = (sec_frac * (10**w)).floor ns.to_s.rjust(w, '0') when 115 # 's' @@ -361,7 +366,7 @@ def format_spec_b(spec, flags, colons, width, prec) when 90 # 'Z' fmt_str(zone_str, width, flags) when 122 # 'z' - fmt_z(colons, width, prec, flags) + fmt_z(colons, width, flags) when 117 # 'u' pad_num(cwday, width || 1, flags) when 119 # 'w' @@ -389,12 +394,9 @@ def format_spec_b(spec, flags, colons, width, prec) end end - # Format year (handles negative years, precision, and all flag variants) - def fmt_year(y, width, prec, flags) - if prec - s = y.abs.to_s.rjust(prec, '0') - s = (y < 0 ? '-' : '') + s - elsif flags & FL_LEFT != 0 + # Format year (handles negative years and all flag variants) + def fmt_year(y, width, flags) + if flags & FL_LEFT != 0 s = (y < 0 ? '-' : '') + y.abs.to_s else default_w = y < 0 ? 5 : 4 @@ -458,7 +460,7 @@ def week_number(ws) end # Format %z with colons variant and GNU extension flag support - def fmt_z(colons, width, _prec, flags) + def fmt_z(colons, width, flags) of = of_seconds sign = of < 0 ? '-' : '+' abs = of.abs From 24a670e5b7438ab0ef4a96d90db6cb9036be0cd7 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 22:12:59 +0900 Subject: [PATCH 041/144] Zero-pad %C, %s, %Q, %u, %w in strftime to match the C extension These numeric conversions were formatted with pad_num's default, which space-pads, but the C extension zero-pads them when a width is given. Pass zero: true for each so a width pads with '0': format before after / C ext ------- ------------ ------------ %4u " 6" "0006" %4w " 6" "0006" %4C " 20" "0020" %10s " 981140706" "0981140706" %20Q (space-pad) "000...86400000" Verified: padding for these specs now matches the C extension; a broad spec/flag/width sweep shows no new differences (the remaining %_z / %_:z space-flag differences on %z are pre-existing and belong to flag handling, addressed separately); full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/strftime.rb | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index cf194f9c..89d56646 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -305,7 +305,7 @@ def format_spec_b(spec, flags, colons, width) fmt_year(y, width, flags) when 67 # 'C' cent = year.div(100) - pad_num(cent, width || 2, flags) + pad_num(cent, width || 2, flags, zero: true) when 121 # 'y' pad_num(year % 100, width || 2, flags, zero: true) when 103 # 'g' @@ -345,12 +345,12 @@ def format_spec_b(spec, flags, colons, width) when 115 # 's' unix = (@jd - 2440588) * 86400 - of_seconds + internal_hour * 3600 + internal_min * 60 + internal_sec - pad_num(unix, width || 1, flags) + pad_num(unix, width || 1, flags, zero: true) when 81 # 'Q' ms = ((@jd - 2440588) * 86400 - of_seconds + internal_hour * 3600 + internal_min * 60 + internal_sec) * 1000 + (sec_frac * 1000).floor - pad_num(ms, width || 1, flags) + pad_num(ms, width || 1, flags, zero: true) when 65 # 'A' fmt_str(DAYNAMES[wday], width, flags) when 97 # 'a' @@ -368,9 +368,9 @@ def format_spec_b(spec, flags, colons, width) when 122 # 'z' fmt_z(colons, width, flags) when 117 # 'u' - pad_num(cwday, width || 1, flags) + pad_num(cwday, width || 1, flags, zero: true) when 119 # 'w' - pad_num(wday, width || 1, flags) + pad_num(wday, width || 1, flags, zero: true) when 85 # 'U' pad_num(week_number(0), width || 2, flags, zero: true) when 87 # 'W' From 64154a1eea837f2c7e0ae719c2da4227d51a29f0 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 22:18:13 +0900 Subject: [PATCH 042/144] Respect strftime flag order for space vs zero padding The '_' (space) and '0' (zero) padding flags were accumulated into a bitmask, so when both appeared their combined state ignored the order in which they were written. The C extension lets the last one win. Make '_' and '0' mutually exclusive in the flag scan: '_' sets space and clears zero, '0' sets zero and clears space. Examples now matching the C extension (month = 07): format before after / C ext ------- ------- ------------- %_0m " 7" "07" %0_m " 7" " 7" %_04m " 7" "0007" %0_4m " 7" " 7" %_0H " 4" "04" Verified: flag-order cases now match the C extension; full suite passes (144 tests, 162595 assertions); no -w warnings. Remaining %z flag handling and flag-after-width cases are addressed in follow-up commits. --- lib/date/strftime.rb | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 89d56646..632ca3f8 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -120,8 +120,10 @@ def internal_strftime(fmt) while (f = sc.scan(/[-_0^#]/)) case f when '-' then flags |= FL_LEFT - when '_' then flags |= FL_SPACE - when '0' then flags |= FL_ZERO + # '_' (space) and '0' (zero) padding are mutually exclusive; whichever + # is specified last wins, matching the C extension. + when '_' then flags = (flags | FL_SPACE) & ~FL_ZERO + when '0' then flags = (flags | FL_ZERO) & ~FL_SPACE when '^' then flags |= FL_UPPER when '#' then flags |= FL_CHCASE end From 7b9c9ade633dd555563e4c73c8417a2d87ac138d Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 22:22:13 +0900 Subject: [PATCH 043/144] Reject a strftime flag that appears after the width Flags must precede the width in the C extension's strftime grammar. A flag character following the width digits makes the spec invalid, and the C extension emits the scanned text verbatim rather than formatting it. Peek for a flag right after parsing the width, and when one is present emit what was scanned so far (flags plus width) literally, resuming the scan from the stray flag. Examples now matching the C extension: format before after / C ext ------- ------- ------------- %4_m "%_m" "%4_m" %04_m "%_m" "%04_m" %4_0m "%_0m" "%4_0m" %10-Y "2001" "%10-Y" Verified: flag-after-width cases now match the C extension; full suite passes (144 tests, 162595 assertions); no -w warnings. The remaining %z flag differences are addressed in a follow-up commit. --- lib/date/strftime.rb | 8 ++++++++ 1 file changed, 8 insertions(+) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 632ca3f8..7c59da50 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -133,6 +133,14 @@ def internal_strftime(fmt) width = sc.scan(/\d+/)&.to_i raise Errno::ERANGE, "strftime" if width && width > STRFTIME_MAX_WIDTH + # Flags must precede the width. A flag appearing after the width makes + # the spec invalid, so emit what was scanned so far verbatim (as the C + # extension does) and resume scanning from the stray flag. + if sc.check(/[-_0^#]/) + result << '%' << fmt[spec_start...sc.charpos] + next + end + # The C extension's strftime grammar has no precision field, so a '.' # here makes the spec invalid. Emit the text up to and including it # verbatim (as the C extension does) and resume scanning after it. From c67d644bd3d14085872e3680c036a24743189202 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 22:31:42 +0900 Subject: [PATCH 044/144] Fix %z flag handling in strftime to match the C extension For %z the '_' and '-' flags behave unlike other conversions, and fmt_z handled them incorrectly: '-' returned the value unpadded even with a width, and '_' only padded when an explicit width was given. Match the C extension: - '_' pads with spaces, to at least the width the zero-padded form would occupy; '-' suppresses that automatic minimum width. - '-' does not left-justify %z; with a width it zero-pads like the default. format before after / C ext -------- ------------ ------------ %_z "+900" " +900" %-10z "+900" "+000000900" %-_z "+900" "+900" %-_10z "+900" " +900" %_::z "+9:00:00" " +9:00:00" Verified: an 86,400-case format x flag x width x colon x modifier sweep over several offsets and eras shows no remaining %z differences; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/strftime.rb | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 7c59da50..af6a00ac 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -520,15 +520,16 @@ def fmt_z(colons, width, flags) end end - if width - if flags & FL_LEFT != 0 - s - elsif flags & FL_SPACE != 0 - s.rjust(width, ' ') - else - digits = s[1..] - sign + digits.rjust(width - 1, '0') - end + if flags & FL_SPACE != 0 + # '_' pads with spaces. Without '-' it pads to at least the width the + # zero-padded form would occupy (the hour is the only field that loses + # its leading zero); '-' suppresses that automatic minimum width. + min_w = (flags & FL_LEFT != 0) ? 0 : s.length + (hh < 10 ? 1 : 0) + s.rjust([width || 0, min_w].max, ' ') + elsif width + # The default and '-' both zero-pad to the given width; for %z, '-' does + # not left-justify. + sign + s[1..].rjust(width - 1, '0') else s end From 160735e96dc798f7c9bcf059620b415f32fa7fc6 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 22:34:53 +0900 Subject: [PATCH 045/144] Pad the %% conversion in strftime like the C extension format_spec_b returned a bare "%" for the %% conversion, ignoring any width or flags. The C extension pads it like a string, the same way %n and %t are already handled here. Route %% through fmt_str so width and padding flags apply: format before after / C ext ------- ------- ------------- %2% "%" " %" %02% "%" "0%" %010% "%" "000000000%" %_10% "%" " %" %-2% "%" "%" Verified: an 86,400-case strftime sweep now differs from the C extension only in the pre-existing %C negative-value space-padding case; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/strftime.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index af6a00ac..d3f45fa8 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -388,7 +388,7 @@ def format_spec_b(spec, flags, colons, width) when 86 # 'V' pad_num(cweek, width || 2, flags, zero: true) when 37 # '%' - '%' + fmt_str('%', width, flags) when 43 # '+' s = internal_strftime('%a %b %e %H:%M:%S %Z %Y') fmt_str(s, width, flags) From 2e0b1a25c8b304916055e199aee2b5b5dae54387 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 22:38:02 +0900 Subject: [PATCH 046/144] Keep the sign with the digits when space-padding in strftime pad_num prefixed the minus sign and then right-justified only the digits, so a negative value space-padded as "- 1" instead of " -1". The C extension right-justifies the sign together with the digits. Right-justify the whole "sign + digits" string for space padding: format before after / C ext ------- -------------- -------------- %_4C "- 1" " -1" %_10C "- 1" " -1" %_20s "- ...800" " ...-...800" (shown for a negative century / pre-epoch %s) Verified: an 86,400-case strftime sweep, plus an extended sweep over year 0/9999, negative years, the Gregorian cutover, JD 0, a leap day and sub-hour offsets, now matches the C extension with zero differences; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/strftime.rb | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index d3f45fa8..babca830 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -434,7 +434,9 @@ def pad_num(n, default_w, flags, zero: nil) if flags & FL_LEFT != 0 sign + abs elsif flags & FL_SPACE != 0 || (flags & FL_ZERO == 0 && zero == false) - sign + abs.rjust(w - sign.length, ' ') + # Space padding right-justifies the sign together with the digits, so a + # negative value pads as " -1", not "- 1" (matching the C extension). + (sign + abs).rjust(w, ' ') else pad = (flags & FL_ZERO != 0 || zero) ? '0' : ' ' sign + abs.rjust([w - sign.length, abs.length].max, pad) From 1cea9faea6c45af61501b8b2f31767d8bd6fee9d Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 22:44:15 +0900 Subject: [PATCH 047/144] Raise TypeError for non-String strptime arguments, matching the C extension _strptime / strptime coerced their string and format arguments with a bare #to_str, so a non-String argument raised NoMethodError (undefined method 'to_str') instead of the C extension's TypeError ("no implicit conversion of X into String"). Add a to_string_value helper that mirrors the C extension's StringValue: it accepts a String or any object with #to_str (via String.try_convert), and otherwise raises TypeError with the same message, including the special nil/true/false names the C error uses. Route the three coercion sites through it. Date._strptime(:foo, "%z") before: undefined method 'to_str' for an instance of Symbol (NoMethodError) after : no implicit conversion of Symbol into String (TypeError) Verified: error behavior now matches the C extension for Symbol, Object, Integer, nil, Array, Float, Hash arguments (string and format); objects responding to #to_str are still accepted; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/strptime.rb | 22 +++++++++++++++++++--- 1 file changed, 19 insertions(+), 3 deletions(-) diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index 0edea3bf..fe790050 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -18,8 +18,8 @@ class << self # # Related: Date.strptime (returns a \Date object). def _strptime(string, format = '%F') - string = String === string ? string : string.to_str - format = String === format ? format : format.to_str + string = to_string_value(string) + format = to_string_value(format) if format == '%F' || format == '%Y-%m-%d' return internal_strptime_ymd(string) end @@ -64,7 +64,7 @@ def _strptime(string, format = '%F') # # Related: Date._strptime (returns a hash). def strptime(string = '-4712-01-01', format = '%F', start = ITALY) - str = String === string ? string : string.to_str + str = to_string_value(string) if format == '%F' || format == '%Y-%m-%d' result = internal_strptime_ymd_to_date(str, start) return result if result @@ -90,6 +90,22 @@ def strptime(string = '-4712-01-01', format = '%F', start = ITALY) private + # Coerce an argument to a String the way the C extension's StringValue + # does: accept a String or anything with #to_str, otherwise raise a + # TypeError with the "no implicit conversion" message (using the special + # names nil/true/false, as the C error does). + def to_string_value(obj) + str = String.try_convert(obj) + return str if str + name = case obj + when nil then 'nil' + when true then 'true' + when false then 'false' + else obj.class.name + end + raise TypeError, "no implicit conversion of #{name} into String" + end + # Pre-compiled regex constants for sp_run SP_WHITESPACE = /[ \t\n\r\v\f]+/ SP_COLONS = /:+/ From 606cd8228acd0471bb017b25f3e543da33234984 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 22:53:34 +0900 Subject: [PATCH 048/144] Raise TypeError for non-String parse arguments, matching the C extension The _parse / _rfc3339 / _iso8601 / _rfc2822 / _httpdate / _jisx0301 / _xmlschema methods coerced a non-String argument with a bare #to_str, so an object without #to_str raised NoMethodError instead of the C extension's TypeError ("no implicit conversion of X into String"). Route coercion through the to_string_value helper (shared from strptime.rb): it accepts a String or any #to_str object and otherwise raises TypeError with the correct message, including the nil/true/false special names. The underscore keyword-parsing methods keep returning {} for a nil argument; every other non-String (Symbol included, as the test suite requires) now raises TypeError. The non-underscore methods inherit this via their _xxx delegate. The previously unused parse_to_str helper is removed. Date._rfc3339(Object.new) before: undefined method 'to_str' for an instance of Object (NoMethodError) after : no implicit conversion of Object into String (TypeError) Verified: type-error behavior matches the C extension and the official tests (nil -> {} for _xxx, Symbol/Object/Integer/nil/Array/Float/Hash -> TypeError); objects responding to #to_str are still accepted; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/parse.rb | 29 +++++++---------------------- 1 file changed, 7 insertions(+), 22 deletions(-) diff --git a/lib/date/parse.rb b/lib/date/parse.rb index a4c2dd93..c532e78d 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -34,9 +34,8 @@ class << self # Related: Date.rfc3339 (returns a \Date object). def _rfc3339(string, limit: 128) unless String === string - raise TypeError if string.is_a?(Symbol) return {} if string.nil? - string = string.to_str + string = to_string_value(string) end return {} if string.empty? raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit @@ -101,9 +100,8 @@ def _rfc3339(string, limit: 128) # Related: Date.httpdate (returns a \Date object). def _httpdate(string, limit: 128) unless String === string - raise TypeError if string.is_a?(Symbol) return {} if string.nil? - string = string.to_str + string = to_string_value(string) end return {} if string.empty? raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit @@ -183,9 +181,8 @@ def _httpdate(string, limit: 128) # Related: Date.rfc2822 (returns a \Date object). def _rfc2822(string, limit: 128) unless String === string - raise TypeError if string.is_a?(Symbol) return {} if string.nil? - string = string.to_str + string = to_string_value(string) end return {} if string.empty? raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit @@ -264,9 +261,8 @@ def _rfc2822(string, limit: 128) # Related: Date.xmlschema (returns a \Date object). def _xmlschema(string, limit: 128) unless String === string - raise TypeError if string.is_a?(Symbol) return {} if string.nil? - string = string.to_str + string = to_string_value(string) end return {} if string.empty? raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit @@ -326,9 +322,8 @@ def _xmlschema(string, limit: 128) # Related: Date.iso8601 (returns a \Date object). def _iso8601(string, limit: 128) unless String === string - raise TypeError if string.is_a?(Symbol) return {} if string.nil? - string = string.to_str + string = to_string_value(string) end return {} if string.empty? raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit @@ -382,9 +377,8 @@ def _iso8601(string, limit: 128) # Related: Date.jisx0301 (returns a \Date object). def _jisx0301(string, limit: 128) unless String === string - raise TypeError if string.is_a?(Symbol) return {} if string.nil? - string = string.to_str + string = to_string_value(string) end return {} if string.empty? raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit @@ -454,10 +448,7 @@ def _jisx0301(string, limit: 128) # # Related: Date.parse(returns a \Date object). def _parse(string, comp = true, limit: 128) - unless String === string - raise TypeError, "no implicit conversion of #{string.class} into String" if string.is_a?(Symbol) || string.nil? - string = string.to_str - end + string = to_string_value(string) unless String === string return {} if string.empty? raise ArgumentError, "string length (#{string.length}) exceeds limit (#{limit})" if limit && string.length > limit @@ -815,12 +806,6 @@ def parse_check_limit(str, limit) raise ArgumentError, "string length (#{str.length}) exceeds limit (#{limit})" if limit && str.length > limit end - def parse_to_str(obj) - return nil if obj.nil? - raise TypeError, "no implicit conversion of #{obj.class} into String" if obj.is_a?(Symbol) - String === obj ? obj : obj.to_str - end - def parse_zone_and_offset(zone_str, hash) return unless zone_str hash[:zone] = zone_str From 040b94816353270c9a32794d68012324a6b38869 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 22:56:40 +0900 Subject: [PATCH 049/144] Unify the strptime/parse limit-exceeded message via parse_check_limit _parse used "string length (N) exceeds limit (L)", while the C extension and the _rfc3339 / _iso8601 / etc. methods use "string length (N) exceeds the limit L". The parse_check_limit helper had the wrong wording too and was never called. Correct parse_check_limit's message and route all seven length checks (_parse and the six _xxx methods) through it, removing the duplicated inline raises. Date._parse("x" * 200, limit: 10) before: string length (200) exceeds limit (10) (ArgumentError) after : string length (200) exceeds the limit 10 (ArgumentError) Verified: the limit-exceeded message matches the C extension across all parse entry points; boundary cases (limit: nil, length == limit) behave correctly; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/parse.rb | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) diff --git a/lib/date/parse.rb b/lib/date/parse.rb index c532e78d..c5f2068f 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -38,7 +38,7 @@ def _rfc3339(string, limit: 128) string = to_string_value(string) end return {} if string.empty? - raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit + parse_check_limit(string, limit) # Fast path: YYYY-MM-DDTHH:MM:SS+HH:MM (25 bytes) or YYYY-MM-DDTHH:MM:SSZ (20 bytes) len = string.length @@ -104,7 +104,7 @@ def _httpdate(string, limit: 128) string = to_string_value(string) end return {} if string.empty? - raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit + parse_check_limit(string, limit) # Fast path for Type 1: "Dow, DD Mon YYYY HH:MM:SS GMT" (29 bytes) len = string.length @@ -185,7 +185,7 @@ def _rfc2822(string, limit: 128) string = to_string_value(string) end return {} if string.empty? - raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit + parse_check_limit(string, limit) # Fast path: "Dow, DD Mon YYYY HH:MM:SS +ZZZZ" (31 bytes, 2-digit day) len = string.length @@ -265,7 +265,7 @@ def _xmlschema(string, limit: 128) string = to_string_value(string) end return {} if string.empty? - raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit + parse_check_limit(string, limit) # Fast path: YYYY-MM-DD (exactly 10 bytes, all ASCII) if string.length == 10 @@ -326,7 +326,7 @@ def _iso8601(string, limit: 128) string = to_string_value(string) end return {} if string.empty? - raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit + parse_check_limit(string, limit) # Fast path: YYYY-MM-DD (exactly 10 bytes, all ASCII) if string.length == 10 @@ -381,7 +381,7 @@ def _jisx0301(string, limit: 128) string = to_string_value(string) end return {} if string.empty? - raise ArgumentError, "string length (#{string.length}) exceeds the limit #{limit}" if limit && string.length > limit + parse_check_limit(string, limit) # Fast path: X##.##.## (9 bytes: era + YY.MM.DD) if string.length == 9 @@ -450,7 +450,7 @@ def _jisx0301(string, limit: 128) def _parse(string, comp = true, limit: 128) string = to_string_value(string) unless String === string return {} if string.empty? - raise ArgumentError, "string length (#{string.length}) exceeds limit (#{limit})" if limit && string.length > limit + parse_check_limit(string, limit) # === Fast paths for common date formats === len = string.length @@ -803,7 +803,7 @@ def jisx0301(string = '-4712-01-01', start = ITALY, limit: 128) # ------------------------------------------------------------------ def parse_check_limit(str, limit) - raise ArgumentError, "string length (#{str.length}) exceeds limit (#{limit})" if limit && str.length > limit + raise ArgumentError, "string length (#{str.length}) exceeds the limit #{limit}" if limit && str.length > limit end def parse_zone_and_offset(zone_str, hash) From 523e0d813210d39e3f2143b76f416e9b2c61615c Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 23:07:24 +0900 Subject: [PATCH 050/144] Validate DateTime.new argument types like the C extension DateTime#initialize converted year and month with Integer(), so numeric strings such as "2000" were accepted where the C extension raises TypeError; day/hour/minute/second raised the generic "expected numeric"; and a non-numeric offset was silently treated as 0. Validate each argument as Numeric with the C extension's message ("invalid (not numeric)"), raise "expected numeric" for a non-String/non-Numeric offset, and run the checks in the C extension's order (offset, then second down to year) so the same field is reported first when several arguments are invalid. Type errors are now raised before the invalid-date check, as in the C extension. DateTime.new("2000") before: OK after: invalid year (not numeric) DateTime.new(2000, "10") before: OK after: invalid month (not numeric) DateTime.new(2000,1,1,"4") before: expected numeric after: invalid hour (not numeric) DateTime.new(2000,1,1,0,0,0,:z) before: OK after: expected numeric Verified: single- and multi-bad-argument cases and the type-vs-invalid-date precedence match the C extension; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/datetime.rb | 20 +++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index be15cab5..8150ed63 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -13,11 +13,17 @@ class DateTime < Date # call-seq: # DateTime.new(year=-4712, month=1, day=1, hour=0, minute=0, second=0, offset=0, start=Date::ITALY) -> datetime def initialize(year = -4712, month = 1, day = 1, hour = 0, minute = 0, second = 0, offset = 0, start = ITALY) - year = Integer(year) - month = Integer(month) + # Validate argument types in the C extension's order (offset, then second + # down to year) so the same field is reported first when several are bad. of_sec = _str_offset_to_sec(offset) - - raise TypeError, "expected numeric" unless day.is_a?(Numeric) + raise TypeError, "invalid second (not numeric)" unless second.is_a?(Numeric) + raise TypeError, "invalid minute (not numeric)" unless minute.is_a?(Numeric) + raise TypeError, "invalid hour (not numeric)" unless hour.is_a?(Numeric) + raise TypeError, "invalid day (not numeric)" unless day.is_a?(Numeric) + raise TypeError, "invalid month (not numeric)" unless month.is_a?(Numeric) + month = Integer(month) + raise TypeError, "invalid year (not numeric)" unless year.is_a?(Numeric) + year = Integer(year) # Fractional day/hour/minute: propagate fraction to smaller units day_r = day.to_r @@ -28,10 +34,6 @@ def initialize(year = -4712, month = 1, day = 1, hour = 0, minute = 0, second = jd = self.class.__send__(:internal_valid_civil?, year, month, day, start) raise Date::Error, "invalid date" unless jd - raise TypeError, "expected numeric" unless hour.is_a?(Numeric) - raise TypeError, "expected numeric" unless minute.is_a?(Numeric) - raise TypeError, "expected numeric" unless second.is_a?(Numeric) - # Propagate fractions to smaller units hour_r = hour.to_r + day_frac * 24 hour_i = hour_r.floor @@ -964,7 +966,7 @@ def _str_offset_to_sec(offset) raise TypeError, "#{offset.class} can't be used as offset" unless r.is_a?(Rational) (r * 86400).to_i else - 0 + raise TypeError, "expected numeric" end end From c7260fdf933666ef920fe6be97b1a80d10a0c0d6 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 23:15:36 +0900 Subject: [PATCH 051/144] Reject a trailing fraction in DateTime.new like the C extension DateTime accepted a fractional day/hour/minute even when a smaller unit was also given (e.g. DateTime.new(2000,1,1.5,1)), silently folding the fraction in, whereas the C extension raises Date::Error "invalid fraction". A fraction is only allowed on the last argument supplied. Distinguish an omitted hour/minute/second from an explicit 0 with an UNSET sentinel default, and raise "invalid fraction" when a fractional day/hour/minute is followed by a supplied smaller unit. The checks run after the type checks and before the date-validity check, matching the C extension's precedence. The class-level DateTime.new now forwards *args to initialize (removing the duplicated default list) so the sentinels propagate. DateTime.new(2000,1,1.5) => OK (12:00:00) DateTime.new(2000,1,1.5,1) before: OK (13:00) after: invalid fraction DateTime.new(2000,1,1.5,0) before: OK (12:00) after: invalid fraction DateTime.new(2000,1,1,2.5,1) before: OK after: invalid fraction Verified: fractional-argument acceptance, and the fraction-vs-type-vs- invalid-date precedence, match the C extension; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/datetime.rb | 40 ++++++++++++++++++++++++++++++---------- 1 file changed, 30 insertions(+), 10 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 8150ed63..77628d7c 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -6,13 +6,25 @@ class DateTime < Date STRFTIME_DATETIME_DEFAULT_FMT = '%FT%T%:z'.encode(Encoding::US_ASCII) private_constant :STRFTIME_DATETIME_DEFAULT_FMT + # Sentinel marking an hour/minute/second argument that was not passed, so a + # trailing fraction can be rejected only when a smaller unit was actually given. + UNSET = Object.new + private_constant :UNSET + # --------------------------------------------------------------------------- # Initializer # --------------------------------------------------------------------------- # call-seq: # DateTime.new(year=-4712, month=1, day=1, hour=0, minute=0, second=0, offset=0, start=Date::ITALY) -> datetime - def initialize(year = -4712, month = 1, day = 1, hour = 0, minute = 0, second = 0, offset = 0, start = ITALY) + def initialize(year = -4712, month = 1, day = 1, hour = UNSET, minute = UNSET, second = UNSET, offset = 0, start = ITALY) + hour_given = !UNSET.equal?(hour) + minute_given = !UNSET.equal?(minute) + second_given = !UNSET.equal?(second) + hour = 0 if UNSET.equal?(hour) + minute = 0 if UNSET.equal?(minute) + second = 0 if UNSET.equal?(second) + # Validate argument types in the C extension's order (offset, then second # down to year) so the same field is reported first when several are bad. of_sec = _str_offset_to_sec(offset) @@ -25,21 +37,29 @@ def initialize(year = -4712, month = 1, day = 1, hour = 0, minute = 0, second = raise TypeError, "invalid year (not numeric)" unless year.is_a?(Numeric) year = Integer(year) - # Fractional day/hour/minute: propagate fraction to smaller units + # A fractional day/hour/minute is only allowed as the last argument given; + # if a smaller unit was also supplied, the C extension rejects the fraction. + # These checks run before the date-validity check, as in the C extension. day_r = day.to_r - day_i = day_r.floor - day_frac = day_r - day_i - day = day_i - + day_frac = day_r - day_r.floor + hour_r0 = hour.to_r + hour_f0 = hour_r0 - hour_r0.floor + minute_r0 = minute.to_r + minute_f0 = minute_r0 - minute_r0.floor + raise Date::Error, "invalid fraction" if day_frac != 0 && (hour_given || minute_given || second_given) + raise Date::Error, "invalid fraction" if hour_f0 != 0 && (minute_given || second_given) + raise Date::Error, "invalid fraction" if minute_f0 != 0 && second_given + + day = day_r.floor jd = self.class.__send__(:internal_valid_civil?, year, month, day, start) raise Date::Error, "invalid date" unless jd # Propagate fractions to smaller units - hour_r = hour.to_r + day_frac * 24 + hour_r = hour_r0 + day_frac * 24 hour_i = hour_r.floor hour_frac = hour_r - hour_i - minute_r = minute.to_r + hour_frac * 60 + minute_r = minute_r0 + hour_frac * 60 minute_i = minute_r.floor minute_frac = minute_r - minute_i @@ -536,9 +556,9 @@ def to_time # --------------------------------------------------------------------------- class << self - def new(year = -4712, month = 1, day = 1, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) + def new(*args) instance = allocate - instance.__send__(:initialize, year, month, day, hour, minute, second, offset, start) + instance.__send__(:initialize, *args) instance end alias_method :civil, :new From 6a9a4da67bfd8d235d6f6bd9998a0f0d7e3fee47 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 23:21:00 +0900 Subject: [PATCH 052/144] Ignore out-of-range numeric DateTime offsets like the C extension A numeric offset (a fraction of a day) was accepted unconditionally, so values outside the valid range produced absurd zones such as -720:00 for DateTime.new(...,-30). The C extension applies a per-type range check. Match it in _str_offset_to_sec: - Integer: only -1, 0, 1 (whole days) are valid; anything else is ignored (offset 0). - Float: valid only within +/- one day; out of range is ignored, and a fractional second is rounded. - Rational (and other numerics via to_r): honored without a range limit. DateTime.new(2001,2,3,4,5,6,-30) before: -720:00 after: +00:00 DateTime.new(2001,2,3,4,5,6,100) before: +2400:00 after: +00:00 DateTime.new(2001,2,3,4,5,6,1.0001) before: +24:00 after: +00:00 DateTime.new(2001,2,3,4,5,6,3r/2) => +36:00 (unchanged) Verified: numeric offset handling matches the C extension across integer, float and rational values and the +/- one-day boundary; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/datetime.rb | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 77628d7c..983db4b8 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -979,12 +979,20 @@ def _str_offset_to_sec(offset) case offset when String self.class.__send__(:_parse_of, offset) - when Rational - (offset * 86400).to_i + when Integer + # Only whole-day offsets of -1, 0, or 1 are valid; anything else is + # ignored (offset 0), matching the C extension. + (-1..1).cover?(offset) ? offset * 86400 : 0 + when Float + # Valid only within +/- one day; out of range is ignored and a + # fractional second is rounded. + sec = offset * 86400 + (sec < -86400 || sec > 86400) ? 0 : sec.round when Numeric + # Rational (and other numerics via to_r) are honored without a range limit. r = offset.to_r raise TypeError, "#{offset.class} can't be used as offset" unless r.is_a?(Rational) - (r * 86400).to_i + (r * 86400).round else raise TypeError, "expected numeric" end From 3c98e0581570b7b0ffb1e6b695e245a4bcbea69b Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 23:25:40 +0900 Subject: [PATCH 053/144] Parse DateTime offset strings via the full zone_to_diff port DateTime's string-offset parser (offset_str_to_sec) was a simplified regexp that handled only Z/UTC/GMT and +HH:MM(:SS)/+HHMM forms. It missed named zones, hour-only forms, three-digit hours, and the out-of-range check, so it disagreed with the C extension. Delegate to sp_zone_to_diff, the existing port of the C extension's date_zone_to_diff (the same routine the C extension uses for offset strings). An unrecognized or out-of-range zone yields 0, which the C extension treats as no offset. offset before after / C ext ---------- ---------- ------------ "+24:00" +24:00 +00:00 "JST" +00:00 +09:00 "PST" +00:00 -08:00 "+09" +00:00 +09:00 "+9" +00:00 +09:00 "+009:00" +00:09 +09:00 "M" +00:00 +12:00 Verified: string-offset handling matches the C extension across numeric forms, named zones, military letters, hour-only forms, and the +/- 24h boundary; numeric offsets remain unaffected; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/core.rb | 19 +++++-------------- 1 file changed, 5 insertions(+), 14 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 3e4dcf30..eb6fd732 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -566,20 +566,11 @@ def new_from_jd(jd, sg, df = nil) # Parse offset string like "+09:00", "-07:30", "Z" to seconds. def offset_str_to_sec(str) - case str - when 'Z', 'z', 'UTC', 'GMT' - 0 - when /\A([+-])(\d{1,2}):?(\d{2})(?::(\d{2}))?\z/ - sign = $1 == '+' ? 1 : -1 - h, m, s = $2.to_i, $3.to_i, ($4 || '0').to_i - sign * (h * 3600 + m * 60 + s) - when /\A([+-])(\d{2})(\d{2})\z/ - sign = $1 == '+' ? 1 : -1 - h, m = $2.to_i, $3.to_i - sign * (h * 3600 + m * 60) - else - 0 - end + # Use the full date_zone_to_diff port so named zones (JST, PST, ...), + # hour-only forms (+09, +9) and the out-of-range check are handled; an + # unrecognized or out-of-range zone yields 0, which the C extension + # treats as no offset. + sp_zone_to_diff(str) || 0 end end From 124117b73ab9139c0fa8c2a7d4768d611a8eb8b9 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 23:35:07 +0900 Subject: [PATCH 054/144] Consolidate DateTime offset handling into _parse_of DateTime.jd / .ordinal / .commercial parsed the offset through _parse_of, which lacked the numeric range checks and non-numeric handling that DateTime.new got in _str_offset_to_sec, so they honored out-of-range or symbol offsets that new rejected. Move the full offset logic (per-type numeric range, string zone lookup, "expected numeric" for other types) into the class method _parse_of, have initialize and new_offset call it, and remove the duplicated _str_offset_to_sec. DateTime.jd(1,2,3,4,-30) before: -720:00 after: +00:00 DateTime.jd(1,2,3,4,:z) before: OK after: expected numeric DateTime.jd(1,2,3,4,100) before: +2400:00 after: +00:00 Verified: offset handling for jd/ordinal/commercial now matches the C extension; initialize/new_offset offset behavior is unchanged; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/datetime.rb | 45 ++++++++++++++++---------------------------- 1 file changed, 16 insertions(+), 29 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 983db4b8..8c1e5922 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -27,7 +27,7 @@ def initialize(year = -4712, month = 1, day = 1, hour = UNSET, minute = UNSET, s # Validate argument types in the C extension's order (offset, then second # down to year) so the same field is reported first when several are bad. - of_sec = _str_offset_to_sec(offset) + of_sec = self.class.__send__(:_parse_of, offset) raise TypeError, "invalid second (not numeric)" unless second.is_a?(Numeric) raise TypeError, "invalid minute (not numeric)" unless minute.is_a?(Numeric) raise TypeError, "invalid hour (not numeric)" unless hour.is_a?(Numeric) @@ -271,7 +271,7 @@ def new_start(start = Date::ITALY) # #=> # # d.new_offset('+09:00') #=> # def new_offset(of = 0) - of_sec = _str_offset_to_sec(of) + of_sec = self.class.__send__(:_parse_of, of) # Keep the same absolute instant, re-expressed in the new offset: shift the # locally stored wall-clock fields by the change in offset. total = @jd * 86400 + @hour * 3600 + @min * 60 + @sec_i + (of_sec - @of) @@ -896,12 +896,22 @@ def _parse_of(offset) case offset when String Date.__send__(:offset_str_to_sec, offset) - when Rational - (offset * 86400).to_i + when Integer + # Only whole-day offsets of -1, 0, or 1 are valid; anything else is + # ignored (offset 0), matching the C extension. + (-1..1).cover?(offset) ? offset * 86400 : 0 + when Float + # Valid only within +/- one day; out of range is ignored and a + # fractional second is rounded. + sec = offset * 86400 + (sec < -86400 || sec > 86400) ? 0 : sec.round when Numeric - (offset * 86400).to_i + # Rational (and other numerics via to_r) are honored without a range limit. + r = offset.to_r + raise TypeError, "#{offset.class} can't be used as offset" unless r.is_a?(Rational) + (r * 86400).round else - 0 + raise TypeError, "expected numeric" end end @@ -975,29 +985,6 @@ def _split_second(second) end end - def _str_offset_to_sec(offset) - case offset - when String - self.class.__send__(:_parse_of, offset) - when Integer - # Only whole-day offsets of -1, 0, or 1 are valid; anything else is - # ignored (offset 0), matching the C extension. - (-1..1).cover?(offset) ? offset * 86400 : 0 - when Float - # Valid only within +/- one day; out of range is ignored and a - # fractional second is rounded. - sec = offset * 86400 - (sec < -86400 || sec > 86400) ? 0 : sec.round - when Numeric - # Rational (and other numerics via to_r) are honored without a range limit. - r = offset.to_r - raise TypeError, "#{offset.class} can't be used as offset" unless r.is_a?(Rational) - (r * 86400).round - else - raise TypeError, "expected numeric" - end - end - def _of2str(of) sign = of < 0 ? '-' : '+' abs = of.abs From 5d90a4f71b070092c2db20ff3ff78a262b2eba0d Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 23:45:15 +0900 Subject: [PATCH 055/144] Validate jd/ordinal/commercial time arguments like the C extension DateTime.jd / .ordinal / .commercial converted their hour/minute/second with Integer(), so they accepted numeric-string time arguments, gave generic type errors, truncated a fractional hour/minute instead of cascading it, and did not reject a fraction followed by a smaller unit. Bring them in line with DateTime.new: type-check each argument as Numeric with the C extension's message and order, reject a trailing fraction (before the date-validity check), and fold a fractional date field or hour/minute into the smaller units. The shared behavior is factored into _check_hms_types, _check_time_fractions and _build_dt_folded. DateTime.jd(1,"2") before: OK after: invalid hour (not numeric) DateTime.jd(1,2.5) before: 02:00 after: 02:30 DateTime.jd(1,1.5,1) before: OK after: invalid fraction DateTime.ordinal(2000,"5") before: OK after: invalid yday (not numeric) DateTime.commercial(2000,"5")before: OK after: invalid cweek (not numeric) Verified: type, fraction, cascade and field-order behavior for all three constructors match the C extension (including the docstring examples and negative-time cascades); full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/datetime.rb | 118 +++++++++++++++++++++++++++++-------------- 1 file changed, 81 insertions(+), 37 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 8c1e5922..3c01b6f1 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -617,35 +617,21 @@ def strptime(string = JULIAN_EPOCH_DATETIME, format = '%FT%T%z', start = Date::I # DateTime.jd(2451945) #=> # # DateTime.jd(Rational('0.5')) # #=> # - def jd(jd = 0, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) - raise TypeError, "no implicit conversion of #{jd.class} into Integer" unless jd.is_a?(Numeric) + def jd(jd = 0, hour = UNSET, minute = UNSET, second = UNSET, offset = 0, start = Date::ITALY) + hour_given = !UNSET.equal?(hour); hour = 0 if UNSET.equal?(hour) + minute_given = !UNSET.equal?(minute); minute = 0 if UNSET.equal?(minute) + second_given = !UNSET.equal?(second); second = 0 if UNSET.equal?(second) + + # Validate in the C extension's order (offset, second, minute, hour, jd). + of_sec = _parse_of(offset) + _check_hms_types(hour, minute, second) + raise TypeError, "invalid jd (not numeric)" unless jd.is_a?(Numeric) + jd_r = jd.to_r jd_i = jd_r.floor - h = Integer(hour) - m = Integer(minute) - of_sec = _parse_of(offset) - if jd_i != jd_r - # Fractional JD: convert fraction to extra seconds and handle overflow - frac_sec = (jd_r - jd_i) * 86400 - second = second.to_r + frac_sec - sec_i, sec_f = _split_sec(second) - if sec_i >= 60 - carry_m, sec_i = sec_i.divmod(60) - m += carry_m - end - if m >= 60 - carry_h, m = m.divmod(60) - h += carry_h - end - if h >= 24 - carry_d, h = h.divmod(24) - jd_i += carry_d - end - else - # Integer JD: pass raw values to _normalize_hms (non-cascading) - sec_i, sec_f = _split_sec(second) - end - _new_dt_from_jd_time(jd_i, h, m, sec_i, sec_f, of_sec, start) + _check_time_fractions(jd_r - jd_i, hour, minute, second, + hour_given, minute_given, second_given) + _build_dt_folded(jd_i, jd_r - jd_i, hour, minute, second, of_sec, start) end # call-seq: @@ -658,12 +644,24 @@ def jd(jd = 0, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY # #=> # # DateTime.ordinal(2001,-332,-20,-55,-54,'+7') # #=> # - def ordinal(year = -4712, yday = 1, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) - jd_v = internal_valid_ordinal?(Integer(year), Integer(yday), start) - raise Date::Error, "invalid date" unless jd_v + def ordinal(year = -4712, yday = 1, hour = UNSET, minute = UNSET, second = UNSET, offset = 0, start = Date::ITALY) + hour_given = !UNSET.equal?(hour); hour = 0 if UNSET.equal?(hour) + minute_given = !UNSET.equal?(minute); minute = 0 if UNSET.equal?(minute) + second_given = !UNSET.equal?(second); second = 0 if UNSET.equal?(second) + + # Validate in the C extension's order (offset, second, minute, hour, yday, year). of_sec = _parse_of(offset) - sec_i, sec_f = _split_sec(second) - _new_dt_from_jd_time(jd_v, Integer(hour), Integer(minute), sec_i, sec_f, of_sec, start) + _check_hms_types(hour, minute, second) + raise TypeError, "invalid yday (not numeric)" unless yday.is_a?(Numeric) + raise TypeError, "invalid year (not numeric)" unless year.is_a?(Numeric) + + yday_r = yday.to_r + yday_i = yday_r.floor + _check_time_fractions(yday_r - yday_i, hour, minute, second, + hour_given, minute_given, second_given) + jd_v = internal_valid_ordinal?(Integer(year), yday_i, start) + raise Date::Error, "invalid date" unless jd_v + _build_dt_folded(jd_v, yday_r - yday_i, hour, minute, second, of_sec, start) end # call-seq: @@ -675,12 +673,26 @@ def ordinal(year = -4712, yday = 1, hour = 0, minute = 0, second = 0, offset = 0 # DateTime.commercial(2002) #=> # # DateTime.commercial(2001,5,6,4,5,6,'+7') # #=> # - def commercial(cwyear = -4712, cweek = 1, cwday = 1, hour = 0, minute = 0, second = 0, offset = 0, start = Date::ITALY) - jd_v = internal_valid_commercial?(Integer(cwyear), Integer(cweek), Integer(cwday), start) - raise Date::Error, "invalid date" unless jd_v + def commercial(cwyear = -4712, cweek = 1, cwday = 1, hour = UNSET, minute = UNSET, second = UNSET, offset = 0, start = Date::ITALY) + hour_given = !UNSET.equal?(hour); hour = 0 if UNSET.equal?(hour) + minute_given = !UNSET.equal?(minute); minute = 0 if UNSET.equal?(minute) + second_given = !UNSET.equal?(second); second = 0 if UNSET.equal?(second) + + # Validate in the C extension's order (offset, second, minute, hour, + # cwday, cweek, cwyear). of_sec = _parse_of(offset) - sec_i, sec_f = _split_sec(second) - _new_dt_from_jd_time(jd_v, Integer(hour), Integer(minute), sec_i, sec_f, of_sec, start) + _check_hms_types(hour, minute, second) + raise TypeError, "invalid cwday (not numeric)" unless cwday.is_a?(Numeric) + raise TypeError, "invalid cweek (not numeric)" unless cweek.is_a?(Numeric) + raise TypeError, "invalid year (not numeric)" unless cwyear.is_a?(Numeric) + + cwday_r = cwday.to_r + cwday_i = cwday_r.floor + _check_time_fractions(cwday_r - cwday_i, hour, minute, second, + hour_given, minute_given, second_given) + jd_v = internal_valid_commercial?(Integer(cwyear), Integer(cweek), cwday_i, start) + raise Date::Error, "invalid date" unless jd_v + _build_dt_folded(jd_v, cwday_r - cwday_i, hour, minute, second, of_sec, start) end # call-seq: @@ -723,6 +735,38 @@ def _normalize_hms(jd, h, m, s) [jd, h, m, s] end + # Type-check the time-of-day arguments shared by jd/ordinal/commercial, in + # the C extension's order (second, then minute, then hour). + def _check_hms_types(hour, minute, second) + raise TypeError, "invalid second (not numeric)" unless second.is_a?(Numeric) + raise TypeError, "invalid minute (not numeric)" unless minute.is_a?(Numeric) + raise TypeError, "invalid hour (not numeric)" unless hour.is_a?(Numeric) + end + + # A fractional date field or hour/minute is only allowed as the last value + # given; if a smaller unit was also supplied, the C extension rejects it. + def _check_time_fractions(date_frac, hour, minute, second, + hour_given, minute_given, second_given) + hr = hour.to_r + mr = minute.to_r + raise Date::Error, "invalid fraction" if date_frac != 0 && (hour_given || minute_given || second_given) + raise Date::Error, "invalid fraction" if (hr - hr.floor) != 0 && (minute_given || second_given) + raise Date::Error, "invalid fraction" if (mr - mr.floor) != 0 && second_given + end + + # Fold the fractional date part and the hour/minute/second into normalized + # time fields (a fraction cascades into the next smaller unit) and build. + def _build_dt_folded(jd_i, date_frac, hour, minute, second, of_sec, start) + hour_r = hour.to_r + date_frac * 24 + h_i = hour_r.floor + minute_r = minute.to_r + (hour_r - h_i) * 60 + m_i = minute_r.floor + second_r = second.to_r + (minute_r - m_i) * 60 + sec_i = second_r.floor + sec_f = second_r - sec_i + _new_dt_from_jd_time(jd_i, h_i, m_i, sec_i, sec_f, of_sec, start) + end + # call-seq: # DateTime.parse(string='-4712-01-01T00:00:00+00:00'[, comp=true[, start=Date::ITALY]], limit: 128) -> datetime # From e3189bcfaa4414b218b8f325dd725a7abb9269ab Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 23:51:48 +0900 Subject: [PATCH 056/144] Coerce iso8601/jisx0301 precision like NUM2INT DateTime#iso8601 and #jisx0301 converted their fractional-digit argument with #to_i, so a String or nil was silently accepted and a Symbol raised NoMethodError, where the C extension raises TypeError. A negative count also produced a stray ".0". Add a _num_to_int helper matching the C extension's NUM2INT: an Integer or any #to_int object (Float, Rational) is accepted, everything else raises TypeError with the right message (including the "from nil to integer" wording). Treat n <= 0 as "no fractional seconds". dt.iso8601("1") before: OK ".5" after: no implicit conversion of String into Integer dt.iso8601(:x) before: NoMethodError after: no implicit conversion of Symbol into Integer dt.iso8601(nil) before: OK after: no implicit conversion from nil to integer dt.iso8601(1.5) => .5 (unchanged) dt.iso8601(-1) before: ".0" after: no fraction Verified: precision-argument handling for iso8601/jisx0301/xmlschema/ rfc3339 matches the C extension across Integer, Float, Rational, negative, String, Symbol and nil; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/datetime.rb | 18 ++++++++++++++---- 1 file changed, 14 insertions(+), 4 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 3c01b6f1..8ecc7a2d 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -308,11 +308,11 @@ def strftime(format = STRFTIME_DATETIME_DEFAULT_FMT) # DateTime.parse('2001-02-03T04:05:06.123456789+07:00').jisx0301(9) # #=> "H13.02.03T04:05:06.123456789+07:00" def jisx0301(n = 0) - n = n.to_i + n = _num_to_int(n) ERA_TABLE.each do |start_jd, era, base_year| if @jd >= start_jd era_year = year - base_year - if n == 0 + if n <= 0 return format('%s%02d.%02d.%02dT%02d:%02d:%02d%s', era, era_year, month, day, hour, min, sec, zone) else @@ -336,8 +336,8 @@ def jisx0301(n = 0) # DateTime.parse('2001-02-03T04:05:06.123456789+07:00').iso8601(9) # #=> "2001-02-03T04:05:06.123456789+07:00" def iso8601(n = 0) - n = n.to_i - if n == 0 + n = _num_to_int(n) + if n <= 0 strftime('%Y-%m-%dT%H:%M:%S%:z') else sf = sec_fraction @@ -977,6 +977,16 @@ def _split_sec(second) private + # Coerce n to an Integer the way the C extension's NUM2INT does: accept an + # Integer or anything with #to_int (e.g. Float, Rational), and otherwise + # raise TypeError rather than falling back to #to_i. + def _num_to_int(n) + return n if Integer === n + return n.to_int if n.respond_to?(:to_int) + raise TypeError, n.nil? ? "no implicit conversion from nil to integer" : + "no implicit conversion of #{n.class} into Integer" + end + def internal_hour @hour end From 20af64043e2808ae626139206464e5d6e6f6f0c3 Mon Sep 17 00:00:00 2001 From: jinroq Date: Wed, 26 Aug 2026 23:59:57 +0900 Subject: [PATCH 057/144] Make DateTime Marshal format byte-compatible with the C extension DateTime#marshal_dump stored the jd/df pair as local time and the sub-second fraction as a Rational, whereas the C extension stores the UTC instant (local time minus the offset) and an integer nanosecond count. Marshalled DateTimes therefore did not round-trip between the C extension and the pure Ruby library: the offset was not restored correctly. Emit jd/df for the UTC instant and scale the fraction to nanoseconds (kept as an Integer when whole), and, on load, shift the UTC jd/df back to local time by the offset. The 2- and 3-element legacy formats are unchanged. Verified: Marshal.dump now produces byte-identical output to the C extension for Date and DateTime, and dumps cross-load correctly in both directions (C dump -> Ruby load and Ruby dump -> C load) including the offset and sub-second fraction; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/datetime.rb | 21 +++++++++++++-------- 1 file changed, 13 insertions(+), 8 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 8ecc7a2d..fdf40dad 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -477,10 +477,13 @@ def hash # :nodoc: def marshal_dump - # 6-element format: [nth, jd, df, sf, of, sg] - df = @hour * 3600 + @min * 60 + @sec_i - sf = (@sec_frac * 1_000_000_000).to_r # nanoseconds as Rational - [0, @jd, df, sf, @of, @start] + # 6-element format: [nth, jd, df, sf, of, sg]. Like the C extension, jd and + # df hold the UTC instant (local time minus the offset), and sf is the + # sub-second part scaled to nanoseconds, kept as an Integer when whole. + jd_carry, df = (@hour * 3600 + @min * 60 + @sec_i - @of).divmod(86400) + sf = @sec_frac * 1_000_000_000 + sf = sf.numerator if sf.denominator == 1 + [0, @jd + jd_carry, df, sf, @of, @start] end # :nodoc: @@ -507,10 +510,12 @@ def marshal_load(array) when 6 _nth, jd, df, sf, of, sg = array sg = normalize_start(sg) - h = df / 3600 - df -= h * 3600 - m = df / 60 - s = df % 60 + # jd/df hold the UTC instant; shift by the offset to recover local time. + jd_carry, local_df = (df + of).divmod(86400) + jd += jd_carry + h = local_df / 3600 + m = (local_df % 3600) / 60 + s = local_df % 60 sf_r = sf.is_a?(Rational) ? (sf / 1_000_000_000) : Rational(sf.to_i, 1_000_000_000) _init_datetime(jd, h, m, s, sf_r, of, sg) else From dd7d755288540396bc90fb30a368972b79da9c12 Mon Sep 17 00:00:00 2001 From: jinroq Date: Fri, 28 Aug 2026 22:46:57 +0900 Subject: [PATCH 058/144] Fix DateTime._strptime/strptime default arguments Both methods defaulted their first argument to JULIAN_EPOCH_DATETIME, a private constant defined on Date. Constant lookup from DateTime's singleton class does not reach a superclass's constants, so calling either method without a string raised NameError instead of the C extension's behavior. Match the C extension: DateTime._strptime requires the string argument (no default), and DateTime.strptime keeps a default but inlines the literal '-4712-01-01T00:00:00+00:00'. The now-unused JULIAN_EPOCH_DATETIME constant is removed. DateTime._strptime() before: NameError after: wrong number of arguments (given 0, expected 1..2) (ArgumentError) DateTime.strptime() before: NameError after: # Verified: default-argument behavior for both methods matches the C extension; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/constants.rb | 6 ------ lib/date/datetime.rb | 4 ++-- 2 files changed, 2 insertions(+), 8 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 8bdaa77b..dbcfe875 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -58,12 +58,6 @@ class Date MONTH_LOWER_STRS = MONTHNAMES.map { |n| n&.downcase&.freeze }.freeze private_constant :DAY_LOWER_STRS, :MONTH_LOWER_STRS - - # Still referenced as a default argument by DateTime._strptime / .strptime, - # whose constant-resolution and defaults are addressed separately (A16). - JULIAN_EPOCH_DATETIME = '-4712-01-01T00:00:00+00:00'.freeze - private_constant :JULIAN_EPOCH_DATETIME - # === Calendar computation (from core.rb) === # Days in month for Gregorian calendar. diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index fdf40dad..03b92b3e 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -578,7 +578,7 @@ def new(*args) # not support specification of flags and width unlike strftime. # # See also strptime(3) and #strftime. - def _strptime(string = JULIAN_EPOCH_DATETIME, format = '%FT%T%z') + def _strptime(string, format = '%FT%T%z') Date._strptime(string, format) end @@ -607,7 +607,7 @@ def _strptime(string = JULIAN_EPOCH_DATETIME, format = '%FT%T%z') # #=> # # # See also strptime(3) and #strftime. - def strptime(string = JULIAN_EPOCH_DATETIME, format = '%FT%T%z', start = Date::ITALY) + def strptime(string = '-4712-01-01T00:00:00+00:00', format = '%FT%T%z', start = Date::ITALY) hash = _strptime(string, format) _dt_new_by_frags(hash, start) end From a336aed995ef12dfa7962a129a45479f0bb47c20 Mon Sep 17 00:00:00 2001 From: jinroq Date: Fri, 28 Aug 2026 22:50:35 +0900 Subject: [PATCH 059/144] Return self from Date/DateTime#marshal_load Both marshal_load methods returned the value of their initializer call (effectively nil to the caller) instead of self, unlike the C extension. Marshal.load itself is unaffected, but a direct marshal_load call now returns the receiver. Add an explicit self after the case in Date#marshal_load and DateTime#marshal_load. Date.allocate.marshal_load(dump) before: nil after: # Verified: marshal_load returns self for both classes as in the C extension; the Marshal round-trip is unchanged; full suite passes (144 tests, 162595 assertions); no -w warnings. --- lib/date/core.rb | 1 + lib/date/datetime.rb | 1 + 2 files changed, 2 insertions(+) diff --git a/lib/date/core.rb b/lib/date/core.rb index eb6fd732..7b0cdb5b 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1465,6 +1465,7 @@ def marshal_load(array) else raise TypeError, "invalid marshal data" end + self end # call-seq: diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 03b92b3e..cfdb4e29 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -521,6 +521,7 @@ def marshal_load(array) else raise TypeError, "invalid marshal data" end + self end # --------------------------------------------------------------------------- From fa8af067082ceadf091a60178509e926f66368ae Mon Sep 17 00:00:00 2001 From: jinroq Date: Fri, 28 Aug 2026 23:06:36 +0900 Subject: [PATCH 060/144] Remove dead _split_sec helper from DateTime The class method _split_sec was only used by the old integer-JD paths of DateTime.jd / .ordinal / .commercial, which were replaced by _build_dt_folded and _check_time_fractions. It now has no call sites (_split_second, used by marshal_load, is a separate method). --- lib/date/datetime.rb | 10 ---------- 1 file changed, 10 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index cfdb4e29..b8c50ff3 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -965,16 +965,6 @@ def _parse_of(offset) end end - def _split_sec(second) - if second.is_a?(Rational) || second.is_a?(Float) - s_r = second.to_r - s_i = s_r.floor - [s_i, s_r - s_i] - else - [Integer(second), 0r] - end - end - end # --------------------------------------------------------------------------- From 8ebc0315a44e83ec54b9aec73dacea6352f841ed Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 29 Aug 2026 00:17:31 +0900 Subject: [PATCH 061/144] Drop fractional day support for Date A Date designates a whole calendar day, so a fractional day component is meaningless for it -- it is even discarded when converting to DateTime. The C extension nonetheless let a Date carry one; I am dropping that. A fractional day supplied as input to a Date is now rejected rather than silently truncated, so that an ambiguous value fails loudly instead of being reinterpreted. - Date#day_fraction always returns Integer 0, and the @day_fraction ivar is removed from Date (dropped from init_from_jd, initialize_copy, new_from_jd, and marshal_dump). Date#ajd is jd - 1/2. - convert_numeric_to_int rejects a non-whole value, and Date#+ / Date#- reject a fractional operand, raising Date::Error "invalid fraction". - DateTime is unchanged: it overrides day_fraction / + / - / ajd and keeps its own fractional support. This is a deliberate, backwards-incompatible spec change, developed test-first: the new expectations were added to the tests and confirmed to fail before the implementation. Updated tests: test_switch_hitter (test_new, test_fractional, incl. boundary and Date#+/#- edge cases), test_date_conv (test_to_date__from_date, test_to_datetime__from_date), test_date_marshal. Performance (C ext vs pure Ruby with YJIT; C baseline 4.0.1_system.tsv): method | C ext (i/s) | Ruby+YJIT (i/s) | ratio ---------------+-------------+-----------------+------ Date.jd | 4,962,001 | 9,614,000 | 194% Date.new | 4,648,499 | 8,176,000 | 176% Date#+ (1) | 5,893,234 | 10,917,000 | 185% Date#- (1) | 3,929,556 | 9,462,000 | 241% Date#- (Date) | 1,875,155 | 5,132,000 | 274% Date#ajd | 7,553,399 | 6,156,000 | 81% (Date#ajd is Rational-allocation bound; this change improves it by removing the former "+ day_fraction". The others improve from dropping @day_fraction handling.) Verified: full suite passes (144 tests, 162614 assertions); no -w warnings; DateTime fractional behavior unchanged. --- lib/date/core.rb | 89 ++++++++++++++------------------- test/date/test_date_conv.rb | 8 +-- test/date/test_date_marshal.rb | 5 +- test/date/test_switch_hitter.rb | 40 +++++++++++---- 4 files changed, 77 insertions(+), 65 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 7b0cdb5b..0621b2d7 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -321,13 +321,18 @@ def _load(s) private # Convert a Numeric argument to an Integer. Rejects non-Numeric input up - # front: a bare Integer() conversion would coerce numeric-looking strings - # such as "0xa", so require a Numeric here and raise TypeError otherwise. + # front (a bare Integer() conversion would coerce numeric-looking strings + # such as "0xa", so require a Numeric here and raise TypeError otherwise), + # and rejects a fractional value: Date designates a whole day, so a + # fractional day is not supported (unlike DateTime). def convert_numeric_to_int(obj, field) + return obj if Integer === obj unless Numeric === obj raise TypeError, "invalid #{field} (not numeric)" end - Integer(obj) + r = obj.to_r + raise Date::Error, "invalid fraction" unless r.denominator == 1 + r.numerator end def civil_fallback(year, month, day, start) @@ -557,10 +562,10 @@ def internal_valid_commercial?(y, w, d, sg) # Internal object factory # --------------------------------------------------------------------------- - # Build a Date from a Julian Day Number (integer part), start, and optional day fraction. - def new_from_jd(jd, sg, df = nil) + # Build a Date from a Julian Day Number and start. + def new_from_jd(jd, sg) obj = allocate - obj.__send__(:init_from_jd, jd, sg, df) + obj.__send__(:init_from_jd, jd, sg) obj end @@ -663,8 +668,8 @@ def start # DateTime.new(2001,2,3,4,5,6,'+7').ajd #=> (11769328217/4800) # DateTime.new(2001,2,2,14,5,6,'-7').ajd #=> (11769328217/4800) def ajd - r = Rational(@jd * 2 - 1, 2) - r + day_fraction + # A Date is at midnight (no day fraction), so ajd is jd - 1/2. + Rational(@jd * 2 - 1, 2) end # call-seq: @@ -769,16 +774,18 @@ def cwyear end # call-seq: - # day_fraction -> rational + # day_fraction -> 0 # - # Returns the fractional part of the day in range (Rational(0, 1)...Rational(1, 1)): + # Returns +0+; a \Date has no fractional day component. + # (DateTime#day_fraction returns the fractional part of the day.) # - # DateTime.new(2001,2,3,12).day_fraction # => (1/2) + # Date.new(2001, 2, 3).day_fraction # => 0 + # DateTime.new(2001, 2, 3, 12).day_fraction # => (1/2) # def day_fraction - # C returns Integer 0 (INT2FIX(0)) for a simple Date without a fraction, - # and a Rational only when a day fraction is present. - @day_fraction || 0 + # Date designates a whole day and has no fractional component, so this is + # always 0 (an Integer). DateTime overrides this with its own value. + 0 end # call-seq: @@ -1059,14 +1066,13 @@ def ===(other) def +(other) case other when Integer - self.class.__send__(:new_from_jd, @jd + other, @start, @day_fraction) + self.class.__send__(:new_from_jd, @jd + other, @start) when Numeric r = other.to_r raise TypeError, "#{other.class} can't be coerced into Integer" unless r.is_a?(Rational) - total = r + day_fraction - days = total.floor - frac = total - days - self.class.__send__(:new_from_jd, @jd + days, @start, frac == 0 ? nil : frac) + # Date designates a whole day, so a fractional number of days is invalid. + raise Date::Error, "invalid fraction" unless r.denominator == 1 + self.class.__send__(:new_from_jd, @jd + r.numerator, @start) else raise TypeError, "expected numeric" end @@ -1094,14 +1100,13 @@ def -(other) when Date Rational(@jd - other.jd) + day_fraction - other.day_fraction when Integer - self.class.__send__(:new_from_jd, @jd - other, @start, @day_fraction) + self.class.__send__(:new_from_jd, @jd - other, @start) when Numeric r = other.to_r raise TypeError, "#{other.class} can't be coerced into Integer" unless r.is_a?(Rational) - total = day_fraction - r - days = total.floor - frac = total - days - self.class.__send__(:new_from_jd, @jd + days, @start, frac == 0 ? nil : frac) + # Date designates a whole day, so a fractional number of days is invalid. + raise Date::Error, "invalid fraction" unless r.denominator == 1 + self.class.__send__(:new_from_jd, @jd - r.numerator, @start) else raise TypeError, "expected numeric" end @@ -1416,7 +1421,6 @@ def initialize_copy(other) # as freshly constructed instances (see init_from_jd). @jd = other.instance_variable_get(:@jd) @start = other.instance_variable_get(:@start) - @day_fraction = other.instance_variable_get(:@day_fraction) @year = other.instance_variable_get(:@year) @month = other.instance_variable_get(:@month) @day = other.instance_variable_get(:@day) @@ -1424,16 +1428,9 @@ def initialize_copy(other) # :nodoc: def marshal_dump - # 6-element format: [nth, jd, df, sf, of, sg] - # df = seconds into day (Integer), sf = sub-second fraction (Rational) - if @day_fraction - total_sec = @day_fraction * 86400 - df_int = total_sec.floor - sf = total_sec - df_int - [0, @jd, df_int, sf, 0, @start] - else - [0, @jd, 0, 0, 0, @start] - end + # 6-element format: [nth, jd, df, sf, of, sg]. A Date has no day fraction, + # so df and sf are always 0. + [0, @jd, 0, 0, 0, @start] end # :nodoc: @@ -1445,23 +1442,14 @@ def marshal_load(array) sg = sg_or_bool == true ? GREGORIAN : (sg_or_bool == false ? JULIAN : sg_or_bool.to_f) init_from_jd(jd_like.to_i, sg) when 3 - # Format 1.8: [ajd, of, sg] + # Format 1.8: [ajd, of, sg]. A Date has no fraction, so take the whole day. ajd, _of, sg = array sg = normalize_start(sg) - raw_jd = ajd + 0.5r - jd = raw_jd.floor - df = raw_jd - jd - init_from_jd(jd, sg, df == 0 ? nil : df) + init_from_jd((ajd + 0.5r).floor, sg) when 6 - # Current format: [nth, jd, df, sf, of, sg] - _nth, jd, df, sf, _of, sg = array - sg = normalize_start(sg) - if df != 0 || sf != 0 - day_frac = (Rational(df) + sf) / 86400 - init_from_jd(jd, sg, day_frac) - else - init_from_jd(jd, sg) - end + # Current format: [nth, jd, df, sf, of, sg]; a Date ignores df/sf. + _nth, jd, _df, _sf, _of, sg = array + init_from_jd(jd, normalize_start(sg)) else raise TypeError, "invalid marshal data" end @@ -1722,13 +1710,12 @@ def normalize_start(sg) sg.is_a?(Infinity) ? sg.to_f : sg end - def init_from_jd(jd, sg, df = nil) + def init_from_jd(jd, sg) @jd = jd # Store the cutover as a Float. Keeps #start, #hash and marshal output # consistent regardless of whether the caller passed an Integer (e.g. ITALY) # or a Float sentinel. @start = sg.to_f - @day_fraction = df # Initialize the lazily-computed civil ivars up front so every Date # instance shares a single object shape regardless of which accessors # are called. (yday/cweek/cwyear are not cached; see #yday/#cweek.) diff --git a/test/date/test_date_conv.rb b/test/date/test_date_conv.rb index 8d810844..b6b59304 100644 --- a/test/date/test_date_conv.rb +++ b/test/date/test_date_conv.rb @@ -111,10 +111,12 @@ def test_to_date__from_time end def test_to_date__from_date - d = Date.new(2004, 9, 19) + 1.to_r/2 + d = Date.new(2004, 9, 19) d2 = d.to_date - assert_equal([2004, 9, 19, 1.to_r/2], + assert_equal([2004, 9, 19, 0], [d2.year, d2.mon, d2.mday, d2.day_fraction]) + # Date no longer supports a fractional day. + assert_raise(Date::Error) { Date.new(2004, 9, 19) + 1.to_r/2 } end def test_to_date__from_datetime @@ -159,7 +161,7 @@ def test_to_datetime__from_time end def test_to_datetime__from_date - d = Date.new(2004, 9, 19) + 1.to_r/2 + d = Date.new(2004, 9, 19) d2 = d.to_datetime assert_equal([2004, 9, 19, 0, 0, 0, 0, 0], [d2.year, d2.mon, d2.mday, d2.hour, d2.min, d2.sec, diff --git a/test/date/test_date_marshal.rb b/test/date/test_date_marshal.rb index fa8b2d91..c330a097 100644 --- a/test/date/test_date_marshal.rb +++ b/test/date/test_date_marshal.rb @@ -40,12 +40,15 @@ def test_marshal expected_error = defined?(FrozenError) ? FrozenError : RuntimeError assert_raise(expected_error){d.marshal_load(a)} - d = Date.new + 1/2r + 2304/65437r/86400 + d = Date.new(2001, 2, 3) m = Marshal.dump(d) d2 = Marshal.load(m) assert_equal(d, d2) assert_equal(d.start, d2.start) assert_instance_of(String, d2.to_s) + + # Date no longer supports a fractional day. + assert_raise(Date::Error) { Date.new + 1/2r } end def test_memsize diff --git a/test/date/test_switch_hitter.rb b/test/date/test_switch_hitter.rb index cc757825..6ef4172e 100644 --- a/test/date/test_switch_hitter.rb +++ b/test/date/test_switch_hitter.rb @@ -23,8 +23,8 @@ def test_new d = Date.new(2001, 2, 3) assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) - d = Date.new(2001, 2, Rational('3.5')) - assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) + # Date no longer supports a fractional day (only DateTime does). + assert_raise(Date::Error) { Date.new(2001, 2, Rational('3.5')) } d = Date.new(2001,2, 3, Date::JULIAN) assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) d = Date.new(2001,2, 3, Date::GREGORIAN) @@ -187,33 +187,53 @@ def test_commercial end def test_fractional + # Date designates a whole day: a whole-valued jd (Integer, or Float/Rational + # with no fraction) is accepted; a fractional jd raises Date::Error. d = Date.jd(2451944.0) assert_equal(2451944, d.jd) d = Date.jd(Rational(2451944)) assert_equal(2451944, d.jd) - d = Date.jd(2451944.5) - assert_equal(2451944, d.jd) - d = Date.jd(Rational('2451944.5')) - assert_equal(2451944, d.jd) + assert_raise(Date::Error) { Date.jd(2451944.5) } + assert_raise(Date::Error) { Date.jd(Rational('2451944.5')) } d = Date.civil(2001, 2, 3.0) assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) d = Date.civil(2001, 2, Rational(3)) assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) - d = Date.civil(2001, 2, 3.5) - assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) - d = Date.civil(2001, 2, Rational('3.5')) - assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) + assert_raise(Date::Error) { Date.civil(2001, 2, 3.5) } + assert_raise(Date::Error) { Date.civil(2001, 2, Rational('3.5')) } d = Date.ordinal(2001, 2.0) assert_equal([2001, 2], [d.year, d.yday]) d = Date.ordinal(2001, Rational(2)) assert_equal([2001, 2], [d.year, d.yday]) + assert_raise(Date::Error) { Date.ordinal(2001, 2.5) } + assert_raise(Date::Error) { Date.ordinal(2001, Rational('2.5')) } d = Date.commercial(2001, 2, 3.0) assert_equal([2001, 2, 3], [d.cwyear, d.cweek, d.cwday]) d = Date.commercial(2001, 2, Rational(3)) assert_equal([2001, 2, 3], [d.cwyear, d.cweek, d.cwday]) + assert_raise(Date::Error) { Date.commercial(2001, 2, 3.5) } + assert_raise(Date::Error) { Date.commercial(2001, 2, Rational('3.5')) } + + # Date#day_fraction is always Integer 0, and #ajd is jd - 1/2. + d = Date.new(2001, 2, 3) + assert_equal(0, d.day_fraction) + assert_instance_of(Integer, d.day_fraction) + assert_equal(4903887r/2, d.ajd) + + # Date arithmetic accepts a whole number of days and rejects a fraction. + assert_equal(Date.new(2001, 2, 5), d + 2) + assert_equal(Date.new(2001, 2, 5), d + 2.0) + assert_equal(Date.new(2001, 2, 5), d + Rational(2)) + assert_equal(Date.new(2001, 2, 1), d - 2) + assert_equal(33r, Date.new(2001, 2, 3) - Date.new(2001, 1, 1)) + assert_raise(Date::Error) { d + Rational(1, 2) } + assert_raise(Date::Error) { d + Rational(3, 2) } + assert_raise(Date::Error) { d + 0.5 } + assert_raise(Date::Error) { d - Rational(1, 2) } + assert_raise(Date::Error) { d - 0.5 } d = DateTime.jd(2451944.0) assert_equal(2451944, d.jd) From ffacbcdea1a8d3f0683afa5d26e6a3ac82b4c695 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 29 Aug 2026 16:13:37 +0900 Subject: [PATCH 062/144] Rename Date#init_from_jd to #initialize and cache known civil fields Date.new/Date.civil computed the Julian Day from year/month/day and then threw those fields away, forcing #year/#month/#day to recompute them from the jd on first access. The private initializer now accepts the civil fields and caches them when the caller already knows them (the fast path in Date.civil, where month is 1..12 and day is 1..28, passes the final values directly); when unknown they stay nil and are computed lazily as before. All three are always assigned, so the object shape is unchanged. - init_from_jd is renamed to the idiomatic #initialize (Date.new is aliased to civil, so Class#new never reaches it); new_from_jd, Date.jd and Date#marshal_load call it. - initialize_copy stays an explicit ivar copy rather than delegating to #initialize: DateTime overrides #initialize with an incompatible (year, month, day, ...) signature, so a shared initialize_copy must not dispatch through it. A comment records why. Performance (C ext vs pure Ruby with YJIT; C baseline 4.0.1_system.tsv): method | C ext (i/s) | Ruby+YJIT (i/s) | ratio -------------+-------------+-----------------+------ Date.civil | 4,648,499 | 7,266,000 | 156% Date.jd | 4,962,001 | 9,599,000 | 193% Date#year | 20,235,536 | 29,737,000 | 147% Date#month | 20,625,632 | 29,753,000 | 144% Date#day | 18,362,006 | 29,866,000 | 163% Verified: full suite passes (144 tests, 162614 assertions); no -w warnings; object shape and DateTime dup/marshal behavior unchanged. --- lib/date/core.rb | 46 +++++++++++++++++++++++++++----------------- lib/date/datetime.rb | 2 +- 2 files changed, 29 insertions(+), 19 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 0621b2d7..d8f18dc1 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -25,10 +25,12 @@ def civil(year = -4712, month = 1, day = 1, start = ITALY) a = yy / 100 gjd = gjd_base - 1524 + 2 - a + a / 4 if gjd >= start - return new_from_jd(gjd, start) + # month/day are in the 1..12 / 1..28 fast-path range, so year, month + # and day are already the final civil fields; cache them directly. + return new_from_jd(gjd, start, year, month, day) else jjd = gjd_base - 1524 - return new_from_jd(jjd, start) if jjd < start + return new_from_jd(jjd, start, year, month, day) if jjd < start # gjd < start <= jjd: date falls in the reform gap; fall through to # civil_fallback, which raises "invalid date". end @@ -105,7 +107,7 @@ def valid_civil?(year, month, day, start = ITALY) def jd(jd = 0, start = ITALY) jd = convert_numeric_to_int(jd, "jd") obj = allocate - obj.__send__(:init_from_jd, jd, start) + obj.__send__(:initialize, jd, start) obj end @@ -562,10 +564,12 @@ def internal_valid_commercial?(y, w, d, sg) # Internal object factory # --------------------------------------------------------------------------- - # Build a Date from a Julian Day Number and start. - def new_from_jd(jd, sg) + # Build a Date from a Julian Day Number and start. When the civil fields + # are already known (e.g. the Date.new fast path), pass them so the new + # instance can cache them instead of recomputing from the Julian Day. + def new_from_jd(jd, sg, year = nil, month = nil, day = nil) obj = allocate - obj.__send__(:init_from_jd, jd, sg) + obj.__send__(:initialize, jd, sg, year, month, day) obj end @@ -847,7 +851,7 @@ def new_start(start = ITALY) obj = self.class.allocate obj.instance_variable_set(:@jd, @jd) # Store the cutover as a Float so #start/#hash/marshal stay consistent - # (see init_from_jd). + # (see #initialize). obj.instance_variable_set(:@start, start.to_f) obj end @@ -1418,7 +1422,10 @@ def to_time # :nodoc: def initialize_copy(other) # Assign every ivar in the canonical order so copies share the same shape - # as freshly constructed instances (see init_from_jd). + # as freshly constructed instances (see #initialize). This stays an explicit + # copy rather than delegating to #initialize: DateTime overrides #initialize + # with an incompatible (year, month, day, ...) signature, so a shared + # initialize_copy must not dispatch through it. @jd = other.instance_variable_get(:@jd) @start = other.instance_variable_get(:@start) @year = other.instance_variable_get(:@year) @@ -1440,16 +1447,16 @@ def marshal_load(array) # Format 1.4/1.6: [jd_like, sg_or_bool] jd_like, sg_or_bool = array sg = sg_or_bool == true ? GREGORIAN : (sg_or_bool == false ? JULIAN : sg_or_bool.to_f) - init_from_jd(jd_like.to_i, sg) + initialize(jd_like.to_i, sg) when 3 # Format 1.8: [ajd, of, sg]. A Date has no fraction, so take the whole day. ajd, _of, sg = array sg = normalize_start(sg) - init_from_jd((ajd + 0.5r).floor, sg) + initialize((ajd + 0.5r).floor, sg) when 6 # Current format: [nth, jd, df, sf, of, sg]; a Date ignores df/sf. _nth, jd, _df, _sf, _of, sg = array - init_from_jd(jd, normalize_start(sg)) + initialize(jd, normalize_start(sg)) else raise TypeError, "invalid marshal data" end @@ -1710,18 +1717,21 @@ def normalize_start(sg) sg.is_a?(Infinity) ? sg.to_f : sg end - def init_from_jd(jd, sg) + def initialize(jd, sg, year = nil, month = nil, day = nil) @jd = jd # Store the cutover as a Float. Keeps #start, #hash and marshal output # consistent regardless of whether the caller passed an Integer (e.g. ITALY) # or a Float sentinel. @start = sg.to_f - # Initialize the lazily-computed civil ivars up front so every Date - # instance shares a single object shape regardless of which accessors - # are called. (yday/cweek/cwyear are not cached; see #yday/#cweek.) - @year = nil - @month = nil - @day = nil + # Cache the civil fields when the caller already knows them (Date.new via + # the fast path passes them), so #year/#month/#day need not recompute them. + # When unknown they stay nil and are computed lazily by #internal_civil. + # Every instance assigns all three here, so the object shape is stable + # regardless of which path constructed it. (yday/cweek/cwyear are not + # cached; see #yday/#cweek.) + @year = year + @month = month + @day = day end def internal_civil diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index b8c50ff3..7bdfa6bc 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -1010,7 +1010,7 @@ def zone_str def _init_datetime(jd, h, m, s, sf, of, sg) @jd = jd # Store the cutover as a Float so #start/#hash/marshal stay consistent - # (see init_from_jd). + # (see Date#initialize). @start = sg.to_f @day_fraction = nil @hour = h From b206d5eb4c9df6236f9669994a75c030d96c71eb Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 29 Aug 2026 16:41:22 +0900 Subject: [PATCH 063/144] Split Date/DateTime strftime time parts into overridable methods The strftime fast paths tested instance_of?(Date) on every call to decide whether to emit a zero time ("00:00:00", "+0000", ...) or the real time. Replace those six runtime type checks with small overridable helpers: Date returns the fixed strings, DateTime overrides them to render its actual time and offset. This removes the type branching from the formatter and lets each class supply its own rendering. - Date gains strftime_hms (%T/%X/%H:%M:%S), strftime_hm (%R), strftime_r12 (%r) and strftime_zoff (%z), each returning a fixed literal; DateTime overrides all four. - internal_strftime, fast_spec and fmt_asctime_str call these helpers instead of branching on instance_of?(Date). fast_spec's %z branch now also uses strftime_zoff, removing a duplicated offset computation. Behavior is unchanged: output is byte-identical to the previous implementation across all 3520 Date+DateTime cases (every specifier x flag combination), so no test changes are needed. Performance (C ext vs pure Ruby with YJIT; C baseline 4.0.1_system.tsv): format | C ext (i/s) | Ruby+YJIT (i/s) | ratio ----------------------+-------------+-----------------+------ strftime (%F default) | 2,863,407 | 7,218,000 | 252% strftime(%c) | 2,041,798 | 1,290,000 | 63% strftime(composite) | 1,671,367 | 1,878,000 | 112% (%c is a pre-existing sub-parity format -- the Ruby asctime path was already ~68% of C before this change; the polymorphic dispatch keeps it essentially unchanged. %T, %r and the composite format are held at or above their prior levels.) Verified: full suite passes (144 tests, 162614 assertions); no -w warnings. --- lib/date/datetime.rb | 23 ++++++++++++++++++ lib/date/strftime.rb | 56 +++++++++++++++++++++++--------------------- 2 files changed, 52 insertions(+), 27 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 7bdfa6bc..dad18f51 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -1007,6 +1007,29 @@ def zone_str _of2str(@of) end + # Overrides of the Date strftime time-part helpers (see Date#strftime_hms): + # a DateTime renders its actual time instead of the Date literals. + def strftime_hms + "#{PAD2[@hour]}:#{PAD2[@min]}:#{PAD2[@sec_i]}" + end + + def strftime_hm + "#{PAD2[@hour]}:#{PAD2[@min]}" + end + + def strftime_r12 + h = @hour % 12 + h = 12 if h == 0 + "#{PAD2[h]}:#{PAD2[@min]}:#{PAD2[@sec_i]} #{@hour < 12 ? 'AM' : 'PM'}" + end + + def strftime_zoff + of = @of + sign = of < 0 ? '-' : '+' + abs = of.abs + "#{sign}#{PAD2[abs / 3600]}#{PAD2[(abs % 3600) / 60]}" + end + def _init_datetime(jd, h, m, s, sf, of, sg) @jd = jd # Store the cutover as a Float so #start/#hash/marshal stay consistent diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index babca830..665c73db 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -54,20 +54,15 @@ def internal_strftime(fmt) internal_civil unless @year return fast_ymd when '%H:%M:%S', '%T', '%X' - return instance_of?(Date) ? +'00:00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}" + # +: this becomes the result string, which #strftime force_encodes in + # place, so it must be mutable (strftime_hms may be a frozen literal). + return +strftime_hms when '%m/%d/%y', '%D', '%x' internal_civil unless @year return "#{PAD2[@month]}/#{PAD2[@day]}/#{PAD2[@year % 100]}" when '%Y-%m-%dT%H:%M:%S%z' internal_civil unless @year - if instance_of?(Date) - return fast_ymd << 'T00:00:00+0000' - else - of = of_seconds - sign = of < 0 ? '-' : '+' - abs = of.abs - return "#{fast_ymd}T#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}#{sign}#{PAD2[abs / 3600]}#{PAD2[(abs % 3600) / 60]}" - end + return "#{fast_ymd}T#{strftime_hms}#{strftime_zoff}" when '%a %b %e %H:%M:%S %Y', '%c' internal_civil unless @year return fmt_asctime_str @@ -199,11 +194,7 @@ def fmt_asctime_str d_s = d < 10 ? " #{d}" : d.to_s y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) - if instance_of?(Date) - "#{ASCTIME_PREFIX[w][@month]}#{d_s} 00:00:00 #{y_s}" - else - "#{ASCTIME_PREFIX[w][@month]}#{d_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} #{y_s}" - end + "#{ASCTIME_PREFIX[w][@month]}#{d_s} #{strftime_hms} #{y_s}" end # Inline fast path for common specs with default formatting (no flags/width) @@ -274,10 +265,7 @@ def fast_spec(spec) when 90 # 'Z' zone_str when 122 # 'z' - of = of_seconds - sign = of < 0 ? '-' : '+' - abs = of.abs - "#{sign}#{PAD2[abs / 3600]}#{PAD2[(abs % 3600) / 60]}" + strftime_zoff when 115 # 's' ((@jd - 2440588) * 86400 - of_seconds + internal_hour * 3600 + internal_min * 60 + internal_sec).to_s # Composite specs — inline expansion @@ -288,20 +276,14 @@ def fast_spec(spec) internal_civil unless @year fast_ymd when 84, 88 # 'T', 'X' - instance_of?(Date) ? '00:00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]}" + strftime_hms when 68, 120 # 'D', 'x' internal_civil unless @year "#{PAD2[@month]}/#{PAD2[@day]}/#{PAD2[@year % 100]}" when 82 # 'R' - instance_of?(Date) ? '00:00' : "#{PAD2[internal_hour]}:#{PAD2[internal_min]}" + strftime_hm when 114 # 'r' - if instance_of?(Date) - '12:00:00 AM' - else - h = internal_hour % 12 - h = 12 if h == 0 - "#{PAD2[h]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} #{internal_hour < 12 ? 'AM' : 'PM'}" - end + strftime_r12 else nil # fall through to format_spec_b end @@ -575,4 +557,24 @@ def zone_str '+00:00' end + # Time-component strings for the strftime fast paths. A Date has no time, so + # each is a fixed literal here; DateTime overrides them with the computed + # values. Keeping them as (overridable) methods lets each class supply its + # own without a per-call instance_of? test inside the formatter. + def strftime_hms # %T, %X, %H:%M:%S + '00:00:00' + end + + def strftime_hm # %R + '00:00' + end + + def strftime_r12 # %r + '12:00:00 AM' + end + + def strftime_zoff # %z (numeric +HHMM offset) + '+0000' + end + end From d44f6c0bbe1c6a8f3ab0940dc5529a12e2110602 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 29 Aug 2026 17:06:53 +0900 Subject: [PATCH 064/144] Rename DateTime second ivars and expose time fields with attr_reader The internal names @sec_i and @sec_frac did not match the public accessors they back, so I am aligning them: @sec_i becomes @sec and @sec_frac becomes @sec_fraction, matching #sec and #sec_fraction. With the ivars named after the accessors, hour/min/sec/sec_fraction reduce to attr_reader declarations instead of hand-written one-line readers; the call-seq documentation and the minute/second/second_fraction aliases are kept. The internal strftime helpers (internal_sec, sec_frac) keep their method names -- they are defined on Date and overridden by DateTime -- and only their ivar references change. This is a pure rename: no behavior changes. The full suite passes (144 tests, 162614 assertions) with no -w warnings, and object shape and memsize stay stable across dup and marshal round-trips. This change touches DateTime only, which is deprecated and exempt from performance measurement in this project, so no benchmark comparison is included. --- lib/date/datetime.rb | 68 +++++++++++++++++++------------------------- 1 file changed, 30 insertions(+), 38 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index dad18f51..d2d0a10b 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -81,9 +81,7 @@ def initialize(year = -4712, month = 1, day = 1, hour = UNSET, minute = UNSET, s # Returns the hour in range (0..23): # # DateTime.new(2001, 2, 3, 4, 5, 6).hour # => 4 - def hour - @hour - end + attr_reader :hour # call-seq: # min -> integer @@ -91,9 +89,7 @@ def hour # Returns the minute in range (0..59): # # DateTime.new(2001, 2, 3, 4, 5, 6).min # => 5 - def min - @min - end + attr_reader :min alias minute min # call-seq: @@ -102,9 +98,7 @@ def min # Returns the second in range (0..59): # # DateTime.new(2001, 2, 3, 4, 5, 6).sec # => 6 - def sec - @sec_i - end + attr_reader :sec alias second sec # call-seq: @@ -114,9 +108,7 @@ def sec # (Rational(0, 1)...Rational(1, 1)): # # DateTime.new(2001, 2, 3, 4, 5, 6.5).sec_fraction # => (1/2) - def sec_fraction - @sec_frac - end + attr_reader :sec_fraction alias second_fraction sec_fraction # call-seq: @@ -146,8 +138,8 @@ def zone # # DateTime.new(2001,2,3,12).day_fraction # => (1/2) def day_fraction - Rational(@hour * 3600 + @min * 60 + @sec_i, 86400) + - Rational(@sec_frac.numerator, @sec_frac.denominator * 86400) + Rational(@hour * 3600 + @min * 60 + @sec, 86400) + + Rational(@sec_fraction.numerator, @sec_fraction.denominator * 86400) end # call-seq: @@ -160,8 +152,8 @@ def day_fraction # DateTime.new(2001,2,2,14,5,6,'-7').ajd #=> (11769328217/4800) def ajd jd_r = Rational(@jd) - time_r = Rational(@hour * 3600 + @min * 60 + @sec_i, 86400) + - Rational(@sec_frac.numerator, @sec_frac.denominator * 86400) + time_r = Rational(@hour * 3600 + @min * 60 + @sec, 86400) + + Rational(@sec_fraction.numerator, @sec_fraction.denominator * 86400) of_r = Rational(@of, 86400) jd_r + time_r - of_r - 0.5r end @@ -187,17 +179,17 @@ def ajd def +(other) case other when Integer - self.class.__send__(:_new_dt_from_jd_time,@jd + other, @hour, @min, @sec_i, @sec_frac, @of, @start) + self.class.__send__(:_new_dt_from_jd_time,@jd + other, @hour, @min, @sec, @sec_fraction, @of, @start) when Rational, Float # other is days (may be fractional) - add as seconds extra_sec = other.to_r * 86400 - total_r = Rational(@jd) * 86400 + @hour * 3600 + @min * 60 + @sec_i + @sec_frac + extra_sec + total_r = Rational(@jd) * 86400 + @hour * 3600 + @min * 60 + @sec + @sec_fraction + extra_sec _from_total_sec_r(total_r) when Numeric r = other.to_r raise TypeError, "#{other.class} can't be coerced into Integer" unless r.is_a?(Rational) extra_sec = r * 86400 - total_r = Rational(@jd) * 86400 + @hour * 3600 + @min * 60 + @sec_i + @sec_frac + extra_sec + total_r = Rational(@jd) * 86400 + @hour * 3600 + @min * 60 + @sec + @sec_fraction + extra_sec _from_total_sec_r(total_r) else raise TypeError, "expected numeric" @@ -226,7 +218,7 @@ def -(other) when Date ajd - other.ajd when Integer - self.class.__send__(:_new_dt_from_jd_time,@jd - other, @hour, @min, @sec_i, @sec_frac, @of, @start) + self.class.__send__(:_new_dt_from_jd_time,@jd - other, @hour, @min, @sec, @sec_fraction, @of, @start) when Rational, Float self + (-other) when Numeric @@ -244,7 +236,7 @@ def -(other) # Returns a new DateTime object representing the time +n+ months later; # the time of day and offset are preserved. (Date#<< delegates to this.) def >>(n) - self.class.__send__(:_new_dt_from_jd_time, month_shifted_jd(n), @hour, @min, @sec_i, @sec_frac, @of, @start) + self.class.__send__(:_new_dt_from_jd_time, month_shifted_jd(n), @hour, @min, @sec, @sec_fraction, @of, @start) end # call-seq: @@ -259,7 +251,7 @@ def >>(n) # # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. def new_start(start = Date::ITALY) - self.class.__send__(:_new_dt_from_jd_time, @jd, @hour, @min, @sec_i, @sec_frac, @of, start) + self.class.__send__(:_new_dt_from_jd_time, @jd, @hour, @min, @sec, @sec_fraction, @of, start) end # call-seq: @@ -274,11 +266,11 @@ def new_offset(of = 0) of_sec = self.class.__send__(:_parse_of, of) # Keep the same absolute instant, re-expressed in the new offset: shift the # locally stored wall-clock fields by the change in offset. - total = @jd * 86400 + @hour * 3600 + @min * 60 + @sec_i + (of_sec - @of) + total = @jd * 86400 + @hour * 3600 + @min * 60 + @sec + (of_sec - @of) jd2, rem = total.divmod(86400) h, rem = rem.divmod(3600) m, s = rem.divmod(60) - self.class.__send__(:_new_dt_from_jd_time, jd2, h, m, s, @sec_frac, of_sec, @start) + self.class.__send__(:_new_dt_from_jd_time, jd2, h, m, s, @sec_fraction, of_sec, @start) end # --------------------------------------------------------------------------- @@ -455,19 +447,19 @@ def to_s # The Julian Day number and seconds are given in UTC; the offset and start # (cutover) follow. def inspect - utc_total = @jd * 86400 + @hour * 3600 + @min * 60 + @sec_i - @of + utc_total = @jd * 86400 + @hour * 3600 + @min * 60 + @sec - @of utc_jd, utc_sec = utc_total.divmod(86400) - nano = @sec_frac * 1_000_000_000 + nano = @sec_fraction * 1_000_000_000 nano_s = nano.denominator == 1 ? nano.numerator.to_s : "(#{nano.numerator}/#{nano.denominator})" of_s = @of < 0 ? "-#{-@of}" : "+#{@of}" "#" end def hash - if @hour == 0 && @min == 0 && @sec_i == 0 + if @hour == 0 && @min == 0 && @sec == 0 [@jd, @start].hash else - [@jd, @hour, @min, @sec_i, @start].hash + [@jd, @hour, @min, @sec, @start].hash end end @@ -480,8 +472,8 @@ def marshal_dump # 6-element format: [nth, jd, df, sf, of, sg]. Like the C extension, jd and # df hold the UTC instant (local time minus the offset), and sf is the # sub-second part scaled to nanoseconds, kept as an Integer when whole. - jd_carry, df = (@hour * 3600 + @min * 60 + @sec_i - @of).divmod(86400) - sf = @sec_frac * 1_000_000_000 + jd_carry, df = (@hour * 3600 + @min * 60 + @sec - @of).divmod(86400) + sf = @sec_fraction * 1_000_000_000 sf = sf.numerator if sf.denominator == 1 [0, @jd + jd_carry, df, sf, @of, @start] end @@ -551,9 +543,9 @@ def to_datetime def to_time y, m, d = self.class.__send__(:jd_to_gregorian, @jd) if @of == 0 - Time.utc(y, m, d, @hour, @min, @sec_i + @sec_frac) + Time.utc(y, m, d, @hour, @min, @sec + @sec_fraction) else - Time.new(y, m, d, @hour, @min, @sec_i + @sec_frac, @of) + Time.new(y, m, d, @hour, @min, @sec + @sec_fraction, @of) end end @@ -992,11 +984,11 @@ def internal_min end def internal_sec - @sec_i + @sec end def sec_frac - @sec_frac + @sec_fraction end def of_seconds @@ -1010,7 +1002,7 @@ def zone_str # Overrides of the Date strftime time-part helpers (see Date#strftime_hms): # a DateTime renders its actual time instead of the Date literals. def strftime_hms - "#{PAD2[@hour]}:#{PAD2[@min]}:#{PAD2[@sec_i]}" + "#{PAD2[@hour]}:#{PAD2[@min]}:#{PAD2[@sec]}" end def strftime_hm @@ -1020,7 +1012,7 @@ def strftime_hm def strftime_r12 h = @hour % 12 h = 12 if h == 0 - "#{PAD2[h]}:#{PAD2[@min]}:#{PAD2[@sec_i]} #{@hour < 12 ? 'AM' : 'PM'}" + "#{PAD2[h]}:#{PAD2[@min]}:#{PAD2[@sec]} #{@hour < 12 ? 'AM' : 'PM'}" end def strftime_zoff @@ -1038,8 +1030,8 @@ def _init_datetime(jd, h, m, s, sf, of, sg) @day_fraction = nil @hour = h @min = m - @sec_i = s - @sec_frac = sf.is_a?(Rational) ? sf : Rational(sf) + @sec = s + @sec_fraction = sf.is_a?(Rational) ? sf : Rational(sf) @of = of.to_i # Initialize lazily-computed (inherited from Date) civil ivars up front so # every DateTime instance shares a single object shape. From 17db8035f3fff4c966acdd9045e585b5bdf16059 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 29 Aug 2026 17:24:30 +0900 Subject: [PATCH 065/144] Fold strftime '+' specifier into the composite expansion table format_spec_b handled '%+' with a dedicated `when 43` branch that expanded it to '%a %b %e %H:%M:%S %Z %Y' and then applied fmt_str -- byte for byte the same work the trailing `else` branch already does for every entry in STRFTIME_COMPOSITE_BYTE. Rather than keep the one-off branch, I am moving '+' into that table (43 => '%a %b %e %H:%M:%S %Z %Y') so the generic composite path formats it. fast_spec returns nil for byte 43, so the dispatch route is unchanged; only the special case disappears. Behavior is unchanged: output is byte-identical to the previous implementation across every '%+' variant (all flag and width combinations, combined with other specifiers, for both Date and DateTime, including negative years and assorted offsets), so no test changes are needed. Performance (Date#strftime, YJIT; C ext baseline 4.0.1_system.tsv): format | before (this branch HEAD) | after | C ext analog -------+---------------------------+---------+---------------------- %+ | 109,971/s | 110,029/s | (no C %+ baseline) %c | 1,485,000/s | 1,490,000/s | %c C ext 2,041,798/s ('%+' has no row in the C benchmark set; the nearest analog is the asctime-style '%c' composite. The change is dispatch-only, so both formats stay at their prior throughput -- differences are within noise.) Verified: full suite passes (144 tests, 162614 assertions); no -w warnings. --- lib/date/constants.rb | 1 + lib/date/strftime.rb | 5 +---- 2 files changed, 2 insertions(+), 4 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index dbcfe875..0d7d5b51 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -122,6 +122,7 @@ class Date # Map composite spec bytes to their expansion strings STRFTIME_COMPOSITE_BYTE = { + 43 => '%a %b %e %H:%M:%S %Z %Y', # '+' 99 => '%a %b %e %H:%M:%S %Y', # 'c' 68 => '%m/%d/%y', # 'D' 70 => '%Y-%m-%d', # 'F' diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 665c73db..3614cbc5 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -371,11 +371,8 @@ def format_spec_b(spec, flags, colons, width) pad_num(cweek, width || 2, flags, zero: true) when 37 # '%' fmt_str('%', width, flags) - when 43 # '+' - s = internal_strftime('%a %b %e %H:%M:%S %Z %Y') - fmt_str(s, width, flags) else - # Try composite + # Try composite (includes '+', see STRFTIME_COMPOSITE_BYTE) expansion = STRFTIME_COMPOSITE_BYTE[spec] if expansion s = internal_strftime(expansion) From c1078d699f70cfbff1bcf1675e777e20818bf547 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 29 Aug 2026 17:38:43 +0900 Subject: [PATCH 066/144] Replace _parse character-class bitmask with boolean locals _parse tracked which character classes a string contains in an integer bitmask (cc) and gated each sub-parser with expressions like `(cc & (HAVE_ALPHA | HAVE_DIGIT)) == (HAVE_ALPHA | HAVE_DIGIT)`. That is a direct port of the C extension's bit-flag idiom and reads poorly in Ruby. I am replacing cc with six boolean locals (have_alpha, have_digit, have_dash, have_dot, have_slash, have_colon) so each gate becomes a plain logical expression -- e.g. the above is now `have_alpha && have_digit`, and the time gate is `have_digit && (have_colon || have_alpha)`. The HAVE_* private constants existed only for this method and are removed. Behavior is unchanged: _parse output is identical to the previous implementation across a diverse corpus (ISO, US, EU, JIS, VMS, slash, dot, time, BC, ordinal, commercial and malformed inputs), so no test changes are needed. Performance (YJIT; C ext baseline 4.0.1_system.tsv): input | C ext (i/s) | Ruby+YJIT (i/s) | ratio ---------------------+-------------+-----------------+------ Date._parse(iso) | 232,828 | 727,910 | 313% Date._parse(us) | 118,925 | 583,515 | 491% Date._parse(eu) | 159,775 | 538,471 | 337% Date._parse(rfc2822) | 81,118 | 198,517 | 245% Date.parse(iso) | 212,255 | 518,420 | 244% Date.parse(us) | 111,533 | 449,551 | 403% Date.parse(eu) | 146,787 | 408,799 | 279% Date.parse(compact) | 132,039 | 513,908 | 389% Throughput is unchanged from the prior Ruby implementation (all differences within measurement noise); the boolean form is purely a readability improvement. Verified: full suite passes (144 tests, 162614 assertions); no -w warnings. --- lib/date/parse.rb | 59 +++++++++++++++++++++-------------------------- 1 file changed, 26 insertions(+), 33 deletions(-) diff --git a/lib/date/parse.rb b/lib/date/parse.rb index c5f2068f..39bdb3dd 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -3,15 +3,6 @@ require_relative "zonetab" class Date - # Character class flags used by _parse - HAVE_ALPHA = 1 - HAVE_DIGIT = 2 - HAVE_DASH = 4 - HAVE_DOT = 8 - HAVE_SLASH = 16 - HAVE_COLON = 32 - private_constant :HAVE_ALPHA, :HAVE_DIGIT, :HAVE_DASH, :HAVE_DOT, :HAVE_SLASH, :HAVE_COLON - class << self # ------------------------------------------------------------------ @@ -501,95 +492,97 @@ def _parse(string, comp = true, limit: 128) str = string.dup str.gsub!(/[^-+',.\/:\@\[\][:alnum:]]+/, ' ') - # check_class (byte-level for speed) - cc = 0 + # check_class (byte-level for speed): record which character classes the + # string contains, so each parser below runs only when the classes it + # needs are present. + have_alpha = have_digit = have_dash = have_dot = have_slash = have_colon = false str.each_byte do |b| if b >= 65 && b <= 90 || b >= 97 && b <= 122 || b > 127 - cc |= HAVE_ALPHA + have_alpha = true elsif b >= 48 && b <= 57 - cc |= HAVE_DIGIT + have_digit = true elsif b == 45 - cc |= HAVE_DASH + have_dash = true elsif b == 46 - cc |= HAVE_DOT + have_dot = true elsif b == 47 - cc |= HAVE_SLASH + have_slash = true elsif b == 58 - cc |= HAVE_COLON + have_colon = true end end h = {} # parse_day (always runs) - if (cc & HAVE_ALPHA) != 0 + if have_alpha parse_day(str, h) end # parse_time (needs colon or alpha for h/am/pm patterns) - if (cc & HAVE_DIGIT) != 0 && (cc & (HAVE_COLON | HAVE_ALPHA)) != 0 + if have_digit && (have_colon || have_alpha) parse_time(str, h) end # Date parsers: first match wins (goto ok) matched = false - if !matched && (cc & (HAVE_ALPHA | HAVE_DIGIT)) == (HAVE_ALPHA | HAVE_DIGIT) + if !matched && have_alpha && have_digit matched = parse_eu(str, h) end - if !matched && (cc & (HAVE_ALPHA | HAVE_DIGIT)) == (HAVE_ALPHA | HAVE_DIGIT) + if !matched && have_alpha && have_digit matched = parse_us(str, h) end - if !matched && (cc & (HAVE_DIGIT | HAVE_DASH)) == (HAVE_DIGIT | HAVE_DASH) + if !matched && have_digit && have_dash matched = parse_iso(str, h) end - if !matched && (cc & (HAVE_DIGIT | HAVE_DOT)) == (HAVE_DIGIT | HAVE_DOT) + if !matched && have_digit && have_dot matched = parse_jis(str, h) end - if !matched && (cc & (HAVE_ALPHA | HAVE_DIGIT | HAVE_DASH)) == (HAVE_ALPHA | HAVE_DIGIT | HAVE_DASH) + if !matched && have_alpha && have_digit && have_dash matched = parse_vms(str, h) end - if !matched && (cc & (HAVE_DIGIT | HAVE_SLASH)) == (HAVE_DIGIT | HAVE_SLASH) + if !matched && have_digit && have_slash matched = parse_sla(str, h) end - if !matched && (cc & (HAVE_DIGIT | HAVE_DOT)) == (HAVE_DIGIT | HAVE_DOT) + if !matched && have_digit && have_dot matched = parse_dot(str, h) end - if !matched && (cc & HAVE_DIGIT) != 0 + if !matched && have_digit matched = parse_iso2(str, h) end - if !matched && (cc & HAVE_DIGIT) != 0 + if !matched && have_digit matched = parse_year(str, h) end - if !matched && (cc & HAVE_ALPHA) != 0 + if !matched && have_alpha matched = parse_mon(str, h) end - if !matched && (cc & HAVE_DIGIT) != 0 + if !matched && have_digit matched = parse_mday(str, h) end - if !matched && (cc & HAVE_DIGIT) != 0 + if !matched && have_digit parse_ddd(str, h) end # Post-processing (always runs after ok label) # parse_bc - if (cc & HAVE_ALPHA) != 0 + if have_alpha parse_bc_post(str, h) end # parse_frag - if (cc & HAVE_DIGIT) != 0 + if have_digit parse_frag(str, h) end From 12dd14bbef0c488ddec6cd489eb835ffcf184084 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 29 Aug 2026 17:43:02 +0900 Subject: [PATCH 067/144] Realign assignment block in DateTime#_init_datetime The @sec_i -> @sec and @sec_frac -> @sec_fraction rename left the two assignments misaligned with the surrounding column-aligned block. Restore the alignment. Whitespace only; no behavior change. --- lib/date/datetime.rb | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index d2d0a10b..7df05499 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -1030,8 +1030,8 @@ def _init_datetime(jd, h, m, s, sf, of, sg) @day_fraction = nil @hour = h @min = m - @sec = s - @sec_fraction = sf.is_a?(Rational) ? sf : Rational(sf) + @sec = s + @sec_fraction = sf.is_a?(Rational) ? sf : Rational(sf) @of = of.to_i # Initialize lazily-computed (inherited from Date) civil ivars up front so # every DateTime instance shares a single object shape. From 49a1b0722963ece6d3ad2c3d78d154745757ad8b Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 29 Aug 2026 17:48:37 +0900 Subject: [PATCH 068/144] Extract optional-sign scanning into sp_scan_sign Fold the repeated five-line optional-sign idiom (%C/%G/%L/%N/%Y) into a private helper. Behavior unchanged; output identical to HEAD. Performance (YJIT; C ext baseline 4.0.1_system.tsv): operation | C ext (i/s) | Ruby+YJIT (i/s) | ratio ---------------+-------------+-----------------+------ Date.strptime | 1,374,554 | 1,074,000 | 78% --- lib/date/strptime.rb | 37 ++++++++++++------------------------- 1 file changed, 12 insertions(+), 25 deletions(-) diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index fe790050..ad4750bf 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -130,6 +130,13 @@ def to_string_value(obj) :SP_DIGITS_1, :SP_DIGITS_2, :SP_DIGITS_3, :SP_DIGITS_4, :SP_DIGITS_9, :SP_DIGITS_MAX + # Scan an optional leading sign, returning -1 for '-' and 1 otherwise + # (a '+' or no sign at all). When no sign is present the scanner is left + # untouched, since SP_SIGN does not match and #scan does not advance. + def sp_scan_sign(sc) + sc.scan(SP_SIGN) == '-' ? -1 : 1 + end + # Core scanner: walks format string and string simultaneously using StringScanner. # Returns new string position on success; throws :sp_fail on failure. def sp_run(str, si, fmt, hash) @@ -211,11 +218,7 @@ def sp_run(str, si, fmt, hash) when 67 # 'C' num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) - if str_sc.scan(SP_SIGN) - sign = str_sc.matched == '-' ? -1 : 1 - else - sign = 1 - end + sign = sp_scan_sign(str_sc) s = str_sc.scan(num_next ? SP_DIGITS_2 : SP_DIGITS_MAX) throw(:sp_fail) unless s hash[:_cent] = sign * s.to_i @@ -237,11 +240,7 @@ def sp_run(str, si, fmt, hash) str_sc.pos = sp_run(str, str_sc.pos, '%Y-%m-%d', hash) when 71 # 'G' - if str_sc.scan(SP_SIGN) - sign = str_sc.matched == '-' ? -1 : 1 - else - sign = 1 - end + sign = sp_scan_sign(str_sc) num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) s = str_sc.scan(num_next ? SP_DIGITS_4 : SP_DIGITS_MAX) throw(:sp_fail) unless s @@ -277,11 +276,7 @@ def sp_run(str, si, fmt, hash) hash[:yday] = n when 76 # 'L' - if str_sc.scan(SP_SIGN) - sign = str_sc.matched == '-' ? -1 : 1 - else - sign = 1 - end + sign = sp_scan_sign(str_sc) osi = str_sc.pos num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) s = str_sc.scan(num_next ? SP_DIGITS_3 : SP_DIGITS_MAX) @@ -305,11 +300,7 @@ def sp_run(str, si, fmt, hash) hash[:mon] = n when 78 # 'N' - if str_sc.scan(SP_SIGN) - sign = str_sc.matched == '-' ? -1 : 1 - else - sign = 1 - end + sign = sp_scan_sign(str_sc) osi = str_sc.pos num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) s = str_sc.scan(num_next ? SP_DIGITS_9 : SP_DIGITS_MAX) @@ -419,11 +410,7 @@ def sp_run(str, si, fmt, hash) str_sc.pos = sp_run(str, str_sc.pos, '%m/%d/%y', hash) when 89 # 'Y' - if str_sc.scan(SP_SIGN) - sign = str_sc.matched == '-' ? -1 : 1 - else - sign = 1 - end + sign = sp_scan_sign(str_sc) num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) s = str_sc.scan(num_next ? SP_DIGITS_4 : SP_DIGITS_MAX) throw(:sp_fail) unless s From ec8ca0d30ee230cfe68ade46dc26ca375a0d5633 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 29 Aug 2026 18:15:07 +0900 Subject: [PATCH 069/144] Deduplicate fmt_str and fmt_z in strftime Drop the redundant leading dup in fmt_str: the case conversions and rjust below already return fresh strings, and every spec result is only appended via `result <<`, so returning the frozen input string is safe. Collapse fmt_z's duplicated no-leading-zero / leading-zero `case colons` blocks into one by pre-rendering the hour, minute and second strings; the two forms differed only in how the hour is padded. Output is byte-identical to before across the full spec/flag/width/colon matrix. Performance (Date#strftime(%A %B), i/s): variant | C ext (4.0.1) | Ruby+YJIT | ratio --------------+---------------+-----------+------ %A %B | 3,109,861 | 445,781 | 14% The C-vs-Ruby gap here is pre-existing (the %A/%B path predates this change); relative to the previous Ruby implementation the change is neutral to slightly faster (%A %B 445.8k vs 444.1k, %::z 334.1k vs 325.5k i/s under YJIT). --- lib/date/strftime.rb | 73 ++++++++++++++++++-------------------------- 1 file changed, 29 insertions(+), 44 deletions(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 3614cbc5..17386492 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -423,20 +423,19 @@ def pad_num(n, default_w, flags, zero: nil) end def fmt_str(s, width, flags) - s = s.dup if flags & FL_CHCASE != 0 s = (s == s.upcase) ? s.downcase : s.upcase elsif flags & FL_UPPER != 0 s = s.upcase end - if flags & FL_LEFT != 0 - s - elsif width + # Padding applies only when not left-justified and a width is given; the + # case conversions above already return fresh strings, so no defensive dup + # is needed for the paths that return s unchanged. + if flags & FL_LEFT == 0 && width pad = flags & FL_ZERO != 0 ? '0' : ' ' - s.rjust(width, pad) - else - s + s = s.rjust(width, pad) end + s end # Week number (0=first partial week) @@ -461,45 +460,31 @@ def fmt_z(colons, width, flags) no_lead = flags & (FL_LEFT | FL_SPACE) != 0 - if no_lead - case colons - when 0 - s = format('%s%d%02d', sign, hh, mm) - when 1 - s = format('%s%d:%02d', sign, hh, mm) - when 2 - s = format('%s%d:%02d:%02d', sign, hh, mm, ss) - when 3 - if ss != 0 - s = format('%s%d:%02d:%02d', sign, hh, mm, ss) - elsif mm != 0 - s = format('%s%d:%02d', sign, hh, mm) + # The colons variants differ between the leading-zero and no-leading-zero + # forms only in how the hour is padded ('%02d' vs '%d'); the minutes and + # seconds are always two digits, so decide the hour rendering once here. + hh_s = (no_lead || hh >= 10) ? hh.to_s : "0#{hh}" + mm_s = mm < 10 ? "0#{mm}" : mm.to_s + ss_s = ss < 10 ? "0#{ss}" : ss.to_s + + s = case colons + when 1 + "#{sign}#{hh_s}:#{mm_s}" + when 2 + "#{sign}#{hh_s}:#{mm_s}:#{ss_s}" + when 3 + if ss != 0 + "#{sign}#{hh_s}:#{mm_s}:#{ss_s}" + elsif mm != 0 + "#{sign}#{hh_s}:#{mm_s}" + else + "#{sign}#{hh_s}" + end + when 0 + "#{sign}#{hh_s}#{mm_s}" else - s = format('%s%d', sign, hh) + "#{sign}#{hh_s}:#{mm_s}" end - else - s = format('%s%d:%02d', sign, hh, mm) - end - else - case colons - when 0 - s = format('%s%02d%02d', sign, hh, mm) - when 1 - s = format('%s%02d:%02d', sign, hh, mm) - when 2 - s = format('%s%02d:%02d:%02d', sign, hh, mm, ss) - when 3 - if ss != 0 - s = format('%s%02d:%02d:%02d', sign, hh, mm, ss) - elsif mm != 0 - s = format('%s%02d:%02d', sign, hh, mm) - else - s = format('%s%02d', sign, hh) - end - else - s = format('%s%02d:%02d', sign, hh, mm) - end - end if flags & FL_SPACE != 0 # '_' pads with spaces. Without '-' it pads to at least the width the From b43e3de0dbe64e3c64bb5be81a8c07ce8c854e7b Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 29 Aug 2026 18:30:49 +0900 Subject: [PATCH 070/144] Deduplicate wday lookup tables in constants HTTPDATE_WDAY held the same abbreviated-day-name -> wday mapping as ABBR_DAY_NUM, so drop it and point its three parse.rb call sites (_httpdate TYPE1/TYPE3, _rfc2822) at ABBR_DAY_NUM. Re-derive HTTPDATE_FULL_WDAY from DAYNAMES as well, replacing the hand-maintained literal, so both wday maps come from the canonical name lists and cannot drift out of sync. Constants-only change; _parse/_httpdate/_rfc2822 output is identical across the corpus. Performance (i/s; C ext baseline 4.0.1_system.tsv, Ruby under YJIT): operation | C ext (4.0.1) | Ruby+YJIT | ratio ---------------+---------------+-----------+------ Date._httpdate | 403,522 | 380,632 | 94% Date._rfc2822 | 375,805 | 310,804 | 83% Date.httpdate | 320,236 | 291,283 | 91% Date.rfc2822 | 304,311 | 252,837 | 83% The C-vs-Ruby ratios are pre-existing and unchanged by this refactor; relative to the previous Ruby implementation performance is neutral. --- lib/date/constants.rb | 9 +++++---- lib/date/parse.rb | 6 +++--- 2 files changed, 8 insertions(+), 7 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 0d7d5b51..12f0f67f 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -162,10 +162,11 @@ class Date private_constant :HTTPDATE_TYPE1_RE, :HTTPDATE_TYPE2_RE, :HTTPDATE_TYPE3_RE, :FAST_HTTPDATE_TYPE1_RE - # Wday lookup from abbreviated day name (3-char lowercase key) - HTTPDATE_WDAY = {'sun'=>0,'mon'=>1,'tue'=>2,'wed'=>3,'thu'=>4,'fri'=>5,'sat'=>6}.freeze - HTTPDATE_FULL_WDAY = {'sunday'=>0,'monday'=>1,'tuesday'=>2,'wednesday'=>3,'thursday'=>4,'friday'=>5,'saturday'=>6}.freeze - private_constant :HTTPDATE_WDAY, :HTTPDATE_FULL_WDAY + # Wday lookup from full day name (lowercase key). The abbreviated-name + # lookup reuses ABBR_DAY_NUM, which is the identical table; both maps are + # derived from the canonical name lists so they cannot drift out of sync. + HTTPDATE_FULL_WDAY = DAYNAMES.each_with_index.to_h { |n, i| [n.downcase, i] }.freeze + private_constant :HTTPDATE_FULL_WDAY RFC2822_RE = /\A\s*(?:(sun|mon|tue|wed|thu|fri|sat)\s*,\s+)?(\d{1,2})\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+(-?\d{2,})\s+(\d{2}):(\d{2})(?::(\d{2}))?\s*([-+]\d{4}|ut|gmt|e[sd]t|c[sd]t|m[sd]t|p[sd]t|[a-ik-z])\s*\z/i private_constant :RFC2822_RE diff --git a/lib/date/parse.rb b/lib/date/parse.rb index 39bdb3dd..ab81df76 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -120,7 +120,7 @@ def _httpdate(string, limit: 128) h = {} if (m = HTTPDATE_TYPE1_RE.match(string)) - h[:wday] = HTTPDATE_WDAY[m[1].downcase] + h[:wday] = ABBR_DAY_NUM[m[1].downcase] h[:mday] = m[2].to_i h[:mon] = ABBR_MONTH_NUM[m[3].downcase] h[:year] = m[4].to_i @@ -141,7 +141,7 @@ def _httpdate(string, limit: 128) h[:zone] = m[8] h[:offset] = 0 elsif (m = HTTPDATE_TYPE3_RE.match(string)) - h[:wday] = HTTPDATE_WDAY[m[1].downcase] + h[:wday] = ABBR_DAY_NUM[m[1].downcase] h[:mon] = ABBR_MONTH_NUM[m[2].downcase] h[:mday] = m[3].to_i h[:hour] = m[4].to_i @@ -208,7 +208,7 @@ def _rfc2822(string, limit: 128) string.gsub(/[\r\n\0]+/, ' ') : string h = {} if (m = RFC2822_RE.match(s)) - h[:wday] = HTTPDATE_WDAY[m[1].downcase] if m[1] + h[:wday] = ABBR_DAY_NUM[m[1].downcase] if m[1] h[:mday] = m[2].to_i h[:mon] = ABBR_MONTH_NUM[m[3].downcase] y_s = m[4] From 4634633926b89629c28028ef81bdce9bbe239ff1 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sat, 29 Aug 2026 22:36:26 +0900 Subject: [PATCH 071/144] Extract repeated strptime idioms into helper methods Address review feedback asking that duplicated code in strptime.rb be extracted into methods: - sp_store_int: fold the "scan / fail-unless / to_i / range-check / store" idiom repeated across 14 numeric specifiers into one helper. - sp_count_keys: count how many keys a fragment hash holds, DRYing up the fast path and the fragment table loop in sp_complete_frags. - sp_strip_word: promote the strip_word closure in sp_zone_to_diff to a method, and use $' instead of the cryptic slice on the utc? strip. Behavior-preserving: byte-identical to the previous implementation across the strptime, fragment-completion, and zone corpora; suite 144/162614/100%. Performance vs the C extension (bench 4.0.1_system, YJIT), unchanged by this refactor: | Method | C ext (i/s) | Ruby (i/s) | Ruby/C | |-------------------------|-------------|------------|--------| | Date._strptime | 2,721,889 | 1,322,000 | 48.6% | | Date.strptime | 1,374,554 | 1,072,000 | 78.0% | | Date.strptime(complex) | 1,114,730 | 505,305 | 45.3% | --- lib/date/strptime.rb | 151 ++++++++++++++++--------------------------- 1 file changed, 54 insertions(+), 97 deletions(-) diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index ad4750bf..4f3dc185 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -137,6 +137,16 @@ def sp_scan_sign(sc) sc.scan(SP_SIGN) == '-' ? -1 : 1 end + # Convert an already-scanned numeric field, validate it against an inclusive + # range, and store it in +hash+ under +sym+. Throws :sp_fail when nothing was + # scanned or the value falls outside [lower, upper]. Returns the stored value. + def sp_store_int(hash, sym, s, lower, upper) + throw(:sp_fail) unless s + n = s.to_i + throw(:sp_fail) if n < lower || n > upper + hash[sym] = n + end + # Core scanner: walks format string and string simultaneously using StringScanner. # Returns new string position on success; throws :sp_fail on failure. def sp_run(str, si, fmt, hash) @@ -230,11 +240,7 @@ def sp_run(str, si, fmt, hash) str_sc.pos = sp_run(str, str_sc.pos, '%m/%d/%y', hash) when 100, 101 # 'd', 'e' - s = str_sc.scan(SP_SPACE_OR_DIGIT) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n < 1 || n > 31 - hash[:mday] = n + sp_store_int(hash, :mday, str_sc.scan(SP_SPACE_OR_DIGIT), 1, 31) when 70 # 'F' str_sc.pos = sp_run(str, str_sc.pos, '%Y-%m-%d', hash) @@ -247,33 +253,17 @@ def sp_run(str, si, fmt, hash) hash[:cwyear] = sign * s.to_i when 103 # 'g' - s = str_sc.scan(SP_DIGITS_2) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n > 99 - hash[:cwyear] = n + n = sp_store_int(hash, :cwyear, str_sc.scan(SP_DIGITS_2), 0, 99) hash[:_cent] ||= n >= 69 ? 19 : 20 when 72, 107 # 'H', 'k' - s = str_sc.scan(SP_SPACE_OR_DIGIT) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n > 24 - hash[:hour] = n + sp_store_int(hash, :hour, str_sc.scan(SP_SPACE_OR_DIGIT), 0, 24) when 73, 108 # 'I', 'l' - s = str_sc.scan(SP_SPACE_OR_DIGIT) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n < 1 || n > 12 - hash[:hour] = n + sp_store_int(hash, :hour, str_sc.scan(SP_SPACE_OR_DIGIT), 1, 12) when 106 # 'j' - s = str_sc.scan(SP_DIGITS_3) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n < 1 || n > 366 - hash[:yday] = n + sp_store_int(hash, :yday, str_sc.scan(SP_DIGITS_3), 1, 366) when 76 # 'L' sign = sp_scan_sign(str_sc) @@ -286,18 +276,10 @@ def sp_run(str, si, fmt, hash) hash[:sec_fraction] = Rational(n, 10**(str_sc.pos - osi)) when 77 # 'M' - s = str_sc.scan(SP_DIGITS_2) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n > 59 - hash[:min] = n + sp_store_int(hash, :min, str_sc.scan(SP_DIGITS_2), 0, 59) when 109 # 'm' - s = str_sc.scan(SP_DIGITS_2) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n < 1 || n > 12 - hash[:mon] = n + sp_store_int(hash, :mon, str_sc.scan(SP_DIGITS_2), 1, 12) when 78 # 'N' sign = sp_scan_sign(str_sc) @@ -345,11 +327,7 @@ def sp_run(str, si, fmt, hash) str_sc.pos = sp_run(str, str_sc.pos, '%I:%M:%S %p', hash) when 83 # 'S' - s = str_sc.scan(SP_DIGITS_2) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n > 60 - hash[:sec] = n + sp_store_int(hash, :sec, str_sc.scan(SP_DIGITS_2), 0, 60) when 115 # 's' sign = 1 @@ -366,42 +344,22 @@ def sp_run(str, si, fmt, hash) str_sc.pos = sp_run(str, str_sc.pos, '%H:%M:%S', hash) when 85 # 'U' - s = str_sc.scan(SP_DIGITS_2) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n > 53 - hash[:wnum0] = n + sp_store_int(hash, :wnum0, str_sc.scan(SP_DIGITS_2), 0, 53) when 117 # 'u' - s = str_sc.scan(SP_DIGITS_1) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n < 1 || n > 7 - hash[:cwday] = n + sp_store_int(hash, :cwday, str_sc.scan(SP_DIGITS_1), 1, 7) when 86 # 'V' - s = str_sc.scan(SP_DIGITS_2) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n < 1 || n > 53 - hash[:cweek] = n + sp_store_int(hash, :cweek, str_sc.scan(SP_DIGITS_2), 1, 53) when 118 # 'v' str_sc.pos = sp_run(str, str_sc.pos, '%e-%b-%Y', hash) when 87 # 'W' - s = str_sc.scan(SP_DIGITS_2) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n > 53 - hash[:wnum1] = n + sp_store_int(hash, :wnum1, str_sc.scan(SP_DIGITS_2), 0, 53) when 119 # 'w' - s = str_sc.scan(SP_DIGITS_1) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n > 6 - hash[:wday] = n + sp_store_int(hash, :wday, str_sc.scan(SP_DIGITS_1), 0, 6) when 88 # 'X' str_sc.pos = sp_run(str, str_sc.pos, '%H:%M:%S', hash) @@ -417,11 +375,7 @@ def sp_run(str, si, fmt, hash) hash[:year] = sign * s.to_i when 121 # 'y' - s = str_sc.scan(SP_DIGITS_2) - throw(:sp_fail) unless s - n = s.to_i - throw(:sp_fail) if n > 99 - hash[:year] = n + n = sp_store_int(hash, :year, str_sc.scan(SP_DIGITS_2), 0, 99) hash[:_cent] ||= n >= 69 ? 19 : 20 when 90, 122 # 'Z', 'z' @@ -611,6 +565,20 @@ def sp_zone(str, si, slen, hash) si + m[0].length end + # Measure a trailing +word+ within the first +len+ characters of +str+, + # ignoring case and requiring a preceding whitespace boundary. Returns the + # number of characters to strip (the word plus its leading whitespace run), + # or nil when +word+ is not present at that position. + def sp_strip_word(str, len, word) + n = word.length + return nil unless len > n + return nil unless str[len - n - 1] =~ /[[:space:]]/ + return nil unless str[len - n, n].casecmp(word) == 0 + n += 1 + n += 1 while len > n && str[len - n - 1] =~ /[[:space:]]/ + n + end + # Convert a zone string to seconds offset from UTC. # Returns Integer (seconds) or Rational, or nil if unparseable. # Ported from the original C date_zone_to_diff(). @@ -638,28 +606,18 @@ def sp_zone_to_diff(zone_str) dst = false # Strip trailing " time" (optionally preceded by "standard" or "daylight") - strip_word = lambda do |str, len, word| - n = word.length - return nil unless len > n - return nil unless str[len - n - 1] =~ /[[:space:]]/ - return nil unless str[len - n, n].casecmp(word) == 0 - n += 1 - n += 1 while len > n && str[len - n - 1] =~ /[[:space:]]/ - n - end - l = s.length - if (w = strip_word.call(s, l, 'time')) + if (w = sp_strip_word(s, l, 'time')) l -= w - if (w2 = strip_word.call(s, l, 'standard')) + if (w2 = sp_strip_word(s, l, 'standard')) l -= w2 - elsif (w2 = strip_word.call(s, l, 'daylight')) + elsif (w2 = sp_strip_word(s, l, 'daylight')) l -= w2 dst = true else l += w # revert end - elsif (w = strip_word.call(s, l, 'dst')) + elsif (w = sp_strip_word(s, l, 'dst')) l -= w dst = true end @@ -672,7 +630,7 @@ def sp_zone_to_diff(zone_str) # Numeric parsing t = s[0, l].strip t = t[3..] if t =~ /\Agmt/i - t = t[$&.length..] if t =~ /\Autc?/i + t = $' if t =~ /\Autc?/i return nil unless t && t.length > 0 && (t[0] == '+' || t[0] == '-') sign = t[0] == '-' ? -1 : 1 @@ -740,18 +698,17 @@ def sp_rewrite_frags(hash) # Complete partial date fragments by filling defaults from today's date. # Mirrors rt_complete_frags() in C. + # Count how many of +keys+ are present in +hash+. + def sp_count_keys(hash, keys) + keys.count { |sym| hash.key?(sym) } + end + def sp_complete_frags(klass, hash) # Fast path: detect :civil case (most common) without iterating all entries k = nil a = nil if hash.key?(:year) || hash.key?(:mon) || hash.key?(:mday) - civil_n = 0 - civil_n += 1 if hash.key?(:year) - civil_n += 1 if hash.key?(:mon) - civil_n += 1 if hash.key?(:mday) - civil_n += 1 if hash.key?(:hour) - civil_n += 1 if hash.key?(:min) - civil_n += 1 if hash.key?(:sec) + civil_n = sp_count_keys(hash, [:year, :mon, :mday, :hour, :min, :sec]) # Check if any other pattern matches better best_n = civil_n skip_civil = false @@ -759,19 +716,19 @@ def sp_complete_frags(klass, hash) skip_civil = true if 1 > best_n end if hash.key?(:yday) # ordinal [:year, :yday, :hour, :min, :sec] - ord_n = (hash.key?(:year) ? 1 : 0) + 1 + (hash.key?(:hour) ? 1 : 0) + (hash.key?(:min) ? 1 : 0) + (hash.key?(:sec) ? 1 : 0) + ord_n = sp_count_keys(hash, [:year, :yday, :hour, :min, :sec]) skip_civil = true if ord_n > best_n end if hash.key?(:cwyear) || hash.key?(:cweek) || hash.key?(:cwday) - com_n = (hash.key?(:cwyear) ? 1 : 0) + (hash.key?(:cweek) ? 1 : 0) + (hash.key?(:cwday) ? 1 : 0) + (hash.key?(:hour) ? 1 : 0) + (hash.key?(:min) ? 1 : 0) + (hash.key?(:sec) ? 1 : 0) + com_n = sp_count_keys(hash, [:cwyear, :cweek, :cwday, :hour, :min, :sec]) skip_civil = true if com_n > best_n end if hash.key?(:wnum0) - wn0_n = (hash.key?(:year) ? 1 : 0) + 1 + (hash.key?(:wday) ? 1 : 0) + (hash.key?(:hour) ? 1 : 0) + (hash.key?(:min) ? 1 : 0) + (hash.key?(:sec) ? 1 : 0) + wn0_n = sp_count_keys(hash, [:year, :wnum0, :wday, :hour, :min, :sec]) skip_civil = true if wn0_n > best_n end if hash.key?(:wnum1) - wn1_n = (hash.key?(:year) ? 1 : 0) + 1 + (hash.key?(:wday) ? 1 : 0) + (hash.key?(:hour) ? 1 : 0) + (hash.key?(:min) ? 1 : 0) + (hash.key?(:sec) ? 1 : 0) + wn1_n = sp_count_keys(hash, [:year, :wnum1, :wday, :hour, :min, :sec]) skip_civil = true if wn1_n > best_n end unless skip_civil @@ -785,7 +742,7 @@ def sp_complete_frags(klass, hash) best_a = nil best_n = 0 COMPLETE_FRAGS_TAB.each do |ek, ea| - n = ea.count { |sym| hash.key?(sym) } + n = sp_count_keys(hash, ea) if n > best_n best_k = ek best_a = ea From 468e4017f6af66687213dc54b9a9ecb001f5ec65 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 27 Sep 2026 16:42:39 +0900 Subject: [PATCH 072/144] Deduplicate offset and year handling in parse.rb MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Address review feedback (PR #155) on repeated code in parse.rb: - parse_ddd: the bracketed-zone branches each repeated `off_s = "+#{off_s}" unless ...` and `h[:offset] = fast_zone_offset(off_s)`. Each branch now only assigns off_s, and the normalization plus offset assignment runs once after the branches, guarded by `if off_s`. - s3e: replace the cryptic `ys_raw[$~.end(0)..]` with `$'`, and extract the "does this token look like a year" test (steps 2/4/5) into s3e_year_like?. - Extract the _comp-flag test (signed or more-than-two-digit year) into s3e_full_year?, shared by s3e and s3eparse_year. Behavior-preserving: byte-identical to the previous implementation across a 47384-line Date._parse/Date.parse corpus (s3e disambiguation and parse_ddd bracket zones); suite 147/162625/100%. Performance is HEAD-neutral under YJIT. | Method | C ext (i/s) | Ruby+YJIT (i/s) | Ruby/C | |-------------|-------------|-----------------|--------| | Date._parse | (see bench/results/20260223_r1/4.0.1_system.tsv) | 7,275 | - | | Date.parse | (同上) | 7,003 | - | --- lib/date/parse.rb | 51 ++++++++++++++++++++++++++--------------------- 1 file changed, 28 insertions(+), 23 deletions(-) diff --git a/lib/date/parse.rb b/lib/date/parse.rb index ab81df76..ef7f752f 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -1282,27 +1282,24 @@ def parse_ddd(str, h) if zone.start_with?('[') zone = zone[1...-1] # strip brackets # Format: [offset:zonename] or [offset zonename] or [offset] or [zonename] + off_s = nil if (zm = zone.match(/\A([-+]?\d+(?:[,.]\d+)?):(.+)/)) # +9:JST, -5:EST, +12:XXX YYY ZZZ h[:zone] = zm[2].strip off_s = zm[1] - off_s = "+#{off_s}" unless off_s.start_with?('+') || off_s.start_with?('-') - h[:offset] = fast_zone_offset(off_s) elsif (zm = zone.match(/\A([-+]?\d+(?:[,.]\d+)?)\s+(\S.+)/)) # Number followed by space and non-empty name h[:zone] = zm[2] off_s = zm[1] - off_s = "+#{off_s}" unless off_s.start_with?('+') || off_s.start_with?('-') - h[:offset] = fast_zone_offset(off_s) else # Could be just a number with optional trailing space: [9], [-9], [9 ] h[:zone] = zone stripped = zone.strip - if stripped =~ /\A([-+]?\d+(?:[,.]\d+)?)\z/ - off_s = $1 - off_s = "+#{off_s}" unless off_s.start_with?('+') || off_s.start_with?('-') - h[:offset] = fast_zone_offset(off_s) - end + off_s = $1 if stripped =~ /\A([-+]?\d+(?:[,.]\d+)?)\z/ + end + if off_s + off_s = "+#{off_s}" unless off_s.start_with?('+') || off_s.start_with?('-') + h[:offset] = fast_zone_offset(off_s) end else h[:zone] = zone @@ -1361,9 +1358,7 @@ def s3e(h, y, m, d, bc) # Step 2: If y is nil but d is present, check if d looks like a year if y.nil? && d - ds = d.to_s - digits = ds.sub(/\A'?-?/, '').sub(/(?:st|nd|rd|th)\z/i, '') - if digits.length > 2 || ds.start_with?("'") + if s3e_year_like?(d.to_s) y = d d = nil end @@ -1381,7 +1376,7 @@ def s3e(h, y, m, d, bc) # Match digits (with optional leading sign), check for trailing non-digit if ys_raw =~ /\A[^-+\d]*([-+]?\d+)/ num_s = $1 - rest = ys_raw[$~.end(0)..] + rest = $' if rest && !rest.empty? && rest =~ /[^\d]/ # trailing non-digit (like "st" in "1st"): this y becomes d, old d becomes y old_d = d @@ -1396,9 +1391,7 @@ def s3e(h, y, m, d, bc) end else year_val = num_s.to_i - if num_s.start_with?('-') || num_s.start_with?('+') || num_s.sub(/\A[-+]/, '').length > 2 - comp_flag = false - end + comp_flag = false if s3e_full_year?(num_s) end end end @@ -1406,8 +1399,7 @@ def s3e(h, y, m, d, bc) # Step 4: Check m - if it looks like a year (apostrophe or > 2 digits), swap US→BE if m.is_a?(String) - ms_digits = m.sub(/\A'?-?/, '').sub(/(?:st|nd|rd|th)\z/i, '') - if m.start_with?("'") || ms_digits.length > 2 + if s3e_year_like?(m) # Rotate: old_y=y, y=m, m=d, d=old_y_string old_y = y y = m @@ -1422,15 +1414,14 @@ def s3e(h, y, m, d, bc) elsif ys =~ /([-+]?\d+)/ num_s = $1 year_val = num_s.to_i - comp_flag = (num_s.start_with?('-') || num_s.start_with?('+') || num_s.sub(/\A[-+]/, '').length > 2) ? false : nil + comp_flag = s3e_full_year?(num_s) ? false : nil end end end # Step 5: Check d - if it looks like a year, swap with y if d.is_a?(String) - ds_digits = d.sub(/\A'?-?/, '').sub(/(?:st|nd|rd|th)\z/i, '') - if d.start_with?("'") || ds_digits.length > 2 + if s3e_year_like?(d) old_y = y # d becomes year ys = d.sub(/(?:st|nd|rd|th)\z/i, '') @@ -1440,7 +1431,7 @@ def s3e(h, y, m, d, bc) elsif ys =~ /([-+]?\d+)/ num_s = $1 year_val = num_s.to_i - comp_flag = (num_s.start_with?('-') || num_s.start_with?('+') || num_s.sub(/\A[-+]/, '').length > 2) ? false : nil + comp_flag = s3e_full_year?(num_s) ? false : nil end d = old_y end @@ -1478,11 +1469,25 @@ def s3eparse_year(s) [s[1..].to_i, true] elsif s =~ /\A[^-+\d]*([-+]?\d+)/ num_s = $1 - cf = (num_s.start_with?('-') || num_s.start_with?('+') || num_s.sub(/\A[-+]/, '').length > 2) ? false : nil + cf = s3e_full_year?(num_s) ? false : nil [num_s.to_i, cf] end end + # Helper: does token +s+ look like a year? True when it is apostrophe-prefixed + # or has more than two significant digits after stripping a leading sign or + # apostrophe and any ordinal suffix. Used by s3e to decide year/day swaps. + def s3e_year_like?(s) + digits = s.sub(/\A'?-?/, '').sub(/(?:st|nd|rd|th)\z/i, '') + digits.length > 2 || s.start_with?("'") + end + + # Helper: is the numeric year string +num_s+ an explicit (non-abbreviated) + # year, i.e. signed or with more than two digits? Determines the _comp flag. + def s3e_full_year?(num_s) + num_s.start_with?('-') || num_s.start_with?('+') || num_s.sub(/\A[-+]/, '').length > 2 + end + # ------------------------------------------------------------------ # Fast Date construction # ------------------------------------------------------------------ From aa2df6b13c7a49596eeeaefc35cdef1c1f5047e2 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 27 Sep 2026 17:08:59 +0900 Subject: [PATCH 073/144] Inline single-use DateTime format constants Address review feedback (PR #155): STRFTIME_DATETIME_DEFAULT_FMT and DATETIME_TO_S_FMT were each used in exactly one place. Inline the format strings into DateTime#strftime's default argument and DateTime#to_s respectively, and drop the private constants. Behavior-preserving; suite 147/162625/100%. DateTime is deprecated, so no benchmark table is included. --- lib/date/datetime.rb | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index d69dae09..1bd0dfa1 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -3,9 +3,6 @@ class DateTime < Date - STRFTIME_DATETIME_DEFAULT_FMT = '%FT%T%:z'.encode(Encoding::US_ASCII) - private_constant :STRFTIME_DATETIME_DEFAULT_FMT - # Sentinel marking an hour/minute/second argument that was not passed, so a # trailing fraction can be rejected only when a smaller unit was actually given. UNSET = Object.new @@ -287,7 +284,7 @@ def new_offset(of = 0) # # For other formats, # see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: - def strftime(format = STRFTIME_DATETIME_DEFAULT_FMT) + def strftime(format = '%FT%T%:z'.encode(Encoding::US_ASCII)) super(format) end @@ -421,9 +418,6 @@ def deconstruct_keys(keys) end end - DATETIME_TO_S_FMT = '%Y-%m-%dT%H:%M:%S%:z'.encode(Encoding::US_ASCII).freeze - private_constant :DATETIME_TO_S_FMT - # call-seq: # dt.to_s -> string # @@ -433,7 +427,7 @@ def deconstruct_keys(keys) # DateTime.new(2001,2,3,4,5,6,'-7').to_s # #=> "2001-02-03T04:05:06-07:00" def to_s - strftime(DATETIME_TO_S_FMT) + strftime('%Y-%m-%dT%H:%M:%S%:z'.encode(Encoding::US_ASCII)) end # call-seq: From 9e6e8da078ba6216fe7d846ef4f5a4e050ade56b Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 27 Sep 2026 17:11:58 +0900 Subject: [PATCH 074/144] Deduplicate DateTime#ajd and offset-string accessors Address review feedback (PR #155): - DateTime#ajd recomputed the day fraction and offset inline; have it call #day_fraction and #offset instead, which return exactly those values. - DateTime#zone and #zone_str both called _of2str(@of). Inline the formatting into #zone, delegate #zone_str to #zone, and drop the single-use _of2str. Behavior-preserving; suite 147/162625/100%. DateTime is deprecated, so no benchmark table is included. --- lib/date/datetime.rb | 22 +++++++--------------- 1 file changed, 7 insertions(+), 15 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 1bd0dfa1..505513b8 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -125,7 +125,11 @@ def offset # # DateTime.parse('04pm+0730').zone #=> "+07:30" def zone - _of2str(@of) + sign = @of < 0 ? '-' : '+' + abs = @of.abs + h = abs / 3600 + m = (abs % 3600) / 60 + format('%s%02d:%02d'.encode(Encoding::US_ASCII), sign, h, m) end # call-seq: @@ -148,11 +152,7 @@ def day_fraction # DateTime.new(2001,2,3,4,5,6,'+7').ajd #=> (11769328217/4800) # DateTime.new(2001,2,2,14,5,6,'-7').ajd #=> (11769328217/4800) def ajd - jd_r = Rational(@jd) - time_r = Rational(@hour * 3600 + @min * 60 + @sec, 86400) + - Rational(@sec_fraction.numerator, @sec_fraction.denominator * 86400) - of_r = Rational(@of, 86400) - jd_r + time_r - of_r - 0.5r + Rational(@jd) + day_fraction - offset - 0.5r end # --------------------------------------------------------------------------- @@ -1011,7 +1011,7 @@ def of_seconds end def zone_str - _of2str(@of) + zone end # Overrides of the Date strftime time-part helpers (see Date#strftime_hms): @@ -1065,14 +1065,6 @@ def _split_second(second) end end - def _of2str(of) - sign = of < 0 ? '-' : '+' - abs = of.abs - h = abs / 3600 - m = (abs % 3600) / 60 - format('%s%02d:%02d'.encode(Encoding::US_ASCII), sign, h, m) - end - def _from_total_sec_r(total_r) jd = (total_r / 86400).floor rem = total_r - jd * 86400 From 45d12ae9c57207337c7837c3c79f57752e34e803 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 27 Sep 2026 17:13:59 +0900 Subject: [PATCH 075/144] Deduplicate DateTime#+ and DateTime#- branches Address review feedback (PR #155): - DateTime#+ : the Numeric branch duplicated the Rational/Float branch. After confirming the value converts to a Rational, delegate with `self + r`. - DateTime#- : an Integer operand produced the same result as routing through #+ with the negated operand, so fold Integer into the Rational/Float branch (`self + (-other)`). _from_total_sec_r is kept as a named helper (one caller) rather than inlined, for readability. Behavior-preserving: DateTime#+ and DateTime#- are byte- identical to the previous implementation across an operand matrix (Integer/ Rational/Float/Numeric, DateTime and Date subtraction, and invalid operands). Suite 147/162625/100%. DateTime is deprecated, so no benchmark table is included. --- lib/date/datetime.rb | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 505513b8..2179e029 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -185,9 +185,7 @@ def +(other) when Numeric r = other.to_r raise TypeError, "#{other.class} can't be coerced into Integer" unless r.is_a?(Rational) - extra_sec = r * 86400 - total_r = Rational(@jd) * 86400 + @hour * 3600 + @min * 60 + @sec + @sec_fraction + extra_sec - _from_total_sec_r(total_r) + self + r else raise TypeError, "expected numeric" end @@ -214,9 +212,7 @@ def -(other) case other when Date ajd - other.ajd - when Integer - self.class.__send__(:_new_dt_from_jd_time,@jd - other, @hour, @min, @sec, @sec_fraction, @of, @start) - when Rational, Float + when Integer, Rational, Float self + (-other) when Numeric r = other.to_r From 82c14958150529117d6985666d073d7ba3513719 Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 27 Sep 2026 17:16:30 +0900 Subject: [PATCH 076/144] Extract repeated match-blanking into a helper (parse) Address review feedback (PR #155): the idiom str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) appeared 21 times across the _parse sub-parsers. Extract it into blank_match!(str, m), which also uses the range-free `str[b, size] = ' ' * size` form the review suggested. Behavior-preserving: byte-identical to the previous implementation across a 47384-line Date._parse/Date.parse corpus; suite 147/162625/100%. --- lib/date/parse.rb | 50 +++++++++++++++++++++++++++-------------------- 1 file changed, 29 insertions(+), 21 deletions(-) diff --git a/lib/date/parse.rb b/lib/date/parse.rb index ef7f752f..aabf732f 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -799,6 +799,14 @@ def parse_check_limit(str, limit) raise ArgumentError, "string length (#{str.length}) exceeds the limit #{limit}" if limit && str.length > limit end + # Blank out the span matched by +m+ in +str+, replacing it with spaces of + # equal length. Avoids allocating a Range for the assignment. + def blank_match!(str, m) + b = m.begin(0) + size = m.end(0) - b + str[b, size] = ' ' * size + end + def parse_zone_and_offset(zone_str, hash) return unless zone_str hash[:zone] = zone_str @@ -934,7 +942,7 @@ def iso8601_bas_datetime(m, h) def parse_day(str, h) if (m = PARSE_DAYS_RE.match(str)) h[:wday] = ABBR_DAY_NUM[m[1].downcase] - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) end end @@ -942,7 +950,7 @@ def parse_time(str, h) if (m = PARSE_TIME_RE.match(str)) time_part = m[1] zone_part = m[2] - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) if (tm = PARSE_TIME_CB_RE.match(time_part)) hour = tm[1].to_i @@ -972,7 +980,7 @@ def parse_eu(str, h) return false unless mon bc = m[3] && m[3] =~ /\Ab/i ? true : false s3e(h, m[4], mon, m[1], bc) - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) true else false @@ -985,7 +993,7 @@ def parse_us(str, h) return false unless mon bc = m[3] && m[3] =~ /\Ab/i ? true : false s3e(h, m[4], mon, m[2], bc) - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) true else false @@ -1006,7 +1014,7 @@ def parse_iso(str, h) else s3e(h, y_s, m_s, d_s, false) end - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) true else false @@ -1021,7 +1029,7 @@ def parse_jis(str, h) h[:year] = m[2].to_i + era_offset h[:mon] = m[3].to_i h[:mday] = m[4].to_i - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) true else false @@ -1033,13 +1041,13 @@ def parse_vms(str, h) mon = ABBR_MONTH_NUM[m[2].downcase] return false unless mon s3e(h, m[3], mon, m[1], false) - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) true elsif (m = PARSE_VMS12_RE.match(str)) mon = ABBR_MONTH_NUM[m[1].downcase] return false unless mon s3e(h, m[3], mon, m[2], false) - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) true else false @@ -1049,7 +1057,7 @@ def parse_vms(str, h) def parse_sla(str, h) if (m = PARSE_SLA_RE.match(str)) s3e(h, m[1], m[2], m[3], false) - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) true else false @@ -1059,7 +1067,7 @@ def parse_sla(str, h) def parse_dot(str, h) if (m = PARSE_DOT_RE.match(str)) s3e(h, m[1], m[2], m[3], false) - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) true else false @@ -1075,14 +1083,14 @@ def parse_iso2(str, h) end h[:cweek] = m[2].to_i h[:cwday] = m[3].to_i if m[3] - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) return true end # iso22: -w-D if (m = PARSE_ISO22_RE.match(str)) h[:cwday] = m[1].to_i - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) return true end @@ -1090,7 +1098,7 @@ def parse_iso2(str, h) if (m = PARSE_ISO23_RE.match(str)) h[:mon] = m[1].to_i if m[1] h[:mday] = m[2].to_i - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) return true end @@ -1098,7 +1106,7 @@ def parse_iso2(str, h) if (m = PARSE_ISO24_RE.match(str)) h[:mon] = m[1].to_i h[:mday] = m[2].to_i if m[2] - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) return true end @@ -1107,7 +1115,7 @@ def parse_iso2(str, h) if (m = PARSE_ISO25_RE.match(str)) h[:year] = m[1].to_i h[:yday] = m[2].to_i - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) return true end end @@ -1116,7 +1124,7 @@ def parse_iso2(str, h) unless str =~ /\d-\d{3}\b/ if (m = PARSE_ISO26_RE.match(str)) h[:yday] = m[1].to_i - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) return true end end @@ -1127,7 +1135,7 @@ def parse_iso2(str, h) def parse_year(str, h) if (m = PARSE_YEAR_RE.match(str)) h[:year] = m[1].to_i - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) true else false @@ -1139,7 +1147,7 @@ def parse_mon(str, h) mon = ABBR_MONTH_NUM[m[1].downcase] if mon h[:mon] = mon - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) return true end end @@ -1149,7 +1157,7 @@ def parse_mon(str, h) def parse_mday(str, h) if (m = PARSE_MDAY_RE.match(str)) h[:mday] = m[1].to_i - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) true else false @@ -1306,7 +1314,7 @@ def parse_ddd(str, h) end end - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) true else false @@ -1316,7 +1324,7 @@ def parse_ddd(str, h) def parse_bc_post(str, h) if (m = PARSE_BC_RE.match(str)) h[:_bc] = true - str[m.begin(0)...m.end(0)] = ' ' * (m.end(0) - m.begin(0)) + blank_match!(str, m) end end From 5ae91c8b9287709243e9df50aa81eb19bde7405b Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 27 Sep 2026 17:20:56 +0900 Subject: [PATCH 077/144] Remove no-op zone reassignment in _rfc2822 Address review feedback (PR #155): the fast path had `zone = '+0000' if zone == '+0000'`, which reassigns the same value it already holds and is used only as a hash value afterward. Delete it. Behavior-preserving: byte-identical to the previous implementation across the Date._parse/Date.parse corpus, and Date._rfc2822 of a "+0000" string still returns zone "+0000". Suite 147/162625/100%. --- lib/date/parse.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/date/parse.rb b/lib/date/parse.rb index aabf732f..df6a90b9 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -192,7 +192,6 @@ def _rfc2822(string, limit: 128) zone = sc[8] sign = zone[0] == '-' ? -1 : 1 offset_val = sign * (zone[1, 2].to_i * 3600 + zone[3, 2].to_i * 60) - zone = '+0000' if zone == '+0000' return { wday: wday_info[0], mday: sc[2].to_i, mon: mon_info[0], year: sc[4].to_i, hour: sc[5].to_i, min: sc[6].to_i, sec: sc[7].to_i, From fe084e5a338efd9d71d2b8e42b1853aa79b6da4e Mon Sep 17 00:00:00 2001 From: jinroq Date: Sun, 27 Sep 2026 17:23:22 +0900 Subject: [PATCH 078/144] Simplify fmt_year in strftime Address review feedback (PR #155): fmt_year's result is always numeric (digits with an optional leading '-'), so the trailing upper/chcase branch was a no-op. Drop it and return the formatted string directly, and hoist the sign into a local to avoid repeating the ternary. Behavior-preserving: %Y and %G output is byte-identical to the previous implementation across 1820 combinations of year (incl. negative and short), flags, and widths; suite 147/162625/100%. Behavior-only refactor, so no benchmark table. --- lib/date/strftime.rb | 19 +++++++------------ 1 file changed, 7 insertions(+), 12 deletions(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 17386492..a29949fb 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -385,24 +385,19 @@ def format_spec_b(spec, flags, colons, width) # Format year (handles negative years and all flag variants) def fmt_year(y, width, flags) + # The result is always numeric (digits with an optional leading '-'), so the + # upper/chcase flags are no-ops and need no handling here. + sign = y < 0 ? '-' : '' if flags & FL_LEFT != 0 - s = (y < 0 ? '-' : '') + y.abs.to_s + sign + y.abs.to_s else - default_w = y < 0 ? 5 : 4 - w = width || default_w + w = width || (y < 0 ? 5 : 4) if flags & FL_SPACE != 0 - raw = (y < 0 ? '-' : '') + y.abs.to_s - s = raw.rjust(w, ' ') + (sign + y.abs.to_s).rjust(w, ' ') else - s = y.abs.to_s.rjust(w - (y < 0 ? 1 : 0), '0') - s = (y < 0 ? '-' : '') + s + sign + y.abs.to_s.rjust(w - sign.length, '0') end end - if flags & (FL_UPPER | FL_CHCASE) != 0 - s.upcase - else - s - end end def pad_num(n, default_w, flags, zero: nil) From de45312cfba917b20698d401c9af0504b3d3ae31 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 15:23:49 -0700 Subject: [PATCH 079/144] Remove Date#initialize_copy This isn't needed, Kernel#initialize_copy works fine as all instance variables are immutable. Fix a bogus test that passed a Date instance to DateTime#initialize_copy. --- lib/date/core.rb | 14 -------------- test/date/test_date_new.rb | 2 +- 2 files changed, 1 insertion(+), 15 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index d8f18dc1..2c4dd333 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1419,20 +1419,6 @@ def to_time # Serialization # --------------------------------------------------------------------------- - # :nodoc: - def initialize_copy(other) - # Assign every ivar in the canonical order so copies share the same shape - # as freshly constructed instances (see #initialize). This stays an explicit - # copy rather than delegating to #initialize: DateTime overrides #initialize - # with an incompatible (year, month, day, ...) signature, so a shared - # initialize_copy must not dispatch through it. - @jd = other.instance_variable_get(:@jd) - @start = other.instance_variable_get(:@start) - @year = other.instance_variable_get(:@year) - @month = other.instance_variable_get(:@month) - @day = other.instance_variable_get(:@day) - end - # :nodoc: def marshal_dump # 6-element format: [nth, jd, df, sf, of, sg]. A Date has no day fraction, diff --git a/test/date/test_date_new.rb b/test/date/test_date_new.rb index b839c528..2c965e9b 100644 --- a/test/date/test_date_new.rb +++ b/test/date/test_date_new.rb @@ -351,7 +351,7 @@ def test_memsize require 'objspace' t = DateTime.now size = ObjectSpace.memsize_of(t) - t.__send__(:initialize_copy, Date.today) + t.__send__(:initialize_copy, DateTime.now) assert_instance_of(DateTime, t) assert_equal(size, ObjectSpace.memsize_of(t), "not reallocated but memsize changed") end From 84b854a1336bb4c89c377d2393c23f722fa95d05 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 15:29:29 -0700 Subject: [PATCH 080/144] Make Date.new_from_jd an alias of Class#new This is simpler and more efficient. --- lib/date/core.rb | 12 +++--------- 1 file changed, 3 insertions(+), 9 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 2c4dd333..5e115441 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -38,6 +38,9 @@ def civil(year = -4712, month = 1, day = 1, start = ITALY) civil_fallback(year, month, day, start) end + alias_method :new_from_jd, :new + private :new_from_jd + # call-seq: # Date.new(year = -4712, month = 1, mday = 1, start = Date::ITALY) -> date # @@ -564,15 +567,6 @@ def internal_valid_commercial?(y, w, d, sg) # Internal object factory # --------------------------------------------------------------------------- - # Build a Date from a Julian Day Number and start. When the civil fields - # are already known (e.g. the Date.new fast path), pass them so the new - # instance can cache them instead of recomputing from the Julian Day. - def new_from_jd(jd, sg, year = nil, month = nil, day = nil) - obj = allocate - obj.__send__(:initialize, jd, sg, year, month, day) - obj - end - # Parse offset string like "+09:00", "-07:30", "Z" to seconds. def offset_str_to_sec(str) # Use the full date_zone_to_diff port so named zones (JST, PST, ...), From a638c1b3a5a1868b5490e49f9530c8748a0411b5 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 15:29:56 -0700 Subject: [PATCH 081/144] Remove mention of DateTime in Date#sec_fraction documentation/comments --- lib/date/core.rb | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 5e115441..013d1248 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -775,14 +775,12 @@ def cwyear # day_fraction -> 0 # # Returns +0+; a \Date has no fractional day component. - # (DateTime#day_fraction returns the fractional part of the day.) # # Date.new(2001, 2, 3).day_fraction # => 0 - # DateTime.new(2001, 2, 3, 12).day_fraction # => (1/2) # def day_fraction # Date designates a whole day and has no fractional component, so this is - # always 0 (an Integer). DateTime overrides this with its own value. + # always 0 (an Integer). 0 end From 114e5ce4d211cfc6b30eab27e85b6b26d78c4966 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 15:31:21 -0700 Subject: [PATCH 082/144] Remove unnecessary String#encode calls in DateTime The file uses `encoding: US-ASCII`, so these literals already had US_ASCII encoding. --- lib/date/datetime.rb | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 2179e029..7d6a345c 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -129,7 +129,7 @@ def zone abs = @of.abs h = abs / 3600 m = (abs % 3600) / 60 - format('%s%02d:%02d'.encode(Encoding::US_ASCII), sign, h, m) + format('%s%02d:%02d', sign, h, m) end # call-seq: @@ -280,7 +280,7 @@ def new_offset(of = 0) # # For other formats, # see {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]: - def strftime(format = '%FT%T%:z'.encode(Encoding::US_ASCII)) + def strftime(format = '%FT%T%:z') super(format) end @@ -423,7 +423,7 @@ def deconstruct_keys(keys) # DateTime.new(2001,2,3,4,5,6,'-7').to_s # #=> "2001-02-03T04:05:06-07:00" def to_s - strftime('%Y-%m-%dT%H:%M:%S%:z'.encode(Encoding::US_ASCII)) + strftime('%Y-%m-%dT%H:%M:%S%:z') end # call-seq: From 36d579d6d9b5646064b6741888384e07df742ed3 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 15:32:21 -0700 Subject: [PATCH 083/144] Freeze DateTime::UNSET private constant --- lib/date/datetime.rb | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 7d6a345c..8f58b5ab 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -5,7 +5,7 @@ class DateTime < Date # Sentinel marking an hour/minute/second argument that was not passed, so a # trailing fraction can be rejected only when a smaller unit was actually given. - UNSET = Object.new + UNSET = Object.new.freeze private_constant :UNSET # --------------------------------------------------------------------------- From 3cd2bfe66db4c0f6156da64396590f16156bedc5 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 15:33:06 -0700 Subject: [PATCH 084/144] Make DateTime.new the same as Class.new This is simpler and performs better. --- lib/date/datetime.rb | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 8f58b5ab..be84c723 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -544,11 +544,7 @@ def to_time # --------------------------------------------------------------------------- class << self - def new(*args) - instance = allocate - instance.__send__(:initialize, *args) - instance - end + define_method(:new, Class.instance_method(:new)) alias_method :civil, :new undef_method :today From fc0f2f512dc26f0f2770d1bda982615bc19bf985 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 15:34:29 -0700 Subject: [PATCH 085/144] Rename DateTime#_parse_of to #_parse_offset The method is private and didn't exist in the C implementation. --- lib/date/datetime.rb | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index be84c723..b2368309 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -24,7 +24,7 @@ def initialize(year = -4712, month = 1, day = 1, hour = UNSET, minute = UNSET, s # Validate argument types in the C extension's order (offset, then second # down to year) so the same field is reported first when several are bad. - of_sec = self.class.__send__(:_parse_of, offset) + of_sec = self.class.__send__(:_parse_offset, offset) raise TypeError, "invalid second (not numeric)" unless second.is_a?(Numeric) raise TypeError, "invalid minute (not numeric)" unless minute.is_a?(Numeric) raise TypeError, "invalid hour (not numeric)" unless hour.is_a?(Numeric) @@ -256,7 +256,7 @@ def new_start(start = Date::ITALY) # #=> # # d.new_offset('+09:00') #=> # def new_offset(of = 0) - of_sec = self.class.__send__(:_parse_of, of) + of_sec = self.class.__send__(:_parse_offset, of) # Keep the same absolute instant, re-expressed in the new offset: shift the # locally stored wall-clock fields by the change in offset. total = @jd * 86400 + @hour * 3600 + @min * 60 + @sec + (of_sec - @of) @@ -607,7 +607,7 @@ def jd(jd = 0, hour = UNSET, minute = UNSET, second = UNSET, offset = 0, start = second_given = !UNSET.equal?(second); second = 0 if UNSET.equal?(second) # Validate in the C extension's order (offset, second, minute, hour, jd). - of_sec = _parse_of(offset) + of_sec = _parse_offset(offset) _check_hms_types(hour, minute, second) raise TypeError, "invalid jd (not numeric)" unless jd.is_a?(Numeric) @@ -634,7 +634,7 @@ def ordinal(year = -4712, yday = 1, hour = UNSET, minute = UNSET, second = UNSET second_given = !UNSET.equal?(second); second = 0 if UNSET.equal?(second) # Validate in the C extension's order (offset, second, minute, hour, yday, year). - of_sec = _parse_of(offset) + of_sec = _parse_offset(offset) _check_hms_types(hour, minute, second) raise TypeError, "invalid yday (not numeric)" unless yday.is_a?(Numeric) raise TypeError, "invalid year (not numeric)" unless year.is_a?(Numeric) @@ -664,7 +664,7 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, hour = UNSET, minute = UNSE # Validate in the C extension's order (offset, second, minute, hour, # cwday, cweek, cwyear). - of_sec = _parse_of(offset) + of_sec = _parse_offset(offset) _check_hms_types(hour, minute, second) raise TypeError, "invalid cwday (not numeric)" unless cwday.is_a?(Numeric) raise TypeError, "invalid cweek (not numeric)" unless cweek.is_a?(Numeric) @@ -920,7 +920,7 @@ def _dt_new_by_frags(hash, sg) _new_dt_from_jd_time(jd, h, m, s, sf, of, sg) end - def _parse_of(offset) + def _parse_offset(offset) case offset when String Date.__send__(:offset_str_to_sec, offset) From 76d65760130068590855dbb4152d906449ccf095 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 15:38:41 -0700 Subject: [PATCH 086/144] Replace some DateTime private method definitions with equivalent aliases --- lib/date/datetime.rb | 24 +++++------------------- 1 file changed, 5 insertions(+), 19 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index b2368309..d835253d 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -982,30 +982,16 @@ def _num_to_int(n) "no implicit conversion of #{n.class} into Integer" end - def internal_hour - @hour - end - - def internal_min - @min - end - - def internal_sec - @sec - end - - def sec_frac - @sec_fraction - end + alias internal_hour hour + alias internal_min min + alias internal_sec sec + alias sec_frac sec_fraction + alias zone_str zone def of_seconds @of end - def zone_str - zone - end - # Overrides of the Date strftime time-part helpers (see Date#strftime_hms): # a DateTime renders its actual time instead of the Date literals. def strftime_hms From 6c8a8440e90fcd2caf0ccac149aed35bf2d7fa14 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 15:39:40 -0700 Subject: [PATCH 087/144] Remove unnecessary comment line --- lib/date/strftime.rb | 1 - 1 file changed, 1 deletion(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index a29949fb..f14b57d0 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -372,7 +372,6 @@ def format_spec_b(spec, flags, colons, width) when 37 # '%' fmt_str('%', width, flags) else - # Try composite (includes '+', see STRFTIME_COMPOSITE_BYTE) expansion = STRFTIME_COMPOSITE_BYTE[spec] if expansion s = internal_strftime(expansion) From 0ff4b7f880dadb093289f09fc3847ca106163f8c Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 15:48:33 -0700 Subject: [PATCH 088/144] Drop usage of DEFAULT_STRFTIME_FMT/YMD_FMT constants These were only used in Date#strftime. To handle the no-argument case, we can return from the default argument value and skip the method body. This is the only case where it is safe to optimize, as other cases need to check the encoding of the format string and match it. Drop the specialized handling for `%Y-%m-%d`, as it always returned US-ASCII encoding, while the C extension returns the encoding of the format string. --- lib/date/constants.rb | 6 ------ lib/date/strftime.rb | 17 +++-------------- test/date/test_date_strftime.rb | 8 ++++++++ 3 files changed, 11 insertions(+), 20 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 12f0f67f..8ed5bfa3 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -96,12 +96,6 @@ class Date # === String formatting (from strftime.rb) === - DEFAULT_STRFTIME_FMT = '%F' - private_constant :DEFAULT_STRFTIME_FMT - - YMD_FMT = '%Y-%m-%d' - private_constant :YMD_FMT - # Pre-computed "Sun Jan " prefix table for %c / asctime [wday][month] ASCTIME_PREFIX = Array.new(7) { |w| Array.new(13) { |m| diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index f14b57d0..e41f0daa 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -19,20 +19,9 @@ class Date # # For other formats, see # {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]. - def strftime(format = DEFAULT_STRFTIME_FMT) - if format.equal?(DEFAULT_STRFTIME_FMT) - internal_civil unless @year - result = fast_ymd.force_encoding(Encoding::US_ASCII) - fmt = DEFAULT_STRFTIME_FMT - else - fmt = format.to_str - if fmt == YMD_FMT - internal_civil unless @year - result = fast_ymd.force_encoding(Encoding::US_ASCII) - else - result = internal_strftime(fmt).force_encoding(fmt.encoding) - end - end + def strftime(format = nil || (return iso8601)) + fmt = format.to_str + result = internal_strftime(fmt).force_encoding(fmt.encoding) # The C extension formats into an output buffer that grows 1024, 2048, ... # and gives up with Errno::ERANGE once the buffer would reach 1024 * flen # (flen = format string length) while still not fitting. The effective diff --git a/test/date/test_date_strftime.rb b/test/date/test_date_strftime.rb index 6ad69c0c..24de349b 100644 --- a/test/date/test_date_strftime.rb +++ b/test/date/test_date_strftime.rb @@ -181,6 +181,14 @@ def test_strftime__4 assert_equal(so, d.strftime(f)) end + def test_strftime_ymd_encoding + d = Date.new(2000) + a = "%Y-%m-%d" + [Encoding::BINARY, Encoding::US_ASCII, Encoding::UTF_8, Encoding::ISO8859_1].each do |enc| + assert_equal(enc, d.strftime(a.encode(enc)).encoding) + end + end + def test_strftime__offset s = '2006-08-08T23:15:33' (-24..24).collect{|x| '%+.2d' % x}.each do |hh| From be6ff07b55fd24ae700075a430f1006c67f6eb00 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 16:18:41 -0700 Subject: [PATCH 089/144] Move Errno::ERANGE raising in strftime There is no point in raising after the format string has already been calculated. Move it inside the year check so that we raise before calculating. --- lib/date/strftime.rb | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index e41f0daa..b53078cc 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -21,17 +21,7 @@ class Date # {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]. def strftime(format = nil || (return iso8601)) fmt = format.to_str - result = internal_strftime(fmt).force_encoding(fmt.encoding) - # The C extension formats into an output buffer that grows 1024, 2048, ... - # and gives up with Errno::ERANGE once the buffer would reach 1024 * flen - # (flen = format string length) while still not fitting. The effective - # limit is thus the smallest 1024 * 2**k that is >= 1024 * flen, i.e. - # 1024 << ceil(log2(flen)); output whose byte length reaches it raises. - # The limit is always >= 1024, so skip the check entirely for shorter output. - if result.bytesize >= 1024 - raise Errno::ERANGE, "strftime" if result.bytesize >= 1024 << (fmt.bytesize - 1).bit_length - end - result + internal_strftime(fmt).force_encoding(fmt.encoding) end private @@ -192,6 +182,7 @@ def fast_spec(spec) when 89 # 'Y' internal_civil unless @year y = @year + check_fmt_year(y) if y >= 1000 y.to_s elsif y >= 0 @@ -371,8 +362,19 @@ def format_spec_b(spec, flags, colons, width) end end + ALLOWED_FMT_YEAR_RANGE = (-(1 << 6796))...(1 << 6800) + private_constant :ALLOWED_FMT_YEAR_RANGE + + def check_fmt_year(y) + unless ALLOWED_FMT_YEAR_RANGE.cover?(y) + raise Errno::ERANGE, "Numerical result out of range" + end + end + # Format year (handles negative years and all flag variants) def fmt_year(y, width, flags) + check_fmt_year(y) + # The result is always numeric (digits with an optional leading '-'), so the # upper/chcase flags are no-ops and need no handling here. sign = y < 0 ? '-' : '' From 6b33e9283ff3829b3fba1607c0578a9d0a2a4f9e Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 16:40:55 -0700 Subject: [PATCH 090/144] Have Date#{year,month,day} check for necessary instance variable first In the common case, this is 1 instance variable access and not 2. --- lib/date/core.rb | 9 +++------ 1 file changed, 3 insertions(+), 6 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 013d1248..4ee7ca95 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -591,8 +591,7 @@ def offset_str_to_sec(str) # (Date.new(1, 1, 1) - 1).year # => 0 # def year - internal_civil unless @year - @year + @year || (internal_civil; @year) end # call-seq: @@ -603,8 +602,7 @@ def year # Date.new(2001, 2, 3).mon # => 2 # def month - internal_civil unless @year - @month + @month || (internal_civil; @month) end alias mon month @@ -616,8 +614,7 @@ def month # Date.new(2001, 2, 3).mday # => 3 # def day - internal_civil unless @year - @day + @day || (internal_civil; @day) end alias mday day From 74a834c29a88aec37ebd0da5e70bb17bb54426d6 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 16:45:18 -0700 Subject: [PATCH 091/144] Avoid internal_civil unless @year At the top of internal_civil, we exit early if @year is set, so conditionals around the call are redundant. I'm guessing it was done for performance, as the instance variable check + conditional can be cheaper than the method call in the common case. However, I don't think it's worth the code cluttering. In strftime, call internal_civil once at the start of the method, and remove all the checks inside. --- lib/date/core.rb | 14 +++++++------- lib/date/strftime.rb | 16 +--------------- 2 files changed, 8 insertions(+), 22 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 4ee7ca95..06cd900d 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -713,7 +713,7 @@ def ld # Date.new(2001, 2, 3).yday # => 34 # def yday - internal_civil unless @year + internal_civil jd_jan1 = self.class.__send__(:civil_to_jd, @year, 1, 1, @start) @jd - jd_jan1 + 1 end @@ -790,7 +790,7 @@ def day_fraction # Date.new(2001).leap? # => false # def leap? - internal_civil unless @year + internal_civil if @jd < @start # julian? @year % 4 == 0 else @@ -1138,7 +1138,7 @@ def >>(n) # last day of the target month (using the calendar that applies under the # cutover). Shared with DateTime#>> so the time of day can be preserved. private def month_shifted_jd(n) - internal_civil unless @year + internal_civil m2 = @month + n.to_i y2 = @year + (m2 - 1).div(12) m2 = (m2 - 1) % 12 + 1 @@ -1515,7 +1515,7 @@ def deconstruct_keys(keys) # See {asctime}[https://linux.die.net/man/3/asctime]. # def asctime - internal_civil unless @year + internal_civil d = @day d_s = d < 10 ? " #{d}" : d.to_s y = @year @@ -1550,7 +1550,7 @@ def rfc3339 # Date.new(2001, 2, 3).rfc2822 # => "Sat, 3 Feb 2001 00:00:00 +0000" # def rfc2822 - internal_civil unless @year + internal_civil w = (@jd + 1) % 7 y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) @@ -1571,7 +1571,7 @@ def rfc2822 # Date.new(2001, 2, 3).httpdate # => "Sat, 03 Feb 2001 00:00:00 GMT" # def httpdate - internal_civil unless @year + internal_civil w = (@jd + 1) % 7 y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) @@ -1591,7 +1591,7 @@ def httpdate # Date.new(2001, 2, 3).jisx0301 # => "H13.02.03" # def jisx0301 - internal_civil unless @year + internal_civil jd = @jd m = @month d = @day diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index b53078cc..09fad90e 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -21,6 +21,7 @@ class Date # {Formats for Dates and Times}[rdoc-ref:language/strftime_formatting.rdoc]. def strftime(format = nil || (return iso8601)) fmt = format.to_str + internal_civil internal_strftime(fmt).force_encoding(fmt.encoding) end @@ -30,23 +31,18 @@ def internal_strftime(fmt) # Fast path for common format strings (whole-string match) case fmt when '%Y-%m-%d', '%F' - internal_civil unless @year return fast_ymd when '%H:%M:%S', '%T', '%X' # +: this becomes the result string, which #strftime force_encodes in # place, so it must be mutable (strftime_hms may be a frozen literal). return +strftime_hms when '%m/%d/%y', '%D', '%x' - internal_civil unless @year return "#{PAD2[@month]}/#{PAD2[@day]}/#{PAD2[@year % 100]}" when '%Y-%m-%dT%H:%M:%S%z' - internal_civil unless @year return "#{fast_ymd}T#{strftime_hms}#{strftime_zoff}" when '%a %b %e %H:%M:%S %Y', '%c' - internal_civil unless @year return fmt_asctime_str when '%A, %B %d, %Y' - internal_civil unless @year w = (@jd + 1) % 7 y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) @@ -180,7 +176,6 @@ def fmt_asctime_str def fast_spec(spec) case spec when 89 # 'Y' - internal_civil unless @year y = @year check_fmt_year(y) if y >= 1000 @@ -191,13 +186,10 @@ def fast_spec(spec) format('-%04d', -y) end when 109 # 'm' - internal_civil unless @year PAD2[@month] when 100 # 'd' - internal_civil unless @year PAD2[@day] when 101 # 'e' - internal_civil unless @year d = @day d < 10 ? " #{d}" : d.to_s when 72 # 'H' @@ -211,10 +203,8 @@ def fast_spec(spec) when 65 # 'A' DAYNAMES[(@jd + 1) % 7] when 98, 104 # 'b', 'h' - internal_civil unless @year ABBR_MONTHNAMES[@month] when 66 # 'B' - internal_civil unless @year MONTHNAMES[@month] when 112 # 'p' internal_hour < 12 ? 'AM' : 'PM' @@ -240,7 +230,6 @@ def fast_spec(spec) when 117 # 'u' cwday.to_s when 121 # 'y' - internal_civil unless @year PAD2[@year % 100] when 90 # 'Z' zone_str @@ -250,15 +239,12 @@ def fast_spec(spec) ((@jd - 2440588) * 86400 - of_seconds + internal_hour * 3600 + internal_min * 60 + internal_sec).to_s # Composite specs — inline expansion when 99 # 'c' - internal_civil unless @year fmt_asctime_str when 70 # 'F' - internal_civil unless @year fast_ymd when 84, 88 # 'T', 'X' strftime_hms when 68, 120 # 'D', 'x' - internal_civil unless @year "#{PAD2[@month]}/#{PAD2[@day]}/#{PAD2[@year % 100]}" when 82 # 'R' strftime_hm From 78e2301719baa6a4b78dcd456b1c6d3ff9a22512 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 17:00:30 -0700 Subject: [PATCH 092/144] Inline strptime constants used in a single place --- lib/date/strptime.rb | 27 ++++++++++----------------- 1 file changed, 10 insertions(+), 17 deletions(-) diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index 4f3dc185..cca018a6 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -108,33 +108,25 @@ def to_string_value(obj) # Pre-compiled regex constants for sp_run SP_WHITESPACE = /[ \t\n\r\v\f]+/ - SP_COLONS = /:+/ SP_EO_CHECK = /[EO]/ - SP_E_COMBO = /E[cCxXyY]/ - SP_O_COMBO = /O[deHImMSuUVwWy]/ SP_ALPHA3 = /[A-Za-z]{3}/ - SP_SIGN = /[+-]/ SP_SPACE_OR_DIGIT = / \d|\d{1,2}/ - SP_AMPM_DOT = /[AaPp]\.[Mm]\./ - SP_AMPM = /[AaPp][Mm]/ SP_NUM_CHECK = /\d|%[EO]?[CDdeFGgHIjkLlMmNQRrSsTUuVvWwXxYy0-9]/ SP_DIGITS_1 = /\d/ SP_DIGITS_2 = /\d{1,2}/ SP_DIGITS_3 = /\d{1,3}/ SP_DIGITS_4 = /\d{1,4}/ - SP_DIGITS_9 = /\d{1,9}/ SP_DIGITS_MAX = /\d+/ - private_constant :SP_WHITESPACE, :SP_COLONS, :SP_EO_CHECK, :SP_E_COMBO, - :SP_O_COMBO, :SP_ALPHA3, :SP_SIGN, :SP_SPACE_OR_DIGIT, - :SP_AMPM_DOT, :SP_AMPM, :SP_NUM_CHECK, + private_constant :SP_WHITESPACE, :SP_EO_CHECK, :SP_ALPHA3, + :SP_SPACE_OR_DIGIT, :SP_NUM_CHECK, :SP_DIGITS_1, :SP_DIGITS_2, :SP_DIGITS_3, :SP_DIGITS_4, - :SP_DIGITS_9, :SP_DIGITS_MAX + :SP_DIGITS_MAX # Scan an optional leading sign, returning -1 for '-' and 1 otherwise # (a '+' or no sign at all). When no sign is present the scanner is left - # untouched, since SP_SIGN does not match and #scan does not advance. + # untouched. def sp_scan_sign(sc) - sc.scan(SP_SIGN) == '-' ? -1 : 1 + sc.scan(/[+-]/) == '-' ? -1 : 1 end # Convert an already-scanned numeric field, validate it against an inclusive @@ -172,7 +164,7 @@ def sp_run(str, si, fmt, hash) fmt_sc.skip(/%/) # skip '%' # Handle colon modifiers: %:z, %::z, %:::z - if fmt_sc.scan(SP_COLONS) + if fmt_sc.scan(/:+/) throw(:sp_fail) unless fmt_sc.skip(/z/) str_sc.pos = sp_zone(str, str_sc.pos, str.bytesize, hash) next @@ -180,7 +172,8 @@ def sp_run(str, si, fmt, hash) # Handle E/O locale modifiers if fmt_sc.check(SP_EO_CHECK) - if fmt_sc.check(SP_E_COMBO) || fmt_sc.check(SP_O_COMBO) + + if fmt_sc.check(/E[cCxXyY]/) || fmt_sc.check(/O[deHImMSuUVwWy]/) fmt_sc.skip(SP_EO_CHECK) # skip modifier, fall through to spec else # Invalid combo: match '%' literally in string @@ -285,7 +278,7 @@ def sp_run(str, si, fmt, hash) sign = sp_scan_sign(str_sc) osi = str_sc.pos num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) - s = str_sc.scan(num_next ? SP_DIGITS_9 : SP_DIGITS_MAX) + s = str_sc.scan(num_next ? /\d{1,9}/ : SP_DIGITS_MAX) throw(:sp_fail) unless s n = s.to_i n = -n if sign == -1 @@ -304,7 +297,7 @@ def sp_run(str, si, fmt, hash) else throw(:sp_fail) end - unless str_sc.scan(SP_AMPM_DOT) || str_sc.scan(SP_AMPM) + unless str_sc.scan(/[AaPp]\.[Mm]\./) || str_sc.scan(/[AaPp][Mm]/) throw(:sp_fail) end hash[:_merid] = merid From 35b6d276379c4f42d2261a50566b1d3e6f0861d9 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 17:11:14 -0700 Subject: [PATCH 093/144] Combine fast/medium paths in internal_strptime_ymd Also, inline regexp constants used in a single place. --- lib/date/strptime.rb | 34 ++++++---------------------------- 1 file changed, 6 insertions(+), 28 deletions(-) diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index cca018a6..664096d8 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -395,39 +395,23 @@ def sp_run(str, si, fmt, hash) str_sc.pos end - # Fast path for %Y-%m-%d / %F format. - # Uses match? + byteslice to avoid StringScanner allocation overhead. - STRPTIME_YMD_EXACT = /\A\d{4}-\d{2}-\d{2}\z/ - STRPTIME_YMD_PREFIX = /\A\d{4}-\d{2}-\d{2}/ - STRPTIME_YMD_GENERAL = /\A([+-]?\d+)-(\d{1,2})-(\d{1,2})(.*)\z/m - private_constant :STRPTIME_YMD_EXACT, :STRPTIME_YMD_PREFIX, :STRPTIME_YMD_GENERAL - def internal_strptime_ymd(str) slen = str.bytesize - # Fast path for "YYYY-MM-DD" (exactly 10 chars) - if slen == 10 && STRPTIME_YMD_EXACT.match?(str) - year = str.byteslice(0, 4).to_i - mon = str.byteslice(5, 2).to_i - mday = str.byteslice(8, 2).to_i - return nil if mon < 1 || mon > 12 || mday < 1 || mday > 31 - return { year: year, mon: mon, mday: mday } - end - - # Medium path for "YYYY-MM-DD..." (10+ chars, standard 4-digit year with leftover) - if slen > 10 && STRPTIME_YMD_PREFIX.match?(str) + # Fast path for "YYYY-MM-DD..." (>= 10 chars, standard 4-digit year with possible leftover) + if slen >= 10 && /\A\d{4}-\d{2}-\d{2}/.match?(str) year = str.byteslice(0, 4).to_i mon = str.byteslice(5, 2).to_i mday = str.byteslice(8, 2).to_i if mon >= 1 && mon <= 12 && mday >= 1 && mday <= 31 hash = { year: year, mon: mon, mday: mday } - hash[:leftover] = str.byteslice(10..) + hash[:leftover] = str.byteslice(10..) if str.length > 10 return hash end end # General path for signed years, short years, etc. - m = STRPTIME_YMD_GENERAL.match(str) + m = /\A([+-]?\d+)-(\d{1,2})-(\d{1,2})(.*)\z/m.match(str) return nil unless m year = m[1].to_i mon = m[2].to_i @@ -439,17 +423,11 @@ def internal_strptime_ymd(str) hash end - # Parse %Y-%m-%d and directly create Date object. - # Returns Date object on success, nil on failure. - # Uses match? + byteslice to avoid StringScanner allocation overhead. - STRPTIME_YMD_GENERAL_EXACT = /\A([+-]?\d+)-(\d{1,2})-(\d{1,2})\z/ - private_constant :STRPTIME_YMD_GENERAL_EXACT - def internal_strptime_ymd_to_date(str, sg) slen = str.bytesize # Fast path for exactly "YYYY-MM-DD" (10 chars, positive 4-digit year) - if slen == 10 && STRPTIME_YMD_EXACT.match?(str) + if slen == 10 && /\A\d{4}-\d{2}-\d{2}\z/.match?(str) year = str.byteslice(0, 4).to_i mon = str.byteslice(5, 2).to_i mday = str.byteslice(8, 2).to_i @@ -461,7 +439,7 @@ def internal_strptime_ymd_to_date(str, sg) end # General path for signed years, non-standard lengths - m = STRPTIME_YMD_GENERAL_EXACT.match(str) + m = /\A([+-]?\d+)-(\d{1,2})-(\d{1,2})\z/.match(str) return nil unless m year = m[1].to_i mon = m[2].to_i From 0753a9796353638f41b518e4f5528c8f56f7b2c7 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 17:25:52 -0700 Subject: [PATCH 094/144] Cache @day_fraction for DateTime The initializer initializes the instance variable to nil, but it was never set, which makes no sense. --- lib/date/datetime.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index d835253d..c2a5b647 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -132,6 +132,11 @@ def zone format('%s%02d:%02d', sign, h, m) end + def freeze + day_fraction + super + end + # call-seq: # day_fraction -> rational # @@ -139,7 +144,7 @@ def zone # # DateTime.new(2001,2,3,12).day_fraction # => (1/2) def day_fraction - Rational(@hour * 3600 + @min * 60 + @sec, 86400) + + @day_fraction ||= Rational(@hour * 3600 + @min * 60 + @sec, 86400) + Rational(@sec_fraction.numerator, @sec_fraction.denominator * 86400) end From 418de0bfeac026651c30d4eb0153e52daf24aba1 Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 17:27:25 -0700 Subject: [PATCH 095/144] Inline DateTime#_from_total_sec_r into only caller --- lib/date/datetime.rb | 23 +++++++++-------------- 1 file changed, 9 insertions(+), 14 deletions(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index c2a5b647..a65d4d91 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -186,7 +186,15 @@ def +(other) # other is days (may be fractional) - add as seconds extra_sec = other.to_r * 86400 total_r = Rational(@jd) * 86400 + @hour * 3600 + @min * 60 + @sec + @sec_fraction + extra_sec - _from_total_sec_r(total_r) + jd = (total_r / 86400).floor + rem = total_r - jd * 86400 + h = rem.to_i / 3600 + rem -= h * 3600 + m = rem.to_i / 60 + s_r = rem - m * 60 + s_i = s_r.floor + s_f = s_r - s_i + self.class.__send__(:_new_dt_from_jd_time,jd, h, m, s_i, s_f, @of, @start) when Numeric r = other.to_r raise TypeError, "#{other.class} can't be coerced into Integer" unless r.is_a?(Rational) @@ -1047,17 +1055,4 @@ def _split_second(second) [Integer(second), 0r] end end - - def _from_total_sec_r(total_r) - jd = (total_r / 86400).floor - rem = total_r - jd * 86400 - h = rem.to_i / 3600 - rem -= h * 3600 - m = rem.to_i / 60 - s_r = rem - m * 60 - s_i = s_r.floor - s_f = s_r - s_i - self.class.__send__(:_new_dt_from_jd_time,jd, h, m, s_i, s_f, @of, @start) - end - end From 9a88d8b38ab1886d39b645b1fd00a2d03689deff Mon Sep 17 00:00:00 2001 From: Jeremy Evans Date: Sat, 24 Oct 2026 17:31:42 -0700 Subject: [PATCH 096/144] Fix call-seq formatting issues No need to use [], as the default argument value implies the argument is not required. --- lib/date/core.rb | 2 +- lib/date/datetime.rb | 40 ++++++++++++++++++++-------------------- 2 files changed, 21 insertions(+), 21 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 06cd900d..4548be1a 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -825,7 +825,7 @@ def julian? end # call-seq: - # new_start(start = Date::ITALY]) -> new_date + # new_start(start = Date::ITALY) -> new_date # # Returns a copy of +self+ with the given +start+ value: # diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index a65d4d91..75594e9e 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -246,7 +246,7 @@ def >>(n) end # call-seq: - # new_start(start = Date::ITALY]) -> new_date + # new_start(start = Date::ITALY) -> new_date # # Returns a copy of +self+ with the given +start+ value: # @@ -261,7 +261,7 @@ def new_start(start = Date::ITALY) end # call-seq: - # d.new_offset([offset=0]) -> date + # d.new_offset(offset=0) -> date # # Duplicates self and resets its offset. # @@ -298,7 +298,7 @@ def strftime(format = '%FT%T%:z') end # call-seq: - # dt.jisx0301([n=0]) -> string + # dt.jisx0301(n=0) -> string # # Returns a string in a JIS X 0301 format. # The optional argument +n+ is the number of digits for fractional seconds. @@ -325,8 +325,8 @@ def jisx0301(n = 0) end # call-seq: - # dt.iso8601([n=0]) -> string - # dt.xmlschema([n=0]) -> string + # dt.iso8601(n=0) -> string + # dt.xmlschema(n=0) -> string # # This method is equivalent to strftime('%FT%T%:z'). # The optional argument +n+ is the number of digits for fractional seconds. @@ -346,7 +346,7 @@ def iso8601(n = 0) alias_method :xmlschema, :iso8601 # call-seq: - # dt.rfc3339([n=0]) -> string + # dt.rfc3339(n=0) -> string # # This method is equivalent to strftime('%FT%T%:z'). # The optional argument +n+ is the number of digits for fractional seconds. @@ -563,7 +563,7 @@ class << self undef_method :today # call-seq: - # DateTime._strptime(string[, format='%FT%T%z']) -> hash + # DateTime._strptime(string, format='%FT%T%z') -> hash # # Parses the given representation of date and time with the given # template, and returns a hash of parsed elements. _strptime does @@ -575,7 +575,7 @@ def _strptime(string, format = '%FT%T%z') end # call-seq: - # DateTime.strptime([string='-4712-01-01T00:00:00+00:00'[, format='%FT%T%z'[ ,start=Date::ITALY]]]) -> datetime + # DateTime.strptime(string='-4712-01-01T00:00:00+00:00', format='%FT%T%z' ,start=Date::ITALY) -> datetime # # Parses the given representation of date and time with the given # template, and creates a DateTime object. strptime does not support @@ -605,7 +605,7 @@ def strptime(string = '-4712-01-01T00:00:00+00:00', format = '%FT%T%z', start = end # call-seq: - # DateTime.jd([jd=0[, hour=0[, minute=0[, second=0[, offset=0[, start=Date::ITALY]]]]]]) -> datetime + # DateTime.jd(jd=0, hour=0, minute=0, second=0, offset=0, start=Date::ITALY) -> datetime # # Creates a DateTime object denoting the given chronological Julian # day number. @@ -632,7 +632,7 @@ def jd(jd = 0, hour = UNSET, minute = UNSET, second = UNSET, offset = 0, start = end # call-seq: - # DateTime.ordinal([year=-4712[, yday=1[, hour=0[, minute=0[, second=0[, offset=0[, start=Date::ITALY]]]]]]]) -> datetime + # DateTime.ordinal(year=-4712, yday=1, hour=0, minute=0, second=0, offset=0, start=Date::ITALY) -> datetime # # Creates a DateTime object denoting the given ordinal date. # @@ -662,7 +662,7 @@ def ordinal(year = -4712, yday = 1, hour = UNSET, minute = UNSET, second = UNSET end # call-seq: - # DateTime.commercial([cwyear=-4712[, cweek=1[, cwday=1[, hour=0[, minute=0[, second=0[, offset=0[, start=Date::ITALY]]]]]]]]) -> datetime + # DateTime.commercial(cwyear=-4712, cweek=1, cwday=1, hour=0, minute=0, second=0, offset=0, start=Date::ITALY) -> datetime # # Creates a DateTime object denoting the given week date. # @@ -693,7 +693,7 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, hour = UNSET, minute = UNSE end # call-seq: - # DateTime.now([start=Date::ITALY]) -> datetime + # DateTime.now(start=Date::ITALY) -> datetime # # Creates a DateTime object denoting the present time. # @@ -765,7 +765,7 @@ def _build_dt_folded(jd_i, date_frac, hour, minute, second, of_sec, start) end # call-seq: - # DateTime.parse(string='-4712-01-01T00:00:00+00:00'[, comp=true[, start=Date::ITALY]], limit: 128) -> datetime + # DateTime.parse(string='-4712-01-01T00:00:00+00:00', comp=true, start=Date::ITALY, limit: 128) -> datetime # # Parses the given representation of date and time, and creates a # DateTime object. @@ -794,7 +794,7 @@ def parse(string = '-4712-01-01T00:00:00+00:00', comp = true, start = Date::ITAL end # call-seq: - # DateTime.iso8601(string='-4712-01-01T00:00:00+00:00'[, start=Date::ITALY], limit: 128) -> datetime + # DateTime.iso8601(string='-4712-01-01T00:00:00+00:00', start=Date::ITALY, limit: 128) -> datetime # # Creates a new DateTime object by parsing from a string according to # some typical ISO 8601 formats. @@ -815,7 +815,7 @@ def iso8601(string = '-4712-01-01T00:00:00+00:00', start = Date::ITALY, limit: 1 end # call-seq: - # DateTime.rfc3339(string='-4712-01-01T00:00:00+00:00'[, start=Date::ITALY], limit: 128) -> datetime + # DateTime.rfc3339(string='-4712-01-01T00:00:00+00:00', start=Date::ITALY, limit: 128) -> datetime # # Creates a new DateTime object by parsing from a string according to # some typical RFC 3339 formats. @@ -832,7 +832,7 @@ def rfc3339(string = '-4712-01-01T00:00:00+00:00', start = Date::ITALY, limit: 1 end # call-seq: - # DateTime.xmlschema(string='-4712-01-01T00:00:00+00:00'[, start=Date::ITALY], limit: 128) -> datetime + # DateTime.xmlschema(string='-4712-01-01T00:00:00+00:00', start=Date::ITALY, limit: 128) -> datetime # # Creates a new DateTime object by parsing from a string according to # some typical XML Schema formats. @@ -849,8 +849,8 @@ def xmlschema(string = '-4712-01-01T00:00:00+00:00', start = Date::ITALY, limit: end # call-seq: - # DateTime.rfc2822(string='Mon, 1 Jan -4712 00:00:00 +0000'[, start=Date::ITALY], limit: 128) -> datetime - # DateTime.rfc822(string='Mon, 1 Jan -4712 00:00:00 +0000'[, start=Date::ITALY], limit: 128) -> datetime + # DateTime.rfc2822(string='Mon, 1 Jan -4712 00:00:00 +0000', start=Date::ITALY, limit: 128) -> datetime + # DateTime.rfc822(string='Mon, 1 Jan -4712 00:00:00 +0000', start=Date::ITALY, limit: 128) -> datetime # # Creates a new DateTime object by parsing from a string according to # some typical RFC 2822 formats. @@ -868,7 +868,7 @@ def rfc2822(string = 'Mon, 1 Jan -4712 00:00:00 +0000', start = Date::ITALY, lim alias rfc822 rfc2822 # call-seq: - # DateTime.httpdate(string='Mon, 01 Jan -4712 00:00:00 GMT'[, start=Date::ITALY]) -> datetime + # DateTime.httpdate(string='Mon, 01 Jan -4712 00:00:00 GMT', start=Date::ITALY) -> datetime # # Creates a new DateTime object by parsing from a string according to # some RFC 2616 format. @@ -885,7 +885,7 @@ def httpdate(string = 'Mon, 01 Jan -4712 00:00:00 GMT', start = Date::ITALY, lim end # call-seq: - # DateTime.jisx0301(string='-4712-01-01T00:00:00+00:00'[, start=Date::ITALY], limit: 128) -> datetime + # DateTime.jisx0301(string='-4712-01-01T00:00:00+00:00', start=Date::ITALY, limit: 128) -> datetime # # Creates a new DateTime object by parsing from a string according to # some typical JIS X 0301 formats. From 02c49055b90898be2cbb8ed4163bc131876c14c9 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 13:15:25 +0900 Subject: [PATCH 097/144] Remove StringScanner fast paths from _rfc3339 and _httpdate Benchmarking (benchmark-ips) shows these hand-rolled StringScanner fast paths add no meaningful speed over the regexp path they short-circuit: _rfc3339 is unchanged and _httpdate gains only ~10-15%, neither of which justifies the extra code and the compute_3key/3KEY-table machinery the httpdate path pulled in. The general RFC3339_RE / HTTPDATE_*_RE paths already handle every case, so removing the fast paths is a pure simplification. Full suite stays green (148 tests, 162629 assertions). Performance (ips; higher is better; C ext = Ruby 4.0.1 system build): method C ext Ruby before Ruby after after/before Date._rfc3339 (off) 488707 290403 287719 0.99x Date._rfc3339 (Z) 488707 360273 364597 1.01x Date._httpdate 403522 341643 291363 0.85x Date.httpdate 320236 215364 194922 0.91x --- lib/date/parse.rb | 43 ------------------------------------------- 1 file changed, 43 deletions(-) diff --git a/lib/date/parse.rb b/lib/date/parse.rb index df6a90b9..08a8f40d 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -31,28 +31,6 @@ def _rfc3339(string, limit: 128) return {} if string.empty? parse_check_limit(string, limit) - # Fast path: YYYY-MM-DDTHH:MM:SS+HH:MM (25 bytes) or YYYY-MM-DDTHH:MM:SSZ (20 bytes) - len = string.length - if len == 25 || len == 20 - sc = StringScanner.new(string) - if sc.scan(/(\d{4})-(\d{2})-(\d{2})[Tt](\d{2}):(\d{2}):(\d{2})/) - h = { - year: sc[1].to_i, mon: sc[2].to_i, mday: sc[3].to_i, - hour: sc[4].to_i, min: sc[5].to_i, sec: sc[6].to_i - } - if sc.scan(/[Zz]\z/) - h[:zone] = sc.matched - h[:offset] = 0 - return h - elsif sc.scan(/([+-])(\d{2}):(\d{2})\z/) - zone = sc.matched - h[:zone] = zone - h[:offset] = (sc[1] == '-' ? -1 : 1) * (sc[2].to_i * 3600 + sc[3].to_i * 60) - return h - end - end - end - h = {} if (m = RFC3339_RE.match(string)) h[:year] = m[1].to_i @@ -97,27 +75,6 @@ def _httpdate(string, limit: 128) return {} if string.empty? parse_check_limit(string, limit) - # Fast path for Type 1: "Dow, DD Mon YYYY HH:MM:SS GMT" (29 bytes) - len = string.length - if len == 29 - sc = StringScanner.new(string) - if sc.scan(/([A-Za-z]{3}), (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) (GMT)\z/i) - wkey = compute_3key(sc[1]) - wday_info = ABBR_DAY_3KEY[wkey] - if wday_info - mkey = compute_3key(sc[3]) - mon_info = ABBR_MONTH_3KEY[mkey] - if mon_info - return { - wday: wday_info[0], mday: sc[2].to_i, mon: mon_info[0], - year: sc[4].to_i, hour: sc[5].to_i, min: sc[6].to_i, sec: sc[7].to_i, - zone: 'GMT', offset: 0 - } - end - end - end - end - h = {} if (m = HTTPDATE_TYPE1_RE.match(string)) h[:wday] = ABBR_DAY_NUM[m[1].downcase] From e16584a45c1626b15a6ad86a0b614ea786c155ef Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 13:39:16 +0900 Subject: [PATCH 098/144] Replace compute_3key integer keys with plain string keys The abbreviated day/month lookup tables were keyed by a bit-packed 3-byte integer built by a dedicated Date.compute_3key helper (the only occupant of lib/date/shared.rb). Benchmarking (benchmark-ips) shows the integer key buys very little over a plain downcased-string key: ~1-9% (largest on Date._rfc2822, low single digits elsewhere), not the kind of margin that justifies a custom key function and an extra source file. Switch ABBR_DAY_3KEY / ABBR_MONTH_3KEY to downcased-string keys (renamed to ABBR_DAY_INFO / ABBR_MONTH_INFO; value stays [index, full_name_length]) and look them up with str.downcase. Delete compute_3key and shared.rb. Behaviour is unchanged; full suite stays green (148 tests, 162629 assertions). Performance (ips; higher is better; C ext = Ruby 4.0.1 system build): method C ext Ruby before Ruby after after/before Date._rfc2822 375805 269000 248000 0.92x Date.rfc2822 304311 184743 175074 0.95x Date._strptime abdy - 419638 405680 0.97x Date.strptime abdy - 291772 288249 0.99x --- lib/date.rb | 1 - lib/date/constants.rb | 17 +++++++++-------- lib/date/parse.rb | 6 ++---- lib/date/shared.rb | 15 --------------- lib/date/strptime.rb | 18 ++++++------------ 5 files changed, 17 insertions(+), 40 deletions(-) delete mode 100644 lib/date/shared.rb diff --git a/lib/date.rb b/lib/date.rb index d7052b75..00037e62 100644 --- a/lib/date.rb +++ b/lib/date.rb @@ -4,7 +4,6 @@ require 'strscan' require_relative "date/version" -require_relative "date/shared" require_relative "date/constants" require_relative "date/core" require_relative "date/strftime" diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 8ed5bfa3..623b156b 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -31,17 +31,18 @@ class Date # proleptic Gregorian calendar. GREGORIAN = -Float::INFINITY - # 3-byte integer key lookup tables for O(1) abbreviated name matching. - # Key = (byte0_lower << 16) | (byte1_lower << 8) | byte2_lower - # Value = [index, full_name_length] - ABBR_DAY_3KEY = ABBR_DAYNAMES.each_with_index.to_h { |n, i| - [compute_3key(n), [i, DAYNAMES[i].length].freeze] + # Case-insensitive abbreviated name lookup tables for O(1) name matching. + # Key = downcased 3-letter abbreviation, Value = [index, full_name_length]. + # The length lets callers verify an optional full-name tail (e.g. the + # "day" in "Sunday" following "Sun"). + ABBR_DAY_INFO = ABBR_DAYNAMES.each_with_index.to_h { |n, i| + [n.downcase.freeze, [i, DAYNAMES[i].length].freeze] }.freeze - ABBR_MONTH_3KEY = ABBR_MONTHNAMES.each_with_index.each_with_object({}) { |(n, i), h| + ABBR_MONTH_INFO = ABBR_MONTHNAMES.each_with_index.each_with_object({}) { |(n, i), h| next if n.nil? - h[compute_3key(n)] = [i, MONTHNAMES[i].length].freeze + h[n.downcase.freeze] = [i, MONTHNAMES[i].length].freeze }.freeze - private_constant :ABBR_DAY_3KEY, :ABBR_MONTH_3KEY + private_constant :ABBR_DAY_INFO, :ABBR_MONTH_INFO # Case-insensitive abbreviated month name -> month number (1-12) ABBR_MONTH_NUM = ABBR_MONTHNAMES.each_with_index.each_with_object({}) { |(n, i), h| diff --git a/lib/date/parse.rb b/lib/date/parse.rb index 08a8f40d..fa2abf5a 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -140,11 +140,9 @@ def _rfc2822(string, limit: 128) if len == 31 sc = StringScanner.new(string) if sc.scan(/([A-Za-z]{3}), (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) ([+-]\d{4})\z/) - wkey = compute_3key(sc[1]) - wday_info = ABBR_DAY_3KEY[wkey] + wday_info = ABBR_DAY_INFO[sc[1].downcase] if wday_info - mkey = compute_3key(sc[3]) - mon_info = ABBR_MONTH_3KEY[mkey] + mon_info = ABBR_MONTH_INFO[sc[3].downcase] if mon_info zone = sc[8] sign = zone[0] == '-' ? -1 : 1 diff --git a/lib/date/shared.rb b/lib/date/shared.rb deleted file mode 100644 index 00d68346..00000000 --- a/lib/date/shared.rb +++ /dev/null @@ -1,15 +0,0 @@ -# frozen_string_literal: true - -# Shared methods used across multiple Date implementation files. -class Date - # Generate a case-insensitive 3-byte integer key from a 3-character string. - # Used for O(1) abbreviated day/month name lookup in parse.rb and strptime.rb. - # Key = (byte0_lower << 16) | (byte1_lower << 8) | byte2_lower - def self.compute_3key(s) - b0 = s.getbyte(0) - b1 = s.getbyte(1) - b2 = s.getbyte(2) - ((b0 | 0x20) << 16) | ((b1 | 0x20) << 8) | (b2 | 0x20) - end - private_class_method :compute_3key -end diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index 664096d8..1a13b77d 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -190,8 +190,7 @@ def sp_run(str, si, fmt, hash) when 65, 97 # 'A', 'a' s3 = str_sc.scan(SP_ALPHA3) throw(:sp_fail) unless s3 - key = compute_3key(s3) - entry = ABBR_DAY_3KEY[key] + entry = ABBR_DAY_INFO[s3.downcase] throw(:sp_fail) unless entry wday_i = entry[0] remaining = entry[1] - 3 @@ -206,8 +205,7 @@ def sp_run(str, si, fmt, hash) when 66, 98, 104 # 'B', 'b', 'h' s3 = str_sc.scan(SP_ALPHA3) throw(:sp_fail) unless s3 - key = compute_3key(s3) - entry = ABBR_MONTH_3KEY[key] + entry = ABBR_MONTH_INFO[s3.downcase] throw(:sp_fail) unless entry mon_i = entry[0] remaining = entry[1] - 3 @@ -461,8 +459,7 @@ def internal_strptime_abdy(str) return nil unless m # Validate weekday via 3-byte key lookup - key = compute_3key(m[1]) - entry = ABBR_DAY_3KEY[key] + entry = ABBR_DAY_INFO[m[1].downcase] return nil unless entry wday = entry[0] day_rest = m[2] @@ -471,8 +468,7 @@ def internal_strptime_abdy(str) end # Validate month via 3-byte key lookup - key = compute_3key(m[3]) - entry = ABBR_MONTH_3KEY[key] + entry = ABBR_MONTH_INFO[m[3].downcase] return nil unless entry mon = entry[0] mon_rest = m[4] @@ -498,8 +494,7 @@ def internal_strptime_abdy_to_date(str, sg) return nil unless m.post_match.empty? # Validate weekday via 3-byte key lookup - key = compute_3key(m[1]) - entry = ABBR_DAY_3KEY[key] + entry = ABBR_DAY_INFO[m[1].downcase] return nil unless entry day_rest = m[2] unless day_rest.empty? @@ -507,8 +502,7 @@ def internal_strptime_abdy_to_date(str, sg) end # Validate month via 3-byte key lookup - key = compute_3key(m[3]) - entry = ABBR_MONTH_3KEY[key] + entry = ABBR_MONTH_INFO[m[3].downcase] return nil unless entry mon = entry[0] mon_rest = m[4] From ca4778fc4994e5d53c5077c185faf36a91690f64 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 14:04:48 +0900 Subject: [PATCH 099/144] Use character-string case dispatch in strftime The strftime spec dispatch (fast_spec / format_spec_b) matched on the byte value of each conversion character (when 89 # 'Y'), with a parallel set of byte-keyed tables (STRFTIME_COMPOSITE_BYTE, *_VALID_BYTES). That reads poorly. Dispatch on the character itself (when 'Y') and key the tables by character instead; the byte-to-int .ord conversions go away. Benchmarking (benchmark-ips) was used to justify the trade-off. Integer case is a few percent faster on bare custom formats because CRuby's opt_case_dispatch turns integer when-clauses into a jump table that string clauses don't get; but the gain is confined to formats that miss the whole-string fast path and carry no flags -- the common formats (%F, %T, %c, ...) hit the fast path and are unaffected, and flagged formats are unchanged within noise. Readability wins over a few percent on an uncommon path. (Symbol clauses also get opt_case_dispatch, but to_sym costs back what the dispatch saves, so they are no better.) Behaviour is unchanged; full suite stays green (148 tests, 162629 assertions). Performance (ips; higher is better; C ext = Ruby 4.0.1 system build): format C ext Ruby before Ruby after %F (whole-string fast path) 3138482 2008842 2037450 (1.01x) %Y/%m/%d %H:%M:%S (scanner) - 139157 134519 (0.97x) %-m %_d %^b (flagged) - 109821 110599 (1.01x) --- lib/date/constants.rb | 44 +++++++------- lib/date/strftime.rb | 138 +++++++++++++++++++++--------------------- 2 files changed, 90 insertions(+), 92 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 623b156b..b09dcbe5 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -115,30 +115,28 @@ class Date PAD2 = (0..99).map { |n| format('%02d', n).freeze }.freeze private_constant :PAD2 - # Map composite spec bytes to their expansion strings - STRFTIME_COMPOSITE_BYTE = { - 43 => '%a %b %e %H:%M:%S %Z %Y', # '+' - 99 => '%a %b %e %H:%M:%S %Y', # 'c' - 68 => '%m/%d/%y', # 'D' - 70 => '%Y-%m-%d', # 'F' - 110 => "\n", # 'n' - 114 => '%I:%M:%S %p', # 'r' - 82 => '%H:%M', # 'R' - 116 => "\t", # 't' - 84 => '%H:%M:%S', # 'T' - 118 => '%e-%^b-%4Y', # 'v' - 88 => '%H:%M:%S', # 'X' - 120 => '%m/%d/%y', # 'x' + # Map composite spec characters to their expansion strings + STRFTIME_COMPOSITE = { + '+' => '%a %b %e %H:%M:%S %Z %Y', + 'c' => '%a %b %e %H:%M:%S %Y', + 'D' => '%m/%d/%y', + 'F' => '%Y-%m-%d', + 'n' => "\n", + 'r' => '%I:%M:%S %p', + 'R' => '%H:%M', + 't' => "\t", + 'T' => '%H:%M:%S', + 'v' => '%e-%^b-%4Y', + 'X' => '%H:%M:%S', + 'x' => '%m/%d/%y', }.freeze - private_constant :STRFTIME_COMPOSITE_BYTE - - # Valid specs for %E locale modifier (as byte values) - # c=99, C=67, x=120, X=88, y=121, Y=89 - STRFTIME_E_VALID_BYTES = [99, 67, 120, 88, 121, 89].freeze - # Valid specs for %O locale modifier (as byte values) - # d=100, e=101, H=72, k=107, I=73, l=108, m=109, M=77, S=83, u=117, U=85, V=86, w=119, W=87, y=121 - STRFTIME_O_VALID_BYTES = [100, 101, 72, 107, 73, 108, 109, 77, 83, 117, 85, 86, 119, 87, 121].freeze - private_constant :STRFTIME_E_VALID_BYTES, :STRFTIME_O_VALID_BYTES + private_constant :STRFTIME_COMPOSITE + + # Valid specs for the %E locale modifier + STRFTIME_E_VALID_CHARS = %w[c C x X y Y].freeze + # Valid specs for the %O locale modifier + STRFTIME_O_VALID_CHARS = %w[d e H k I l m M S u U V w W y].freeze + private_constant :STRFTIME_E_VALID_CHARS, :STRFTIME_O_VALID_CHARS # Maximum allowed format width to prevent unreasonable memory allocation STRFTIME_MAX_WIDTH = 65535 diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 09fad90e..6ca34edc 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -73,7 +73,7 @@ def internal_strftime(fmt) # Quick dispatch: if next char is a simple letter spec (A-Z excluding E/O, # or a-z), skip flag/width parsing entirely. if (quick = sc.scan(/[A-DFG-NP-Za-z]/)) - fast = fast_spec(quick.ord) + fast = fast_spec(quick) if fast result << fast next @@ -123,15 +123,15 @@ def internal_strftime(fmt) colons = (c = sc.scan(/:+/)) ? c.length : 0 # Locale modifier (%E or %O) - locale_mod = sc.scan(/[EO]/)&.ord + locale_mod = sc.scan(/[EO]/) - spec = sc.getch&.ord + spec = sc.getch # Colons are valid only for %z and at most three of them. Any other use # (a colon before the width, a colon with a non-z spec, or four or more # colons) is invalid, and the C extension emits the original text # literally rather than formatting it. - if colons > 0 && (spec != 122 || colons > 3) + if colons > 0 && (spec != 'z' || colons > 3) result << '%' << fmt[spec_start...sc.charpos] next end @@ -140,7 +140,7 @@ def internal_strftime(fmt) # When it is not, the C extension emits the original text verbatim, # including any width, colons, and flags, so restore and emit it here. if locale_mod - valid = locale_mod == 69 ? STRFTIME_E_VALID_BYTES : STRFTIME_O_VALID_BYTES # 69='E' + valid = locale_mod == 'E' ? STRFTIME_E_VALID_CHARS : STRFTIME_O_VALID_CHARS unless valid.include?(spec) result << '%' << fmt[spec_start...sc.charpos] next @@ -175,7 +175,7 @@ def fmt_asctime_str # Inline fast path for common specs with default formatting (no flags/width) def fast_spec(spec) case spec - when 89 # 'Y' + when 'Y' y = @year check_fmt_year(y) if y >= 1000 @@ -185,38 +185,38 @@ def fast_spec(spec) else format('-%04d', -y) end - when 109 # 'm' + when 'm' PAD2[@month] - when 100 # 'd' + when 'd' PAD2[@day] - when 101 # 'e' + when 'e' d = @day d < 10 ? " #{d}" : d.to_s - when 72 # 'H' + when 'H' PAD2[internal_hour] - when 77 # 'M' + when 'M' PAD2[internal_min] - when 83 # 'S' + when 'S' PAD2[internal_sec] - when 97 # 'a' + when 'a' ABBR_DAYNAMES[(@jd + 1) % 7] - when 65 # 'A' + when 'A' DAYNAMES[(@jd + 1) % 7] - when 98, 104 # 'b', 'h' + when 'b', 'h' ABBR_MONTHNAMES[@month] - when 66 # 'B' + when 'B' MONTHNAMES[@month] - when 112 # 'p' + when 'p' internal_hour < 12 ? 'AM' : 'PM' - when 80 # 'P' + when 'P' internal_hour < 12 ? 'am' : 'pm' - when 37 # '%' + when '%' '%' - when 110 # 'n' + when 'n' "\n" - when 116 # 't' + when 't' "\t" - when 106 # 'j' + when 'j' yd = yday if yd < 10 "00#{yd}" @@ -225,30 +225,30 @@ def fast_spec(spec) else yd.to_s end - when 119 # 'w' + when 'w' ((@jd + 1) % 7).to_s - when 117 # 'u' + when 'u' cwday.to_s - when 121 # 'y' + when 'y' PAD2[@year % 100] - when 90 # 'Z' + when 'Z' zone_str - when 122 # 'z' + when 'z' strftime_zoff - when 115 # 's' + when 's' ((@jd - 2440588) * 86400 - of_seconds + internal_hour * 3600 + internal_min * 60 + internal_sec).to_s # Composite specs — inline expansion - when 99 # 'c' + when 'c' fmt_asctime_str - when 70 # 'F' + when 'F' fast_ymd - when 84, 88 # 'T', 'X' + when 'T', 'X' strftime_hms - when 68, 120 # 'D', 'x' + when 'D', 'x' "#{PAD2[@month]}/#{PAD2[@day]}/#{PAD2[@year % 100]}" - when 82 # 'R' + when 'R' strftime_hm - when 114 # 'r' + when 'r' strftime_r12 else nil # fall through to format_spec_b @@ -258,92 +258,92 @@ def fast_spec(spec) # Full spec handling with bitmask flags (called when fast_spec returns nil or flags/width present) def format_spec_b(spec, flags, colons, width) case spec - when 89, 71 # 'Y', 'G' - y = spec == 89 ? year : cwyear + when 'Y', 'G' + y = spec == 'Y' ? year : cwyear fmt_year(y, width, flags) - when 67 # 'C' + when 'C' cent = year.div(100) pad_num(cent, width || 2, flags, zero: true) - when 121 # 'y' + when 'y' pad_num(year % 100, width || 2, flags, zero: true) - when 103 # 'g' + when 'g' pad_num(cwyear % 100, width || 2, flags, zero: true) - when 109 # 'm' + when 'm' pad_num(month, width || 2, flags, zero: true) - when 100 # 'd' + when 'd' pad_num(day, width || 2, flags, zero: true) - when 101 # 'e' + when 'e' pad_num(day, width || 2, flags, zero: false) - when 106 # 'j' + when 'j' pad_num(yday, width || 3, flags, zero: true) - when 72 # 'H' + when 'H' pad_num(internal_hour, width || 2, flags, zero: true) - when 107 # 'k' + when 'k' pad_num(internal_hour, width || 2, flags, zero: false) - when 73 # 'I' + when 'I' h = internal_hour % 12 h = 12 if h == 0 pad_num(h, width || 2, flags, zero: true) - when 108 # 'l' + when 'l' h = internal_hour % 12 h = 12 if h == 0 pad_num(h, width || 2, flags, zero: false) - when 77 # 'M' + when 'M' pad_num(internal_min, width || 2, flags, zero: true) - when 83 # 'S' + when 'S' pad_num(internal_sec, width || 2, flags, zero: true) - when 76 # 'L' + when 'L' w = width || 3 ms = (sec_frac * (10**w)).floor ms.to_s.rjust(w, '0') - when 78 # 'N' + when 'N' w = width || 9 ns = (sec_frac * (10**w)).floor ns.to_s.rjust(w, '0') - when 115 # 's' + when 's' unix = (@jd - 2440588) * 86400 - of_seconds + internal_hour * 3600 + internal_min * 60 + internal_sec pad_num(unix, width || 1, flags, zero: true) - when 81 # 'Q' + when 'Q' ms = ((@jd - 2440588) * 86400 - of_seconds + internal_hour * 3600 + internal_min * 60 + internal_sec) * 1000 + (sec_frac * 1000).floor pad_num(ms, width || 1, flags, zero: true) - when 65 # 'A' + when 'A' fmt_str(DAYNAMES[wday], width, flags) - when 97 # 'a' + when 'a' fmt_str(ABBR_DAYNAMES[wday], width, flags) - when 66 # 'B' + when 'B' fmt_str(MONTHNAMES[month], width, flags) - when 98, 104 # 'b', 'h' + when 'b', 'h' fmt_str(ABBR_MONTHNAMES[month], width, flags) - when 112 # 'p' + when 'p' fmt_str(internal_hour < 12 ? 'AM' : 'PM', width, flags) - when 80 # 'P' + when 'P' fmt_str(internal_hour < 12 ? 'am' : 'pm', width, flags) - when 90 # 'Z' + when 'Z' fmt_str(zone_str, width, flags) - when 122 # 'z' + when 'z' fmt_z(colons, width, flags) - when 117 # 'u' + when 'u' pad_num(cwday, width || 1, flags, zero: true) - when 119 # 'w' + when 'w' pad_num(wday, width || 1, flags, zero: true) - when 85 # 'U' + when 'U' pad_num(week_number(0), width || 2, flags, zero: true) - when 87 # 'W' + when 'W' pad_num(week_number(1), width || 2, flags, zero: true) - when 86 # 'V' + when 'V' pad_num(cweek, width || 2, flags, zero: true) - when 37 # '%' + when '%' fmt_str('%', width, flags) else - expansion = STRFTIME_COMPOSITE_BYTE[spec] + expansion = STRFTIME_COMPOSITE[spec] if expansion s = internal_strftime(expansion) fmt_str(s, width, flags) else - "%#{spec&.chr}" + "%#{spec}" end end end From 8631a121ca855c3cffac403c0bcbeca614574933 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 14:06:30 +0900 Subject: [PATCH 100/144] Use character-string case dispatch in strptime sp_run Mirror the strftime change in the strptime format interpreter: sp_run dispatched on spec_ch.ord with integer when-clauses (when 65, 97 # 'A', 'a'); dispatch on spec_ch directly (when 'A', 'a') and drop the .ord. The else branch already referred to spec_ch, so the integer spec local is removed entirely. As in strftime, integer case can be a hair faster via opt_case_dispatch, but here the dispatch is a smaller slice of each spec's work, so the cost is ~1-2% on sp_run formats and nil on the %F/abdy fast paths. Readability wins. Behaviour is unchanged; full suite stays green (148 tests, 162629 assertions). Performance (ips; higher is better; C ext = Ruby 4.0.1 system build): format C ext Ruby before Ruby after _strptime %F (fast path) 2721889 887029 870258 (0.98x) _strptime %d-%m-%Y - 133207 131735 (0.99x) _strptime %y-%b-%d - 124500 123068 (0.99x) _strptime %a%d%b%y - 108591 106755 (0.98x) --- lib/date/strptime.rb | 77 ++++++++++++++++++++++---------------------- 1 file changed, 38 insertions(+), 39 deletions(-) diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index 1a13b77d..a3442fb7 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -184,10 +184,9 @@ def sp_run(str, si, fmt, hash) end spec_ch = fmt_sc.getch - spec = spec_ch&.ord - case spec - when 65, 97 # 'A', 'a' + case spec_ch + when 'A', 'a' s3 = str_sc.scan(SP_ALPHA3) throw(:sp_fail) unless s3 entry = ABBR_DAY_INFO[s3.downcase] @@ -202,7 +201,7 @@ def sp_run(str, si, fmt, hash) end hash[:wday] = wday_i - when 66, 98, 104 # 'B', 'b', 'h' + when 'B', 'b', 'h' s3 = str_sc.scan(SP_ALPHA3) throw(:sp_fail) unless s3 entry = ABBR_MONTH_INFO[s3.downcase] @@ -217,46 +216,46 @@ def sp_run(str, si, fmt, hash) end hash[:mon] = mon_i - when 67 # 'C' + when 'C' num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) sign = sp_scan_sign(str_sc) s = str_sc.scan(num_next ? SP_DIGITS_2 : SP_DIGITS_MAX) throw(:sp_fail) unless s hash[:_cent] = sign * s.to_i - when 99 # 'c' + when 'c' str_sc.pos = sp_run(str, str_sc.pos, '%a %b %e %H:%M:%S %Y', hash) - when 68 # 'D' + when 'D' str_sc.pos = sp_run(str, str_sc.pos, '%m/%d/%y', hash) - when 100, 101 # 'd', 'e' + when 'd', 'e' sp_store_int(hash, :mday, str_sc.scan(SP_SPACE_OR_DIGIT), 1, 31) - when 70 # 'F' + when 'F' str_sc.pos = sp_run(str, str_sc.pos, '%Y-%m-%d', hash) - when 71 # 'G' + when 'G' sign = sp_scan_sign(str_sc) num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) s = str_sc.scan(num_next ? SP_DIGITS_4 : SP_DIGITS_MAX) throw(:sp_fail) unless s hash[:cwyear] = sign * s.to_i - when 103 # 'g' + when 'g' n = sp_store_int(hash, :cwyear, str_sc.scan(SP_DIGITS_2), 0, 99) hash[:_cent] ||= n >= 69 ? 19 : 20 - when 72, 107 # 'H', 'k' + when 'H', 'k' sp_store_int(hash, :hour, str_sc.scan(SP_SPACE_OR_DIGIT), 0, 24) - when 73, 108 # 'I', 'l' + when 'I', 'l' sp_store_int(hash, :hour, str_sc.scan(SP_SPACE_OR_DIGIT), 1, 12) - when 106 # 'j' + when 'j' sp_store_int(hash, :yday, str_sc.scan(SP_DIGITS_3), 1, 366) - when 76 # 'L' + when 'L' sign = sp_scan_sign(str_sc) osi = str_sc.pos num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) @@ -266,13 +265,13 @@ def sp_run(str, si, fmt, hash) n = -n if sign == -1 hash[:sec_fraction] = Rational(n, 10**(str_sc.pos - osi)) - when 77 # 'M' + when 'M' sp_store_int(hash, :min, str_sc.scan(SP_DIGITS_2), 0, 59) - when 109 # 'm' + when 'm' sp_store_int(hash, :mon, str_sc.scan(SP_DIGITS_2), 1, 12) - when 78 # 'N' + when 'N' sign = sp_scan_sign(str_sc) osi = str_sc.pos num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) @@ -282,10 +281,10 @@ def sp_run(str, si, fmt, hash) n = -n if sign == -1 hash[:sec_fraction] = Rational(n, 10**(str_sc.pos - osi)) - when 110, 116 # 'n', 't' + when 'n', 't' str_sc.pos = sp_run(str, str_sc.pos, ' ', hash) - when 80, 112 # 'P', 'p' + when 'P', 'p' throw(:sp_fail) if str_sc.eos? c0 = str_sc.peek(1) if c0 == 'P' || c0 == 'p' @@ -300,7 +299,7 @@ def sp_run(str, si, fmt, hash) end hash[:_merid] = merid - when 81 # 'Q' + when 'Q' sign = 1 if str_sc.skip(/-/) sign = -1 @@ -311,16 +310,16 @@ def sp_run(str, si, fmt, hash) n = -n if sign == -1 hash[:seconds] = Rational(n, 1000) - when 82 # 'R' + when 'R' str_sc.pos = sp_run(str, str_sc.pos, '%H:%M', hash) - when 114 # 'r' + when 'r' str_sc.pos = sp_run(str, str_sc.pos, '%I:%M:%S %p', hash) - when 83 # 'S' + when 'S' sp_store_int(hash, :sec, str_sc.scan(SP_DIGITS_2), 0, 60) - when 115 # 's' + when 's' sign = 1 if str_sc.skip(/-/) sign = -1 @@ -331,52 +330,52 @@ def sp_run(str, si, fmt, hash) n = -n if sign == -1 hash[:seconds] = n - when 84 # 'T' + when 'T' str_sc.pos = sp_run(str, str_sc.pos, '%H:%M:%S', hash) - when 85 # 'U' + when 'U' sp_store_int(hash, :wnum0, str_sc.scan(SP_DIGITS_2), 0, 53) - when 117 # 'u' + when 'u' sp_store_int(hash, :cwday, str_sc.scan(SP_DIGITS_1), 1, 7) - when 86 # 'V' + when 'V' sp_store_int(hash, :cweek, str_sc.scan(SP_DIGITS_2), 1, 53) - when 118 # 'v' + when 'v' str_sc.pos = sp_run(str, str_sc.pos, '%e-%b-%Y', hash) - when 87 # 'W' + when 'W' sp_store_int(hash, :wnum1, str_sc.scan(SP_DIGITS_2), 0, 53) - when 119 # 'w' + when 'w' sp_store_int(hash, :wday, str_sc.scan(SP_DIGITS_1), 0, 6) - when 88 # 'X' + when 'X' str_sc.pos = sp_run(str, str_sc.pos, '%H:%M:%S', hash) - when 120 # 'x' + when 'x' str_sc.pos = sp_run(str, str_sc.pos, '%m/%d/%y', hash) - when 89 # 'Y' + when 'Y' sign = sp_scan_sign(str_sc) num_next = !fmt_sc.eos? && fmt_sc.check(SP_NUM_CHECK) s = str_sc.scan(num_next ? SP_DIGITS_4 : SP_DIGITS_MAX) throw(:sp_fail) unless s hash[:year] = sign * s.to_i - when 121 # 'y' + when 'y' n = sp_store_int(hash, :year, str_sc.scan(SP_DIGITS_2), 0, 99) hash[:_cent] ||= n >= 69 ? 19 : 20 - when 90, 122 # 'Z', 'z' + when 'Z', 'z' str_sc.pos = sp_zone(str, str_sc.pos, str.bytesize, hash) - when 37 # '%' + when '%' throw(:sp_fail) if str_sc.eos? || str_sc.peek(1) != '%' str_sc.skip(/%/) - when 43 # '+' + when '+' str_sc.pos = sp_run(str, str_sc.pos, '%a %b %e %H:%M:%S %Z %Y', hash) else From 3c85c59b14abc2e324001acb93a218379066e8d5 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 14:17:58 +0900 Subject: [PATCH 101/144] Inline low-value packaging tables; keep MONTH_DAY_SUFFIX Four precomputed string tables existed only to shave a few percent off cold formatting paths. Benchmarking (benchmark-ips) shows the saving does not justify the precomputation, so interpolate inline instead and drop the constants: ASCTIME_PREFIX -> "#{ABBR_DAYNAMES[w]} #{ABBR_MONTHNAMES[m]} " (%c) RFC_MON_SPACE -> " #{ABBR_MONTHNAMES[m]} " (rfc2822/httpdate) DAY_FULL_COMMA -> "#{DAYNAMES[w]}, " (%A, %B %d, %Y) MONTH_FULL_SPACE -> "#{MONTHNAMES[m]} " (%A, %B %d, %Y) MONTH_DAY_SUFFIX is KEPT: it feeds the %F / %Y-%m-%d fast path (fast_ymd), a genuinely hot path where the two-dimensional table is worth 27-37%. Behaviour is unchanged; full suite stays green (148 tests, 162629 assertions). Performance (ips; higher is better; C ext = Ruby 4.0.1 system build): method C ext Ruby before Ruby after strftime %c 2041798 893314 840160 (0.94x) strftime %A, %B %d, %Y 3109861 1432571 1394155 (0.97x) rfc2822 (instance) 1974374 1495095 1418530 (0.95x) httpdate (instance) 1663871 1489462 1426341 (0.96x) strftime %F (MDS kept) 3138482 2025282 2033269 (1.00x) --- lib/date/constants.rb | 19 ------------------- lib/date/core.rb | 8 ++++---- lib/date/strftime.rb | 4 ++-- 3 files changed, 6 insertions(+), 25 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index b09dcbe5..3f3a305a 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -72,10 +72,6 @@ class Date GJD_MONTH_OFFSET = [nil, 428, 459, 122, 153, 183, 214, 244, 275, 306, 336, 367, 397].freeze private_constant :GJD_MONTH_OFFSET - # Pre-computed " Mon " strings for rfc2822/httpdate: " Jan ", " Feb ", ... - RFC_MON_SPACE = ABBR_MONTHNAMES.map { |m| m ? " #{m} ".freeze : nil }.freeze - private_constant :RFC_MON_SPACE - ERA_TABLE = [ [2458605, 'R', 2018], # Reiwa: 2019-05-01 [2447535, 'H', 1988], # Heisei: 1989-01-08 @@ -95,21 +91,6 @@ class Date }.freeze private_constant :MONTH_DAY_SUFFIX - # === String formatting (from strftime.rb) === - - # Pre-computed "Sun Jan " prefix table for %c / asctime [wday][month] - ASCTIME_PREFIX = Array.new(7) { |w| - Array.new(13) { |m| - m == 0 ? nil : "#{ABBR_DAYNAMES[w]} #{ABBR_MONTHNAMES[m]} ".freeze - }.freeze - }.freeze - private_constant :ASCTIME_PREFIX - - # Pre-computed "Saturday, " prefix table for %A format [wday] - DAY_FULL_COMMA = DAYNAMES.map { |d| "#{d}, ".freeze }.freeze - # Pre-computed "March " prefix table for %B format [month] - MONTH_FULL_SPACE = MONTHNAMES.map { |m| m ? "#{m} ".freeze : nil }.freeze - private_constant :DAY_FULL_COMMA, :MONTH_FULL_SPACE # Pre-computed 2-digit zero-padded strings for 0..99 PAD2 = (0..99).map { |n| format('%02d', n).freeze }.freeze diff --git a/lib/date/core.rb b/lib/date/core.rb index 4548be1a..613f26d2 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1555,9 +1555,9 @@ def rfc2822 y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) if instance_of?(Date) - "#{ABBR_DAYNAMES[w]}, #{@day}#{RFC_MON_SPACE[@month]}#{y_s} 00:00:00 +0000" + "#{ABBR_DAYNAMES[w]}, #{@day} #{ABBR_MONTHNAMES[@month]} #{y_s} 00:00:00 +0000" else - "#{ABBR_DAYNAMES[w]}, #{@day}#{RFC_MON_SPACE[@month]}#{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} +0000" + "#{ABBR_DAYNAMES[w]}, #{@day} #{ABBR_MONTHNAMES[@month]} #{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} +0000" end end alias_method :rfc822, :rfc2822 @@ -1576,9 +1576,9 @@ def httpdate y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) if instance_of?(Date) - "#{ABBR_DAYNAMES[w]}, #{PAD2[@day]}#{RFC_MON_SPACE[@month]}#{y_s} 00:00:00 GMT" + "#{ABBR_DAYNAMES[w]}, #{PAD2[@day]} #{ABBR_MONTHNAMES[@month]} #{y_s} 00:00:00 GMT" else - "#{ABBR_DAYNAMES[w]}, #{PAD2[@day]}#{RFC_MON_SPACE[@month]}#{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} GMT" + "#{ABBR_DAYNAMES[w]}, #{PAD2[@day]} #{ABBR_MONTHNAMES[@month]} #{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} GMT" end end diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 6ca34edc..31cd9df7 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -46,7 +46,7 @@ def internal_strftime(fmt) w = (@jd + 1) % 7 y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) - return "#{DAY_FULL_COMMA[w]}#{MONTH_FULL_SPACE[@month]}#{PAD2[@day]}, #{y_s}" + return "#{DAYNAMES[w]}, #{MONTHNAMES[@month]} #{PAD2[@day]}, #{y_s}" end result = +''.encode(fmt.encoding) @@ -169,7 +169,7 @@ def fmt_asctime_str d_s = d < 10 ? " #{d}" : d.to_s y = @year y_s = y >= 1000 ? y.to_s : (y >= 0 ? format('%04d', y) : format('-%04d', -y)) - "#{ASCTIME_PREFIX[w][@month]}#{d_s} #{strftime_hms} #{y_s}" + "#{ABBR_DAYNAMES[w]} #{ABBR_MONTHNAMES[@month]} #{d_s} #{strftime_hms} #{y_s}" end # Inline fast path for common specs with default formatting (no flags/width) From 6b96fa8776ba11a86d1074161c0249f4ba457fe3 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 15:39:45 +0900 Subject: [PATCH 102/144] Add regression tests for two edge-case fixes toward the C extension Two earlier commits in this series also corrected edge-case behaviour toward the C extension, although their messages described the behaviour as unchanged: - 02c4905 (remove the _httpdate StringScanner fast path): that fast path hardcoded the zone as "GMT", so lowercase input now preserves the given case (zone "gmt"), matching the C extension. - ca4778f (character-string case dispatch in strftime): a multibyte character after '%' used to raise RangeError (Integer#chr on the codepoint); it is now emitted verbatim as "%", matching the C extension. Both are already correct in the current tree; these tests lock the behaviour in. Expected values were taken from the C extension (date 3.5.1). Full suite: 150 tests, 162633 assertions, green. --- test/date/test_date_parse.rb | 10 ++++++++++ test/date/test_date_strftime.rb | 9 +++++++++ 2 files changed, 19 insertions(+) diff --git a/test/date/test_date_parse.rb b/test/date/test_date_parse.rb index 8308f258..fc032df6 100644 --- a/test/date/test_date_parse.rb +++ b/test/date/test_date_parse.rb @@ -1038,6 +1038,16 @@ def test__httpdate assert_raise(TypeError) {Date._httpdate('Sat, 03 Feb 2001 04:05:06 GMT'.to_sym)} end + def test__httpdate_preserves_zone_case + # The parsed :zone is returned as given, preserving case, matching the + # C extension. (A removed fast path used to hardcode it to "GMT".) + h = Date._httpdate('sat, 03 feb 2001 04:05:06 gmt') + assert_equal([2001, 2, 3, 4, 5, 6, 'gmt', 0], + h.values_at(:year, :mon, :mday, :hour, :min, :sec, :zone, :offset)) + h = Date._httpdate('Sat, 03 Feb 2001 04:05:06 GMT') + assert_equal('GMT', h[:zone]) + end + def test__jisx0301 h = Date._jisx0301('13.02.03') assert_equal([2001, 2, 3, nil, nil, nil, nil], diff --git a/test/date/test_date_strftime.rb b/test/date/test_date_strftime.rb index 24de349b..ce5e53ce 100644 --- a/test/date/test_date_strftime.rb +++ b/test/date/test_date_strftime.rb @@ -189,6 +189,15 @@ def test_strftime_ymd_encoding end end + def test_strftime_multibyte_invalid_conversion + # A multibyte character after '%' is an invalid conversion specifier and + # is emitted verbatim as "%", matching the C extension. It must not + # raise (an earlier implementation raised RangeError via Integer#chr). + d = Date.new(2001, 2, 3) + assert_equal("%あ", d.strftime("%あ")) + assert_equal("x%あy", d.strftime("x%あy")) + end + def test_strftime__offset s = '2006-08-08T23:15:33' (-24..24).collect{|x| '%+.2d' % x}.each do |hh| From b012024f31d5af67bdc96ed225b327182e281357 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 15:40:42 +0900 Subject: [PATCH 103/144] Clean up after the dispatch/key refactors Follow-up tidy-ups with no behaviour change: - strptime: the "3-byte key lookup" comments were left over from the integer-key tables; the lookup is now a plain abbreviation lookup. - constants: remove FAST_HTTPDATE_TYPE1_RE, which is unreferenced (the former httpdate fast path used an inline regexp, not this constant). - constants: drop a stray double blank line left by removing the packaging tables. Full suite: 150 tests, 162633 assertions, green. --- lib/date/constants.rb | 6 +----- lib/date/strptime.rb | 8 ++++---- 2 files changed, 5 insertions(+), 9 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 3f3a305a..7ffefe23 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -91,7 +91,6 @@ class Date }.freeze private_constant :MONTH_DAY_SUFFIX - # Pre-computed 2-digit zero-padded strings for 0..99 PAD2 = (0..99).map { |n| format('%02d', n).freeze }.freeze private_constant :PAD2 @@ -131,10 +130,7 @@ class Date HTTPDATE_TYPE1_RE = /\A\s*(sun|mon|tue|wed|thu|fri|sat)\s*,\s+(\d{2})\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+(-?\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+(gmt)\s*\z/i HTTPDATE_TYPE2_RE = /\A\s*(sunday|monday|tuesday|wednesday|thursday|friday|saturday)\s*,\s+(\d{2})\s*-\s*(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s*-\s*(\d{2})\s+(\d{2}):(\d{2}):(\d{2})\s+(gmt)\s*\z/i HTTPDATE_TYPE3_RE = /\A\s*(sun|mon|tue|wed|thu|fri|sat)\s+(jan|feb|mar|apr|may|jun|jul|aug|sep|oct|nov|dec)\s+(\d{1,2})\s+(\d{2}):(\d{2}):(\d{2})\s+(\d{4})\s*\z/i - # Fast path: simplified Type 1 with generic [a-zA-Z] instead of alternation - FAST_HTTPDATE_TYPE1_RE = /\A\s*([a-zA-Z]{3}),\s+(\d{2})\s+([a-zA-Z]{3})\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+(GMT)\s*\z/i - private_constant :HTTPDATE_TYPE1_RE, :HTTPDATE_TYPE2_RE, :HTTPDATE_TYPE3_RE, - :FAST_HTTPDATE_TYPE1_RE + private_constant :HTTPDATE_TYPE1_RE, :HTTPDATE_TYPE2_RE, :HTTPDATE_TYPE3_RE # Wday lookup from full day name (lowercase key). The abbreviated-name # lookup reuses ABBR_DAY_NUM, which is the identical table; both maps are diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index a3442fb7..412c0289 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -457,7 +457,7 @@ def internal_strptime_abdy(str) m = STRPTIME_ABDY_PAT.match(str) return nil unless m - # Validate weekday via 3-byte key lookup + # Validate weekday via abbreviation lookup entry = ABBR_DAY_INFO[m[1].downcase] return nil unless entry wday = entry[0] @@ -466,7 +466,7 @@ def internal_strptime_abdy(str) return nil unless day_rest.length == entry[1] - 3 && day_rest.downcase == DAY_LOWER_STRS[wday][3..] end - # Validate month via 3-byte key lookup + # Validate month via abbreviation lookup entry = ABBR_MONTH_INFO[m[3].downcase] return nil unless entry mon = entry[0] @@ -492,7 +492,7 @@ def internal_strptime_abdy_to_date(str, sg) return nil unless m return nil unless m.post_match.empty? - # Validate weekday via 3-byte key lookup + # Validate weekday via abbreviation lookup entry = ABBR_DAY_INFO[m[1].downcase] return nil unless entry day_rest = m[2] @@ -500,7 +500,7 @@ def internal_strptime_abdy_to_date(str, sg) return nil unless day_rest.length == entry[1] - 3 && day_rest.downcase == DAY_LOWER_STRS[entry[0]][3..] end - # Validate month via 3-byte key lookup + # Validate month via abbreviation lookup entry = ABBR_MONTH_INFO[m[3].downcase] return nil unless entry mon = entry[0] From 02ebff468e2ce567f4252733219f1f23d46265fe Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 15:46:38 +0900 Subject: [PATCH 104/144] Derive ABBR_*_NUM from ABBR_*_INFO After the integer-key tables became string-keyed, ABBR_DAY_NUM/ ABBR_MONTH_NUM and ABBR_DAY_INFO/ABBR_MONTH_INFO ended up with identical keys, differing only in whether the value carries the full-name length. Build the NUM maps from the INFO maps (index only) instead of repeating the name list and downcasing logic. No behaviour change. Full suite: 150 tests, 162633 assertions, green. --- lib/date/constants.rb | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 7ffefe23..7dfe033a 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -44,14 +44,10 @@ class Date }.freeze private_constant :ABBR_DAY_INFO, :ABBR_MONTH_INFO - # Case-insensitive abbreviated month name -> month number (1-12) - ABBR_MONTH_NUM = ABBR_MONTHNAMES.each_with_index.each_with_object({}) { |(n, i), h| - next if n.nil? - h[n.downcase] = i - }.freeze - - # Case-insensitive abbreviated day name -> wday number (0-6) - ABBR_DAY_NUM = ABBR_DAYNAMES.each_with_index.to_h { |n, i| [n.downcase, i] }.freeze + # Abbreviated-name -> index maps, derived from the *_INFO tables above: same + # (downcased) keys, with the index alone as the value (no name length). + ABBR_MONTH_NUM = ABBR_MONTH_INFO.transform_values { |v| v[0] }.freeze + ABBR_DAY_NUM = ABBR_DAY_INFO.transform_values { |v| v[0] }.freeze private_constant :ABBR_MONTH_NUM, :ABBR_DAY_NUM # Lowercase full name strings for StringScanner-based head matching From 891afaca4781f7c082382bf2310da1a92e06f6f0 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 15:49:07 +0900 Subject: [PATCH 105/144] Fix %v year formatting for negative years The %v composite expanded to %e-%^b-%4Y, so negative years were width-4 including the sign (e.g. Date.new(-5,1,9).strftime('%v') gave " 9-JAN--005"). The C extension uses %Y there (sign plus at least four digits), giving " 9-JAN--0005". Expand to %e-%^b-%Y to match. Positive and four-plus-digit years are unaffected (%Y and %4Y agree there). Verified against the C extension (date 3.5.1). As a side effect %v is a bit faster, since %Y takes the no-width fast_spec path that %4Y did not. Performance (ips; higher is better): format Ruby before Ruby after strftime %v 97005 116609 (1.20x) Full suite: 151 tests, 162636 assertions, green. --- lib/date/constants.rb | 2 +- test/date/test_date_strftime.rb | 8 ++++++++ 2 files changed, 9 insertions(+), 1 deletion(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 7dfe033a..fd76beef 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -102,7 +102,7 @@ class Date 'R' => '%H:%M', 't' => "\t", 'T' => '%H:%M:%S', - 'v' => '%e-%^b-%4Y', + 'v' => '%e-%^b-%Y', 'X' => '%H:%M:%S', 'x' => '%m/%d/%y', }.freeze diff --git a/test/date/test_date_strftime.rb b/test/date/test_date_strftime.rb index ce5e53ce..b3c0fc18 100644 --- a/test/date/test_date_strftime.rb +++ b/test/date/test_date_strftime.rb @@ -189,6 +189,14 @@ def test_strftime_ymd_encoding end end + def test_strftime_v_negative_year + # %v formats the year with %Y (sign plus at least four digits), matching + # the C extension, not a width-4 %4Y. + assert_equal(' 9-JAN--0005', Date.new(-5, 1, 9).strftime('%v')) + assert_equal(' 9-JAN--0012', Date.new(-12, 1, 9).strftime('%v')) + assert_equal(' 9-JAN-0005', Date.new(5, 1, 9).strftime('%v')) + end + def test_strftime_multibyte_invalid_conversion # A multibyte character after '%' is an invalid conversion specifier and # is emitted verbatim as "%", matching the C extension. It must not From 09f5cbd7d073c5603334841828dab81a8ede378f Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 15:53:19 +0900 Subject: [PATCH 106/144] Emit the original text for invalid strftime conversions An invalid conversion (an unknown conversion character, or flags/width followed by end-of-string with no conversion) must be emitted verbatim with its flags and width intact, as the C extension does. The Ruby implementation collapsed these to a bare "%" (end-of-string case) or "%" (unknown character), dropping any flags and width: strftime("%-") "%" -> "%-" strftime("%05") "%" -> "%05" strftime("%-q") "%q" -> "%-q" strftime("%5q") "%q" -> "%5q" Handle end-of-string right after reading the conversion character, and have format_spec_b return nil for an unknown conversion so the caller can emit the original `%...` slice from the format string. Valid conversions, including flagged and composite ones, are unaffected. Verified against the C extension (date 3.5.1). Performance on valid formats is unchanged (the change only affects the invalid path): format Ruby before Ruby after strftime %-5d %05m 148652 146938 (~1.0x) strftime %Y/%m/%d 256872 258874 (~1.0x) Full suite: 153 tests, 162652 assertions, green. --- lib/date/strftime.rb | 19 +++++++++++++++++-- test/date/test_date_strftime.rb | 20 ++++++++++++++++++++ 2 files changed, 37 insertions(+), 2 deletions(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 31cd9df7..f8e794c7 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -127,6 +127,14 @@ def internal_strftime(fmt) spec = sc.getch + # End of string reached after '%' and some flags/width/colons/modifier, + # with no conversion character. The C extension emits the original text + # verbatim rather than collapsing it to a bare '%'. + if spec.nil? + result << '%' << fmt[spec_start...sc.charpos] + next + end + # Colons are valid only for %z and at most three of them. Any other use # (a colon before the width, a colon with a non-z spec, or four or more # colons) is invalid, and the C extension emits the original text @@ -156,7 +164,14 @@ def internal_strftime(fmt) end end - result << format_spec_b(spec, flags, colons, width) + formatted = format_spec_b(spec, flags, colons, width) + if formatted + result << formatted + else + # Unknown conversion: emit the original text (flags, width and all) + # verbatim, as the C extension does. + result << '%' << fmt[spec_start...sc.charpos] + end end result @@ -343,7 +358,7 @@ def format_spec_b(spec, flags, colons, width) s = internal_strftime(expansion) fmt_str(s, width, flags) else - "%#{spec}" + nil # unknown conversion: caller emits the original text verbatim end end end diff --git a/test/date/test_date_strftime.rb b/test/date/test_date_strftime.rb index b3c0fc18..ac684e97 100644 --- a/test/date/test_date_strftime.rb +++ b/test/date/test_date_strftime.rb @@ -197,6 +197,26 @@ def test_strftime_v_negative_year assert_equal(' 9-JAN-0005', Date.new(5, 1, 9).strftime('%v')) end + def test_strftime_incomplete_spec_at_eos + # Flags and/or a width followed by end-of-string (no conversion character) + # are emitted verbatim, matching the C extension, rather than collapsing + # to a bare "%". + d = Date.new(2001, 2, 3) + %w[%- %_ %0 %^ %# %5 %05 %10 %-5].each do |f| + assert_equal(f, d.strftime(f), "strftime(#{f.inspect})") + end + end + + def test_strftime_invalid_spec_with_flags + # An unknown conversion character preceded by flags and/or a width is + # emitted verbatim, matching the C extension; the flags/width must not be + # dropped (which would leave just "%"). + d = Date.new(2001, 2, 3) + %w[%q %-q %5q %05q %-5q %^q %#q].each do |f| + assert_equal(f, d.strftime(f), "strftime(#{f.inspect})") + end + end + def test_strftime_multibyte_invalid_conversion # A multibyte character after '%' is an invalid conversion specifier and # is emitted verbatim as "%", matching the C extension. It must not From ad85ee02b11897df8c6d12da5d42cc3bdea03fdf Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 15:59:12 +0900 Subject: [PATCH 107/144] Ignore the '#' flag on composite strftime conversions The '#' (change-case) flag applied to a composite conversion (%c, %r, %v, ...) was case-flipping the whole expanded result, so e.g. %#c produced "SAT FEB 3 ...". The C extension ignores '#' on composites (only '^', width and justification apply there), leaving %#c as "Sat Feb 3 ...". Mask FL_CHCASE out before formatting the composite result. The difference was only visible on composites with alphabetic content (%c, %r, %v); the digit-only composites (%x, %D, %F, %T, %R) were already identical. Verified against the C extension (date 3.5.1). Performance (ips; higher is better): format Ruby before Ruby after strftime %#c 194451 240039 (1.23x, skips the needless flip) strftime %c 1022374 1106401 (~unchanged) Full suite: 154 tests, 162657 assertions, green. --- lib/date/strftime.rb | 4 +++- test/date/test_date_strftime.rb | 12 ++++++++++++ 2 files changed, 15 insertions(+), 1 deletion(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index f8e794c7..ed504d0a 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -356,7 +356,9 @@ def format_spec_b(spec, flags, colons, width) expansion = STRFTIME_COMPOSITE[spec] if expansion s = internal_strftime(expansion) - fmt_str(s, width, flags) + # The '#' (change-case) flag has no effect on composite conversions + # in the C extension; only '^' (upcase), width and justification do. + fmt_str(s, width, flags & ~FL_CHCASE) else nil # unknown conversion: caller emits the original text verbatim end diff --git a/test/date/test_date_strftime.rb b/test/date/test_date_strftime.rb index ac684e97..ae948949 100644 --- a/test/date/test_date_strftime.rb +++ b/test/date/test_date_strftime.rb @@ -189,6 +189,18 @@ def test_strftime_ymd_encoding end end + def test_strftime_hash_flag_ignored_on_composites + # The '#' (change-case) flag has no effect on composite conversions + # (%c, %r, %v, ...), matching the C extension; the '^' (upcase) flag + # still applies. + d = Date.new(2001, 2, 3) + assert_equal('Sat Feb 3 00:00:00 2001', d.strftime('%#c')) + assert_equal('12:00:00 AM', d.strftime('%#r')) + assert_equal(' 3-FEB-2001', d.strftime('%#v')) + assert_equal('SAT FEB 3 00:00:00 2001', d.strftime('%^c')) + assert_equal('SAT FEB 3 00:00:00 2001', d.strftime('%#^c')) + end + def test_strftime_v_negative_year # %v formats the year with %Y (sign plus at least four digits), matching # the C extension, not a width-4 %4Y. From b33eeea630638c48a0db31e8f37fbde568cb7298 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 16:03:56 +0900 Subject: [PATCH 108/144] Emit invalid bytes in a strftime format verbatim MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit A format string carrying bytes that are invalid in its own encoding (for example "%\xFF" tagged UTF-8) made the StringScanner regexp raise ArgumentError ("invalid byte sequence"). The C extension copies such bytes through verbatim, so strftime("%\xFF") returns "%\xFF". When the format is not valid in its encoding, scan it byte-wise (binary) and let #strftime re-label the result with the original encoding. Valid formats, including multibyte ones, take the original path unchanged. Verified against the C extension (date 3.5.1). Performance is unchanged for valid formats (only a valid_encoding? check is added on the scanner path): format Ruby before Ruby after strftime %Y/%m/%d %H:%M:%S 141404 139484 (~1.0x) strftime %F 2357521 2363662 (~1.0x) strftime %Y年%m月%d日 222788 224721 (~1.0x) Full suite: 155 tests, 162659 assertions, green. --- lib/date/strftime.rb | 5 +++++ test/date/test_date_strftime.rb | 10 ++++++++++ 2 files changed, 15 insertions(+) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index ed504d0a..9ae34c50 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -49,6 +49,11 @@ def internal_strftime(fmt) return "#{DAYNAMES[w]}, #{MONTHNAMES[@month]} #{PAD2[@day]}, #{y_s}" end + # If the format contains bytes that are invalid in its own encoding, scan + # it byte-wise so the regexp engine does not raise; the C extension copies + # such bytes through verbatim, and #strftime re-labels the result with the + # format's encoding. Valid formats (the common case) are scanned as-is. + fmt = fmt.b unless fmt.valid_encoding? result = +''.encode(fmt.encoding) sc = StringScanner.new(fmt) diff --git a/test/date/test_date_strftime.rb b/test/date/test_date_strftime.rb index ae948949..a6feb6a8 100644 --- a/test/date/test_date_strftime.rb +++ b/test/date/test_date_strftime.rb @@ -229,6 +229,16 @@ def test_strftime_invalid_spec_with_flags end end + def test_strftime_invalid_encoding_format + # An invalid byte sequence in the format string is emitted verbatim + # instead of raising, matching the C extension. + d = Date.new(2001, 2, 3) + fmt = "%\xFF".dup.force_encoding("UTF-8") + assert_equal(fmt, d.strftime(fmt)) + fmt2 = "x%\xFFy".dup.force_encoding("UTF-8") + assert_equal(fmt2, d.strftime(fmt2)) + end + def test_strftime_multibyte_invalid_conversion # A multibyte character after '%' is an invalid conversion specifier and # is emitted verbatim as "%", matching the C extension. It must not From ea1cdd50b06f16ed180f93a0548323905a81778d Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 16:06:18 +0900 Subject: [PATCH 109/144] Validate the zone offset range in _rfc3339 Date._rfc3339 computed the numeric offset from the zone string without range-checking it, so "...+99:99" gave offset 362340 and "...+24:00" gave 86400. The C extension treats an hour >= 24 or minute >= 60 as an invalid offset: it keeps the zone string but reports offset nil. Add the range check. Verified against the C extension (date 3.5.1). Performance is unchanged. (The same missing range check exists in fast_zone_offset, which feeds _iso8601/_xmlschema/_parse; that is a separate, broader fix.) Performance (ips; higher is better; C ext = Ruby 4.0.1 system build): method C ext Ruby before Ruby after Date._rfc3339 off 488706 279500 281425 (~1.0x) Date._rfc3339 Z 488706 351549 356419 (~1.0x) Full suite: 156 tests, 162675 assertions, green. --- lib/date/parse.rb | 6 +++++- test/date/test_date_parse.rb | 15 +++++++++++++++ 2 files changed, 20 insertions(+), 1 deletion(-) diff --git a/lib/date/parse.rb b/lib/date/parse.rb index fa2abf5a..891815f7 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -45,7 +45,11 @@ def _rfc3339(string, limit: 128) if zone[0] == 'Z' || zone[0] == 'z' h[:offset] = 0 else - h[:offset] = (zone[0] == '-' ? -1 : 1) * (zone[1, 2].to_i * 3600 + zone[4, 2].to_i * 60) + hh = zone[1, 2].to_i + mm = zone[4, 2].to_i + # An out-of-range offset (hour >= 24 or minute >= 60) is invalid; the + # C extension keeps the zone string but reports a nil offset. + h[:offset] = (hh < 24 && mm < 60) ? (zone[0] == '-' ? -1 : 1) * (hh * 3600 + mm * 60) : nil end end h diff --git a/test/date/test_date_parse.rb b/test/date/test_date_parse.rb index fc032df6..346969ab 100644 --- a/test/date/test_date_parse.rb +++ b/test/date/test_date_parse.rb @@ -889,6 +889,21 @@ def test__rfc3339 assert_raise(TypeError) {Date._rfc3339('2001-02-03T04:05:06Z'.to_sym)} end + def test__rfc3339_offset_out_of_range + # An out-of-range zone offset (hour >= 24 or minute >= 60) gives a nil + # offset while the remaining fields and the zone string are kept, + # matching the C extension. + %w[+24:00 +25:00 +12:60 +99:99].each do |z| + h = Date._rfc3339("2001-02-03T04:05:06#{z}") + assert_nil(h[:offset], "offset for #{z}") + assert_equal(z, h[:zone], "zone for #{z}") + assert_equal(2001, h[:year]) + end + # In-range boundaries still compute. + assert_equal(86340, Date._rfc3339('2001-02-03T04:05:06+23:59')[:offset]) + assert_equal(0, Date._rfc3339('2001-02-03T04:05:06+00:00')[:offset]) + end + def test__xmlschema h = Date._xmlschema('2001-02-03') assert_equal([2001, 2, 3, nil, nil, nil, nil], From 4a3d8a175e275915da86088fa56e0d2fb812a134 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 16:13:30 +0900 Subject: [PATCH 110/144] Range-check colon-form zone offsets in fast_zone_offset fast_zone_offset computed an offset from +HH:MM / +HHMM without checking its range, so _iso8601/_xmlschema/_parse accepted "+99:99" (362340) and "+24:00" (86400). The C extension range-checks the colon form only (hour >= 24 or minute >= 60 -> nil offset) and leaves the compact +HHMM form unchecked; the rule is format-driven, not method-driven (so _rfc2822's "+9999" still parses). Capture the colon and apply the check only when it is present. This also removes a spurious "invalid offset is ignored" warning: the non-underscore DateTime.iso8601/parse used to build with the bogus large offset and warn; they now receive a nil offset and build cleanly, as the C extension does. (_rfc3339 was fixed separately in the previous commit.) Verified against the C extension (date 3.5.1). Performance is unchanged: method C ext Ruby before Ruby after Date._iso8601 723572 183000 179864 (~1.0x) Date._rfc2822 375804 171183 169697 (~1.0x) Date._parse - 43017 42911 (~1.0x) Full suite: 157 tests, 162688 assertions, green. --- lib/date/parse.rb | 9 +++++++-- test/date/test_date_parse.rb | 17 +++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/lib/date/parse.rb b/lib/date/parse.rb index 891815f7..82094c31 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -786,9 +786,14 @@ def fast_zone_offset(zone_str) if zone_str[0] == '+' || zone_str[0] == '-' sc = StringScanner.new(zone_str) - if sc.scan(/([+-])(\d{2}):?(\d{2})\z/) + if sc.scan(/([+-])(\d{2})(:?)(\d{2})\z/) + hh = sc[2].to_i + mm = sc[4].to_i + # The colon form (+HH:MM) is range-checked: an hour >= 24 or minute + # >= 60 is an invalid offset (nil). The compact form (+HHMM) is not. + return nil if !sc[3].empty? && (hh >= 24 || mm >= 60) sign = sc[1] == '-' ? -1 : 1 - return sign * (sc[2].to_i * 3600 + sc[3].to_i * 60) + return sign * (hh * 3600 + mm * 60) end end diff --git a/test/date/test_date_parse.rb b/test/date/test_date_parse.rb index 346969ab..ba1a4d12 100644 --- a/test/date/test_date_parse.rb +++ b/test/date/test_date_parse.rb @@ -889,6 +889,23 @@ def test__rfc3339 assert_raise(TypeError) {Date._rfc3339('2001-02-03T04:05:06Z'.to_sym)} end + def test_zone_offset_colon_form_range_validated + # The colon offset form (+HH:MM) is range-checked: an hour >= 24 or + # minute >= 60 yields a nil offset. The compact form (+HHMM) is not + # range-checked. This matches the C extension and is format-driven, not + # method-driven. + %w[_parse _iso8601 _xmlschema].each do |m| + assert_nil(Date.send(m, '2001-02-03T04:05:06+99:99')[:offset], "#{m} +99:99") + assert_nil(Date.send(m, '2001-02-03T04:05:06+24:00')[:offset], "#{m} +24:00") + assert_equal(86340, Date.send(m, '2001-02-03T04:05:06+23:59')[:offset], "#{m} +23:59") + end + assert_nil(Date._parse('2001-02-03T04:05:06-99:99')[:offset]) + # Compact form is not range-checked. + assert_equal(362340, Date._parse('2001-02-03T04:05:06+9999')[:offset]) + assert_equal(362340, Date._iso8601('2001-02-03T04:05:06+9999')[:offset]) + assert_equal(362340, Date._rfc2822('Sat, 3 Feb 2001 04:05:06 +9999')[:offset]) + end + def test__rfc3339_offset_out_of_range # An out-of-range zone offset (hour >= 24 or minute >= 60) gives a nil # offset while the remaining fields and the zone string are kept, From 792acc09b5f0819197f12fc72032a7a02c3074c9 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 16:18:56 +0900 Subject: [PATCH 111/144] Replace single-use StringScanner with Regexp#match in parse.rb Each parse fast path allocated a StringScanner only to run one anchored scan and read its captures. Match the (now \A-anchored) regexp against the string directly instead, which is simpler and skips the scanner allocation. Covers the _rfc2822, _xmlschema, _iso8601 (YYYY-MM-DD and YYYYMMDD), _jisx0301 and fast_zone_offset paths. The genuine walk-the-string scanners in strftime/strptime are left as they are. Behaviour is identical (diffed the affected methods before/after); verified against the C extension. Full suite: 157 tests, 162688 assertions, green. Performance (ips; higher is better): method Ruby before Ruby after Date._rfc2822 166622 178472 (1.07x) Date._iso8601 ymd 647549 732450 (1.13x) Date._xmlschema ymd 642057 737178 (1.15x) Date._jisx0301 493111 604299 (1.23x) --- lib/date/parse.rb | 55 +++++++++++++++++++++-------------------------- 1 file changed, 24 insertions(+), 31 deletions(-) diff --git a/lib/date/parse.rb b/lib/date/parse.rb index 82094c31..44dd7526 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -142,18 +142,17 @@ def _rfc2822(string, limit: 128) # Fast path: "Dow, DD Mon YYYY HH:MM:SS +ZZZZ" (31 bytes, 2-digit day) len = string.length if len == 31 - sc = StringScanner.new(string) - if sc.scan(/([A-Za-z]{3}), (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) ([+-]\d{4})\z/) - wday_info = ABBR_DAY_INFO[sc[1].downcase] + if (m = /\A([A-Za-z]{3}), (\d{2}) ([A-Za-z]{3}) (\d{4}) (\d{2}):(\d{2}):(\d{2}) ([+-]\d{4})\z/.match(string)) + wday_info = ABBR_DAY_INFO[m[1].downcase] if wday_info - mon_info = ABBR_MONTH_INFO[sc[3].downcase] + mon_info = ABBR_MONTH_INFO[m[3].downcase] if mon_info - zone = sc[8] + zone = m[8] sign = zone[0] == '-' ? -1 : 1 offset_val = sign * (zone[1, 2].to_i * 3600 + zone[3, 2].to_i * 60) return { - wday: wday_info[0], mday: sc[2].to_i, mon: mon_info[0], - year: sc[4].to_i, hour: sc[5].to_i, min: sc[6].to_i, sec: sc[7].to_i, + wday: wday_info[0], mday: m[2].to_i, mon: mon_info[0], + year: m[4].to_i, hour: m[5].to_i, min: m[6].to_i, sec: m[7].to_i, zone: zone, offset: offset_val } end @@ -218,9 +217,8 @@ def _xmlschema(string, limit: 128) # Fast path: YYYY-MM-DD (exactly 10 bytes, all ASCII) if string.length == 10 - sc = StringScanner.new(string) - if sc.scan(/(\d{4})-(\d{2})-(\d{2})\z/) - return { year: sc[1].to_i, mon: sc[2].to_i, mday: sc[3].to_i } + if (m = /\A(\d{4})-(\d{2})-(\d{2})\z/.match(string)) + return { year: m[1].to_i, mon: m[2].to_i, mday: m[3].to_i } end end @@ -279,9 +277,8 @@ def _iso8601(string, limit: 128) # Fast path: YYYY-MM-DD (exactly 10 bytes, all ASCII) if string.length == 10 - sc = StringScanner.new(string) - if sc.scan(/(\d{4})-(\d{2})-(\d{2})\z/) - return { mday: sc[3].to_i, year: sc[1].to_i, mon: sc[2].to_i } + if (m = /\A(\d{4})-(\d{2})-(\d{2})\z/.match(string)) + return { mday: m[3].to_i, year: m[1].to_i, mon: m[2].to_i } end end @@ -334,14 +331,13 @@ def _jisx0301(string, limit: 128) # Fast path: X##.##.## (9 bytes: era + YY.MM.DD) if string.length == 9 - sc = StringScanner.new(string) - if sc.scan(/([A-Za-z])(\d{2})\.(\d{2})\.(\d{2})\z/) - era_offset = JISX0301_ERA[sc[1].downcase] + if (m = /\A([A-Za-z])(\d{2})\.(\d{2})\.(\d{2})\z/.match(string)) + era_offset = JISX0301_ERA[m[1].downcase] if era_offset return { - year: sc[2].to_i + era_offset, - mon: sc[3].to_i, - mday: sc[4].to_i + year: m[2].to_i + era_offset, + mon: m[3].to_i, + mday: m[4].to_i } end end @@ -406,17 +402,15 @@ def _parse(string, comp = true, limit: 128) # Fast ISO: YYYY-MM-DD (exactly 10 ASCII bytes) if len == 10 - sc = StringScanner.new(string) - if sc.scan(/(\d{4})-(\d{2})-(\d{2})\z/) - return { year: sc[1].to_i, mon: sc[2].to_i, mday: sc[3].to_i } + if (m = /\A(\d{4})-(\d{2})-(\d{2})\z/.match(string)) + return { year: m[1].to_i, mon: m[2].to_i, mday: m[3].to_i } end end # Fast compact: YYYYMMDD (exactly 8 ASCII digit bytes) if len == 8 - sc = StringScanner.new(string) - if sc.scan(/(\d{4})(\d{2})(\d{2})\z/) - return { year: sc[1].to_i, mon: sc[2].to_i, mday: sc[3].to_i } + if (m = /\A(\d{4})(\d{2})(\d{2})\z/.match(string)) + return { year: m[1].to_i, mon: m[2].to_i, mday: m[3].to_i } end end @@ -785,14 +779,13 @@ def fast_zone_offset(zone_str) return 0 if len == 1 && (zone_str[0] == 'Z' || zone_str[0] == 'z') if zone_str[0] == '+' || zone_str[0] == '-' - sc = StringScanner.new(zone_str) - if sc.scan(/([+-])(\d{2})(:?)(\d{2})\z/) - hh = sc[2].to_i - mm = sc[4].to_i + if (m = /\A([+-])(\d{2})(:?)(\d{2})\z/.match(zone_str)) + hh = m[2].to_i + mm = m[4].to_i # The colon form (+HH:MM) is range-checked: an hour >= 24 or minute # >= 60 is an invalid offset (nil). The compact form (+HHMM) is not. - return nil if !sc[3].empty? && (hh >= 24 || mm >= 60) - sign = sc[1] == '-' ? -1 : 1 + return nil if !m[3].empty? && (hh >= 24 || mm >= 60) + sign = m[1] == '-' ? -1 : 1 return sign * (hh * 3600 + mm * 60) end end From e934355baef943b9c2ae2be28a01f620ca376ec9 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 19:26:21 +0900 Subject: [PATCH 112/144] Add exhaustive strftime C-extension comparison tests Generate a strftime comparison matrix covering every conversion specifier crossed with every flag combination (2**5), width, colon count (0-4) and locale modifier, for both a Date and a DateTime -- 66240 cases each, 132480 assertions in all. Expected results come from the C extension (date 3.5.1) and are stored as gzip-compressed fixtures (test/date/strftime_cext_{date,datetime}.tsv.gz, ~238 KB each); gen_strftime_cext_matrix.rb regenerates them under a C-extension Ruby. The test asserts the pure-Ruby strftime reproduces every result. This answers the review request for generated C-extension strftime tests and would systematically catch any strftime behaviour divergence. The whole matrix currently passes with zero differences; it runs in under two seconds. Full suite: 159 tests, 295166 assertions, green. --- test/date/gen_strftime_cext_matrix.rb | 75 ++++++++++++++++++++++++ test/date/strftime_cext_date.tsv.gz | Bin 0 -> 243342 bytes test/date/strftime_cext_datetime.tsv.gz | Bin 0 -> 243228 bytes test/date/test_strftime_cext_matrix.rb | 27 +++++++++ 4 files changed, 102 insertions(+) create mode 100644 test/date/gen_strftime_cext_matrix.rb create mode 100644 test/date/strftime_cext_date.tsv.gz create mode 100644 test/date/strftime_cext_datetime.tsv.gz create mode 100644 test/date/test_strftime_cext_matrix.rb diff --git a/test/date/gen_strftime_cext_matrix.rb b/test/date/gen_strftime_cext_matrix.rb new file mode 100644 index 00000000..8c9dc1c2 --- /dev/null +++ b/test/date/gen_strftime_cext_matrix.rb @@ -0,0 +1,75 @@ +# frozen_string_literal: true +# +# Generator for the strftime C-extension comparison fixtures used by +# test_strftime_cext_matrix.rb. +# +# It enumerates every strftime conversion specifier combined with every +# combination of flags, widths, colon counts and locale modifiers, formats a +# fixed Date and DateTime with each, and records the result. The fixtures must +# be regenerated with a Ruby whose +date+ library is the C extension (the +# behavioural reference), NOT the pure-Ruby library under test: +# +# ruby test/date/gen_strftime_cext_matrix.rb +# +# Each output line is "\t", where is the formatted +# string's #inspect, or "!" when strftime raised. The files are +# gzip-compressed (about 120 KB each). +# +# Fixed reference values: Date.new(2001, 2, 3) and +# DateTime.new(2001, 2, 3, 14, 5, 6, '+07:30'). + +require 'date' +require 'zlib' + +module StrftimeCextMatrix + SPECS = %w[a A b B c C d D e F g G h H I j k l L m M n N p P Q r R s S t T u U V v w W x X y Y z Z + %].freeze + FLAG_CHARS = %w[- _ 0 ^ #].freeze + FLAG_COMBOS = (0...(1 << FLAG_CHARS.length)).map { |mask| + FLAG_CHARS.each_index.select { |i| mask[i] == 1 }.map { |i| FLAG_CHARS[i] }.join + }.freeze + WIDTHS = ['', '1', '10'].freeze + COLONS = ['', ':', '::', ':::', '::::'].freeze + LOCALES = ['', 'E', 'O'].freeze + + REFERENCE = { + 'date' => Date.new(2001, 2, 3), + 'datetime' => DateTime.new(2001, 2, 3, 14, 5, 6, '+07:30'), + }.freeze + + module_function + + def each_format + return enum_for(:each_format) unless block_given? + SPECS.each do |spec| + FLAG_COMBOS.each do |flags| + WIDTHS.each do |w| + COLONS.each do |colons| + LOCALES.each do |loc| + yield "%#{flags}#{w}#{colons}#{loc}#{spec}" + end + end + end + end + end + end + + def encode(obj, fmt) + obj.strftime(fmt).inspect + rescue StandardError => e + "!#{e.class}" + end + + def fixture_path(dir, key) + File.join(dir, "strftime_cext_#{key}.tsv.gz") + end + + def generate(dir = __dir__) + REFERENCE.each do |key, obj| + Zlib::GzipWriter.open(fixture_path(dir, key)) do |gz| + each_format { |fmt| gz.write("#{fmt}\t#{encode(obj, fmt)}\n") } + end + end + end +end + +StrftimeCextMatrix.generate if $PROGRAM_NAME == __FILE__ diff --git a/test/date/strftime_cext_date.tsv.gz b/test/date/strftime_cext_date.tsv.gz new file mode 100644 index 0000000000000000000000000000000000000000..afa72f9b91fff1516538c8cf826f8a68f3fe384b GIT binary patch literal 243342 zcmdqKcRXBc_ck7k8f8e-XhS4|=n{Q&LW&eb^dKY%g6IaLMURLUJ&{Osk|@zeiC!XF zqSw))4TiyZha@=XIpchv^ZWds@AJN&i#_wlJ+t@Rd+oK>eXVQl%@Ra(Ea)V_;uxOg zKv^iyY*d%~scc+_^cGNyeYM1S^7*GIe7v)-OYkqY<3c|{kd0=cVe}ewoQ{cRTLqf) zt3kov)4U<*!kv|CJ3|%QNf1=q&K9zQd3zPIy*kALVcs5Vd%21E+nm}24-M^XqnV4^ zp4g4Y$I9D12wm!DjDIHCSRk4CRk9VqV4l+O&28oEhFh3NIb3>3KFMyhZ>t}^Bxe60 z=_~5;bRyI)LfJXW-yyEfSs(Ab@RAaHmL#IJTD#j|XUm{-a8EUmSSFJk27*D?~6bN-_wqx<)G+{eMFZR6q z)7POZkZVY!ZqkXN=&4OfY5%JQ*RtQ(x5303UP?Aqi?@tP=6KP>IlX+Undl53;UP<* z@R0_hWTx5}B{uL<2<0ezn2ENHRwiu|dt{DZDgC0t-Bya=k4khoHFmo$ev^fEhnYf( z*+p{2X=v%>C~>3h1g~qx4OGolF|m#lF|j!kbaaTCoM^o@H6Cc<%;AgIpOB+HuE%Ac(r#KsOKiaA=CwEhqa`$87_9j0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AkSET&$dttUA%q2C)6R{S@9z>FTpfPR5_g6B=^t5|I8%h*k2RwFWH*4Aef-|6au{$BzzQ>vBx zzuX2s4jsWtbU3~wMkCwx>nL&8dTCXNoHdqh=9^=oi3GYHpcwEu!~OM;s{|2%ALI4{QfBr=NI|H(CiUI3y3f5-;61BwK|N9UOioDgUiEznC3(3r~GQra4rKC?Olalw_9(k`f;{EgborTd@by#K){)p8gyO2P14xu4G`4{eQGT*yP z`n=R3DQ2nH)3?T7u36l;`(UQz&5HQqR{0ZIhUw#~6igAF+y8NDrhj3BX*}8_(<5RB G)&BrYnbG_J literal 0 HcmV?d00001 diff --git a/test/date/strftime_cext_datetime.tsv.gz b/test/date/strftime_cext_datetime.tsv.gz new file mode 100644 index 0000000000000000000000000000000000000000..0d4ce0ce56e55ef782ca55d6d1ba1d52b889dc8c GIT binary patch literal 243228 zcmdqKcUV)~_614_5ReiOq(}=z5tNRC^eTb{3m}3N0YQ3|PUs+AM5)r$BT5IAB2~I{ zq$#}y3B4r*lDvQ=o)XVJ=Y8+~?)Sa{oBXlD-dTI@Ip-R4%oUCZAVDNOz?y*AX0$5$ zBl^_X5w>8v)C)qS>B3> z{QNusf-c2uUdD{qpwc18F3cXhh8?v9L2b=*K-f{!T~BwhKfCk0^5f$e6q>!P>%Q|$ zYLc?ERrJ~jYwAOp4<$0WA7wf>SS&MJKY4E+-|>#|t%k~tE2le84eyOW*Q8vm(mx_E zd`Sy*jyvb^IMg+{*~5_dl=zw&cb?2fXT9El5oXV*6O$xw`$X@_#V3j#UpDw%yW~51 zz6|z7ET#N@^bOAi+elNkjgnBb&$M(c{A6{r!zFK6S=Y4lJiVh;Vy`S2lqY8WBn?bF zW}}kyrsY(W+D(tSC!r;qM%Jk{gOZRUNA#U(vF1zYz1gO{rKY{Drae?sXwP4t$9Y*` zEHL>>N7kJC+G6F^(LD=l1WThX--BbN8q+T?OGTnx+nqW5`OLVEGD|%gc=vJq zBIGh0ZjgR>JYjxUMlSSH$>sbPE?sp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coverage gaps by exercising behaviour that no test reached before: - strptime "%a %b %d %Y" fast path (_strptime and strptime) - strftime whole-format fast paths "%Y-%m-%dT%H:%M:%S%z" and "%A, %B %d, %Y" - _rfc2822 two-digit-day fast path and _parse US month-name fast path - valid_civil?/valid_ordinal?/gregorian_leap?/julian_leap?/leap? happy paths (existing tests only covered their TypeError branches) - step with a negative and a non-integer step, step 0 on the general path, and upto/downto on a non-Date receiver - deconstruct_keys with a single key, for Date and DateTime lib/date line coverage rises from 93.23% to 96.77%. Full suite: 167 tests, 295218 assertions, green. --- test/date/test_date.rb | 22 ++++++++++++++++++++++ test/date/test_date_arith.rb | 18 ++++++++++++++++++ test/date/test_date_new.rb | 9 +++++++++ test/date/test_date_parse.rb | 12 ++++++++++++ test/date/test_date_strftime.rb | 8 ++++++++ test/date/test_date_strptime.rb | 8 ++++++++ 6 files changed, 77 insertions(+) diff --git a/test/date/test_date.rb b/test/date/test_date.rb index 7e37fc94..80191abf 100644 --- a/test/date/test_date.rb +++ b/test/date/test_date.rb @@ -6,6 +6,28 @@ class DateSub < Date; end class DateTimeSub < DateTime; end class TestDate < Test::Unit::TestCase + def test_deconstruct_keys_single_key + d = Date.new(1999, 5, 23) + assert_equal({year: 1999}, d.deconstruct_keys([:year])) + assert_equal({month: 5}, d.deconstruct_keys([:month])) + assert_equal({day: 23}, d.deconstruct_keys([:day])) + assert_equal({wday: 0}, d.deconstruct_keys([:wday])) + assert_equal({yday: 143}, d.deconstruct_keys([:yday])) + assert_equal({}, d.deconstruct_keys([:century])) + dt = DateTime.new(1999, 5, 23, 4, 5, 6, '+03:30') + assert_equal({year: 1999}, dt.deconstruct_keys([:year])) + assert_equal({month: 5}, dt.deconstruct_keys([:month])) + assert_equal({day: 23}, dt.deconstruct_keys([:day])) + assert_equal({wday: 0}, dt.deconstruct_keys([:wday])) + assert_equal({yday: 143}, dt.deconstruct_keys([:yday])) + assert_equal({hour: 4}, dt.deconstruct_keys([:hour])) + assert_equal({min: 5}, dt.deconstruct_keys([:min])) + assert_equal({sec: 6}, dt.deconstruct_keys([:sec])) + assert_equal({sec_fraction: 0r}, dt.deconstruct_keys([:sec_fraction])) + assert_equal({zone: '+03:30'}, dt.deconstruct_keys([:zone])) + assert_equal({}, dt.deconstruct_keys([:century])) + end + def test_range_infinite_float today = Date.today r = today...Float::INFINITY diff --git a/test/date/test_date_arith.rb b/test/date/test_date_arith.rb index c3633c94..705abba5 100644 --- a/test/date/test_date_arith.rb +++ b/test/date/test_date_arith.rb @@ -7,6 +7,24 @@ class Rat < Numeric def to_r; self; end end + def test_step_upto_downto_additional_paths + # step with a negative integer step (Date fast loop). + r = []; Date.new(2001, 2, 5).step(Date.new(2001, 2, 1), -2) { |d| r << d.mday } + assert_equal([5, 3, 1], r) + # step with a non-integer step takes the general path, both directions. + r = []; Date.new(2001, 2, 1).step(Date.new(2001, 2, 5), 2r) { |d| r << d.mday } + assert_equal([1, 3, 5], r) + r = []; Date.new(2001, 2, 5).step(Date.new(2001, 2, 1), -2r) { |d| r << d.mday } + assert_equal([5, 3, 1], r) + # a zero step is rejected on the general path too. + assert_raise(ArgumentError) { Date.new(2001, 2, 1).step(Date.new(2001, 2, 3), 0r) { } } + # upto/downto general path (non-Date receiver delegates to step). + r = []; DateTime.new(2001, 2, 1).upto(DateTime.new(2001, 2, 3)) { |d| r << d.mday } + assert_equal([1, 2, 3], r) + r = []; DateTime.new(2001, 2, 3).downto(DateTime.new(2001, 2, 1)) { |d| r << d.mday } + assert_equal([3, 2, 1], r) + end + def test_new_offset d = DateTime.new(2002, 3, 14) assert_equal(Rational(9, 24), d.new_offset(Rational(9, 24)).offset) diff --git a/test/date/test_date_new.rb b/test/date/test_date_new.rb index 2c965e9b..f5379eb8 100644 --- a/test/date/test_date_new.rb +++ b/test/date/test_date_new.rb @@ -4,6 +4,15 @@ class TestDateNew < Test::Unit::TestCase + def test_valid_and_leap_predicates_true + # Happy paths for the predicate class methods. + assert_equal(true, Date.valid_civil?(2001, 2, 3)) + assert_equal(true, Date.valid_ordinal?(2001, 60)) + assert_equal(true, Date.gregorian_leap?(2000)) + assert_equal(true, Date.julian_leap?(1900)) + assert_equal(true, Date.leap?(2000)) + end + def test_jd d = Date.jd dt = DateTime.jd diff --git a/test/date/test_date_parse.rb b/test/date/test_date_parse.rb index ba1a4d12..7a38c61b 100644 --- a/test/date/test_date_parse.rb +++ b/test/date/test_date_parse.rb @@ -5,6 +5,18 @@ class TestDateParse < Test::Unit::TestCase + def test__parse_us_month_name_fast_path + assert_equal({year: 2001, mon: 2, mday: 3}, Date._parse('February 3, 2001')) + assert_equal({year: 2001, mon: 2, mday: 3}, Date._parse('Feb 3 2001')) + end + + def test__rfc2822_two_digit_day_fast_path + # "Dow, DD Mon YYYY HH:MM:SS +ZZZZ" (31 bytes, 2-digit day) fast path. + h = Date._rfc2822('Sat, 03 Feb 2001 04:05:06 +0700') + assert_equal([6, 3, 2, 2001, 4, 5, 6, '+0700', 25200], + h.values_at(:wday, :mday, :mon, :year, :hour, :min, :sec, :zone, :offset)) + end + def test__parse [ # ctime(3), asctime(3) diff --git a/test/date/test_date_strftime.rb b/test/date/test_date_strftime.rb index a6feb6a8..e9154e10 100644 --- a/test/date/test_date_strftime.rb +++ b/test/date/test_date_strftime.rb @@ -67,6 +67,14 @@ class TestDateStrftime < Test::Unit::TestCase STRFTIME_2001_02_03.update(STRFTIME_2001_02_03_CVS19) STRFTIME_2001_02_03.update(STRFTIME_2001_02_03_GNUext) + def test_strftime_whole_string_fast_paths + # Dedicated whole-format fast paths in internal_strftime. + assert_equal('2001-02-03T04:05:06+0700', + DateTime.new(2001, 2, 3, 4, 5, 6, '+07:00').strftime('%Y-%m-%dT%H:%M:%S%z')) + assert_equal('Saturday, February 03, 2001', + Date.new(2001, 2, 3).strftime('%A, %B %d, %Y')) + end + def test_strftime d = Date.new(2001,2,3) STRFTIME_2001_02_03.each do |f, s| diff --git a/test/date/test_date_strptime.rb b/test/date/test_date_strptime.rb index f68f749e..0bf76242 100644 --- a/test/date/test_date_strptime.rb +++ b/test/date/test_date_strptime.rb @@ -67,6 +67,14 @@ class TestDateStrptime < Test::Unit::TestCase STRFTIME_2001_02_03.update(STRFTIME_2001_02_03_CVS19) STRFTIME_2001_02_03.update(STRFTIME_2001_02_03_GNUext) + def test__strptime_abdy_fast_path + # "%a %b %d %Y" has a dedicated fast path in _strptime/strptime. + assert_equal({wday: 6, mon: 2, mday: 3, year: 2001}, + Date._strptime('Sat Feb 03 2001', '%a %b %d %Y')) + assert_equal(Date.new(2001, 2, 3), + Date.strptime('Sat Feb 03 2001', '%a %b %d %Y')) + end + def test__strptime STRFTIME_2001_02_03.each do |f, s| if (f == '%I' and s[0] == '12') or From b9c83a0f192dff19d86e71c9d3640f573d46f083 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 19:46:12 +0900 Subject: [PATCH 114/144] Cover more strftime/strptime edge paths Add tests for reachable edge paths that were still uncovered: - strftime with a flag after the width ("%1-5d") or a precision ("%1.2d"), %Y/%G through the full year formatter with an explicit width (positive and negative years), composite conversions with a width ("%5c", "%12x"), and %:z / %::z on a zoned DateTime - fast_ymd year padding for small-positive and negative years ("%F") - %c/%D/%x reached through the scanner rather than the whole-string fast path (i.e. not standing alone) - strptime "%a %b %d %Y" with full day/month names and with an invalid weekday abbreviation, and _strptime rejecting a non-String argument lib/date line coverage rises to 97.38%; strftime.rb to 98.93%. Full suite green. --- test/date/test_date_strftime.rb | 26 ++++++++++++++++++++++++++ test/date/test_date_strptime.rb | 15 +++++++++++++++ 2 files changed, 41 insertions(+) diff --git a/test/date/test_date_strftime.rb b/test/date/test_date_strftime.rb index e9154e10..271c773b 100644 --- a/test/date/test_date_strftime.rb +++ b/test/date/test_date_strftime.rb @@ -67,6 +67,32 @@ class TestDateStrftime < Test::Unit::TestCase STRFTIME_2001_02_03.update(STRFTIME_2001_02_03_CVS19) STRFTIME_2001_02_03.update(STRFTIME_2001_02_03_GNUext) + def test_strftime_width_flag_precision_and_composite_edges + d = Date.new(2001, 2, 3) + assert_equal('%1-5d', d.strftime('%1-5d')) # flag after width -> verbatim + assert_equal('%1.2d', d.strftime('%1.2d')) # precision '.' -> verbatim + assert_equal('-0005', Date.new(-5, 2, 3).strftime('%G')) + assert_equal('2001', d.strftime('%1G')) + assert_equal('-5', Date.new(-5, 2, 3).strftime('%1G')) + assert_equal('Sat Feb 3 00:00:00 2001', d.strftime('%5c')) + assert_equal(' 02/03/01', d.strftime('%12x')) + dt = DateTime.new(2001, 2, 3, 4, 5, 6, '+07:30') + assert_equal('+07:30', dt.strftime('%:z')) + assert_equal('+07:30:00', dt.strftime('%::z')) + end + + def test_strftime_fast_ymd_and_embedded_composites + # fast_ymd year padding for small positive and negative years. + assert_equal('0500-02-03', Date.new(500, 2, 3).strftime('%F')) + assert_equal('-0005-02-03', Date.new(-5, 2, 3).strftime('%F')) + # %c/%D/%x reached through the scanner (not the whole-string fast path, + # which only matches those specs standing alone). + d = Date.new(2001, 2, 3) + assert_equal('(Sat Feb 3 00:00:00 2001)', d.strftime('(%c)')) + assert_equal('(02/03/01)', d.strftime('(%D)')) + assert_equal('(02/03/01)', d.strftime('(%x)')) + end + def test_strftime_whole_string_fast_paths # Dedicated whole-format fast paths in internal_strftime. assert_equal('2001-02-03T04:05:06+0700', diff --git a/test/date/test_date_strptime.rb b/test/date/test_date_strptime.rb index 0bf76242..4a465605 100644 --- a/test/date/test_date_strptime.rb +++ b/test/date/test_date_strptime.rb @@ -67,6 +67,21 @@ class TestDateStrptime < Test::Unit::TestCase STRFTIME_2001_02_03.update(STRFTIME_2001_02_03_CVS19) STRFTIME_2001_02_03.update(STRFTIME_2001_02_03_GNUext) + def test__strptime_abdy_full_name_and_invalid + # Full day/month names (abbreviation plus matching tail) are accepted. + assert_equal({wday: 6, mon: 2, mday: 3, year: 2001}, + Date._strptime('Saturday February 03 2001', '%a %b %d %Y')) + assert_equal(Date.new(2001, 2, 3), + Date.strptime('Saturday February 03 2001', '%a %b %d %Y')) + # An unknown weekday abbreviation is invalid. + assert_raise(Date::Error) { Date.strptime('Xxx Feb 03 2001', '%a %b %d %Y') } + end + + def test__strptime_rejects_non_string + assert_raise(TypeError) { Date._strptime(true, '%F') } + assert_raise(TypeError) { Date._strptime(false, '%F') } + end + def test__strptime_abdy_fast_path # "%a %b %d %Y" has a dedicated fast path in _strptime/strptime. assert_equal({wday: 6, mon: 2, mday: 3, year: 2001}, From 7ab5f0787fd82b2a29756c927245bccc4072cd81 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 19:48:04 +0900 Subject: [PATCH 115/144] Drop unreachable branches in strftime Two branches could never run given their callers: - in internal_strftime, the literal scan consumes every non-'%' byte, so after it fails the scanner is always at a '%'; the "unless sc.skip(/%/)" fallback was dead. Just step over the '%'. - in fmt_z, four-or-more colons are rejected by internal_strftime before fmt_z is called, so the colon count is always 0..3; fold the former explicit "when 0" into the else (which now handles the 0 case) and drop the separate unreachable else. Behaviour is unchanged (the exhaustive strftime matrix exercises %z with every colon count); strftime.rb reaches 100% line coverage. Full suite green. --- lib/date/strftime.rb | 12 ++++-------- 1 file changed, 4 insertions(+), 8 deletions(-) diff --git a/lib/date/strftime.rb b/lib/date/strftime.rb index 9ae34c50..9d43654f 100644 --- a/lib/date/strftime.rb +++ b/lib/date/strftime.rb @@ -64,11 +64,9 @@ def internal_strftime(fmt) next end - # Must be '%' or something unexpected - unless sc.skip(/%/) - result << sc.getch - next - end + # The scan above consumes every non-'%' byte, so the scanner is now + # positioned at a '%'; step over it. + sc.skip(/%/) if sc.eos? result << '%' @@ -473,10 +471,8 @@ def fmt_z(colons, width, flags) else "#{sign}#{hh_s}" end - when 0 + else # 0; internal_strftime rejects four or more colons before this "#{sign}#{hh_s}#{mm_s}" - else - "#{sign}#{hh_s}:#{mm_s}" end if flags & FL_SPACE != 0 From 4eca0d45746c1bb8b011b25a5bec1a34498ce471 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 19:54:56 +0900 Subject: [PATCH 116/144] Remove dead jd/ordinal helpers; match C ext fractional-cutover inspect - Delete jd_to_civil, ordinal_to_jd and jd_to_ordinal from Date's singleton: ordinal_to_jd and jd_to_ordinal have no callers at all, and jd_to_civil is only referenced by the dead jd_to_ordinal. - inspect: print the integer part of a finite start even when it is fractional (e.g. Date.new(2001,2,3,2400000.5).inspect now ends in "2400000j", as the C extension prints it, not "2400000.5j"). This also collapses the two whole/fractional branches into one. Behaviour is unchanged except the fractional-start inspect (now matching the C extension). Full suite green. --- lib/date/core.rb | 30 +++--------------------------- 1 file changed, 3 insertions(+), 27 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 613f26d2..32229cc8 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -439,29 +439,6 @@ def jd_to_julian(jd) [year, mon, day] end - # JD -> (year, month, day), respecting start (cutover). - def jd_to_civil(jd, sg) - if sg == Float::INFINITY - jd_to_julian(jd) - elsif sg == -Float::INFINITY || jd >= sg - jd_to_gregorian(jd) - else - jd_to_julian(jd) - end - end - - # Ordinal (year, day-of-year) -> JD - def ordinal_to_jd(y, d, sg) - civil_to_jd(y, 1, 1, sg) + d - 1 - end - - # JD -> (year, day-of-year) - def jd_to_ordinal(jd, sg) - y, = jd_to_civil(jd, sg) - jd_jan1 = civil_to_jd(y, 1, 1, sg) - [y, jd - jd_jan1 + 1] - end - # Commercial (ISO week: cwyear, cweek, cwday) -> JD def commercial_to_jd(y, w, d, sg = -Float::INFINITY) # Jan 4 is always in week 1 (ISO 8601) @@ -1659,17 +1636,16 @@ def inspect end # Format the start (cutover) for #inspect: "Inf"/"-Inf" for the infinite - # sentinels and an integer for whole values. + # sentinels, otherwise the integer part of the start (matching the C + # extension, which prints a whole jd even for a fractional start). private def inspect_sg sg = @start if sg == Float::INFINITY 'Inf' elsif sg == -Float::INFINITY '-Inf' - elsif sg == sg.to_i - sg.to_i.to_s else - sg.to_s + sg.to_i.to_s end end From 5f84be7e66b882ae06d7988b4beb85e1eeaf771b Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 19:55:04 +0900 Subject: [PATCH 117/144] Add coverage tests for calendar starts, ordinal, comparisons and errors Close further coverage gaps with reachable, oracle-verified cases: - Date#inspect with Julian, Gregorian and fractional starts - Date#<=> and #== against an incomparable object - Date.ordinal and dates with Julian/Gregorian starts and a pre-reform date - Date#amjd - DateTime.new with a non-numeric offset and with a nil argument (TypeError) - _strptime "%p" with a non-meridian string, strptime with an invalid y-m-d - _rfc2822 with obsolete folding whitespace (CR/LF) lib/date line coverage reaches 98.18% (strftime 100%, core 98.53%). Full suite green. --- test/date/test_date.rb | 15 +++++++++++++++ test/date/test_date_attr.rb | 4 ++++ test/date/test_date_new.rb | 12 ++++++++++++ test/date/test_date_parse.rb | 6 ++++++ test/date/test_date_strptime.rb | 5 +++++ 5 files changed, 42 insertions(+) diff --git a/test/date/test_date.rb b/test/date/test_date.rb index 80191abf..e002a5e6 100644 --- a/test/date/test_date.rb +++ b/test/date/test_date.rb @@ -6,6 +6,21 @@ class DateSub < Date; end class DateTimeSub < DateTime; end class TestDate < Test::Unit::TestCase + def test_inspect_start_variants + assert_equal('#', + Date.new(2001, 2, 3, Date::JULIAN).inspect) + assert_equal('#', + Date.new(2001, 2, 3, Date::GREGORIAN).inspect) + # A fractional start prints as a whole jd, matching the C extension. + assert_equal('#', + Date.new(2001, 2, 3, 2400000.5).inspect) + end + + def test_spaceship_and_equal_with_incomparable + assert_nil(Date.new(2001, 2, 3) <=> Object.new) + assert_equal(false, Date.new(2001, 2, 3) == Object.new) + end + def test_deconstruct_keys_single_key d = Date.new(1999, 5, 23) assert_equal({year: 1999}, d.deconstruct_keys([:year])) diff --git a/test/date/test_date_attr.rb b/test/date/test_date_attr.rb index 1e4d1bfd..23c17a49 100644 --- a/test/date/test_date_attr.rb +++ b/test/date/test_date_attr.rb @@ -4,6 +4,10 @@ class TestDateAttr < Test::Unit::TestCase + def test_amjd + assert_equal(Rational(51943, 1), Date.new(2001, 2, 3).amjd) + end + def test__attr date = Date.new(1965, 5, 23) datetime = DateTime.new(1965, 5, 23, 22, 31, 59) diff --git a/test/date/test_date_new.rb b/test/date/test_date_new.rb index f5379eb8..6fa8ff42 100644 --- a/test/date/test_date_new.rb +++ b/test/date/test_date_new.rb @@ -4,6 +4,18 @@ class TestDateNew < Test::Unit::TestCase + def test_ordinal_and_calendar_start_paths + assert_equal(Date.new(2001, 3, 1), Date.ordinal(2001, 60)) + assert_equal(2, Date.new(2001, 2, 3, Date::JULIAN).month) + assert_equal(2, Date.new(2001, 2, 3, Date::GREGORIAN).month) + assert_equal(2086308, Date.new(1000, 1, 1).jd) # before the reform -> Julian + end + + def test_datetime_new_offset_type_errors + assert_raise(TypeError) { DateTime.new(2001, 1, 1, 0, 0, 0, Object.new) } + assert_raise(TypeError) { DateTime.new(nil) } + end + def test_valid_and_leap_predicates_true # Happy paths for the predicate class methods. assert_equal(true, Date.valid_civil?(2001, 2, 3)) diff --git a/test/date/test_date_parse.rb b/test/date/test_date_parse.rb index 7a38c61b..d761b000 100644 --- a/test/date/test_date_parse.rb +++ b/test/date/test_date_parse.rb @@ -10,6 +10,12 @@ def test__parse_us_month_name_fast_path assert_equal({year: 2001, mon: 2, mday: 3}, Date._parse('Feb 3 2001')) end + def test__rfc2822_folding_whitespace + # Obsolete folding whitespace (CR/LF) is collapsed before parsing. + h = Date._rfc2822("Sat,\r\n 3 Feb 2001 00:00:00 +0000") + assert_equal([3, 2, 2001], h.values_at(:mday, :mon, :year)) + end + def test__rfc2822_two_digit_day_fast_path # "Dow, DD Mon YYYY HH:MM:SS +ZZZZ" (31 bytes, 2-digit day) fast path. h = Date._rfc2822('Sat, 03 Feb 2001 04:05:06 +0700') diff --git a/test/date/test_date_strptime.rb b/test/date/test_date_strptime.rb index 4a465605..05ae3a3a 100644 --- a/test/date/test_date_strptime.rb +++ b/test/date/test_date_strptime.rb @@ -67,6 +67,11 @@ class TestDateStrptime < Test::Unit::TestCase STRFTIME_2001_02_03.update(STRFTIME_2001_02_03_CVS19) STRFTIME_2001_02_03.update(STRFTIME_2001_02_03_GNUext) + def test__strptime_meridian_failure_and_invalid_ymd + assert_nil(Date._strptime('zz', '%p')) # not AM/PM + assert_raise(Date::Error) { Date.strptime('2001-13-45', '%F') } # bad m/d + end + def test__strptime_abdy_full_name_and_invalid # Full day/month names (abbreviation plus matching tail) are accepted. assert_equal({wday: 6, mon: 2, mday: 3, year: 2001}, From 6d4df74da521b2fd512fb07aca86e61cd9b6e62e Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 20:06:10 +0900 Subject: [PATCH 118/144] Add Marshal cross-version/cross-implementation test Verify the pure-Ruby Date/DateTime load Marshal data written by the C extension and round-trip their own dumps. A committed fixture (test/date/marshal_cext.dump, 225 bytes) holds a spread of objects serialised by the C extension (date 3.5.1): Date with Italian, Julian, Gregorian, negative-year, jd-based and pre-reform values, and DateTime with no offset, a positive and a negative offset, and a sub-second. The marshal_dump array format is identical across date 3.3.x, 3.4.x and 3.5.x (checked against those gems), so the fixture also covers data written by older versions. gen_marshal_cext.rb regenerates it under a C-extension Ruby. Full suite: 179 tests, 295254 assertions, green. --- test/date/gen_marshal_cext.rb | 45 +++++++++++++++++++++++++++++++++ test/date/marshal_cext.dump | Bin 0 -> 225 bytes test/date/test_marshal_cext.rb | 31 +++++++++++++++++++++++ 3 files changed, 76 insertions(+) create mode 100644 test/date/gen_marshal_cext.rb create mode 100644 test/date/marshal_cext.dump create mode 100644 test/date/test_marshal_cext.rb diff --git a/test/date/gen_marshal_cext.rb b/test/date/gen_marshal_cext.rb new file mode 100644 index 00000000..f2099e97 --- /dev/null +++ b/test/date/gen_marshal_cext.rb @@ -0,0 +1,45 @@ +# frozen_string_literal: true +# +# Generator for the Marshal compatibility fixture used by +# test_marshal_cext.rb. It serialises a spread of Date and DateTime objects +# and writes the bytes to test/date/marshal_cext.dump. Regenerate it with a +# Ruby whose +date+ library is the C extension (the reference whose on-disk +# format the pure-Ruby library must keep reading): +# +# ruby test/date/gen_marshal_cext.rb +# +# The Date marshal format (the marshal_dump array) has been identical across +# date 3.3.x, 3.4.x and 3.5.x, so the fixture also stands in for data written +# by those older gems. + +require 'date' + +module MarshalCextFixture + module_function + + # The exact objects serialised into the fixture. The test rebuilds this same + # list with the pure-Ruby library and checks each loaded object against it. + def objects + [ + Date.new(2001, 2, 3), + Date.new(2001, 2, 3, Date::JULIAN), + Date.new(2001, 2, 3, Date::GREGORIAN), + Date.new(-5, 1, 1), + Date.jd(2451944), + Date.new(1000, 1, 1), # before the reform (Julian) + DateTime.new(2001, 2, 3, 4, 5, 6), + DateTime.new(2001, 2, 3, 4, 5, 6, '+07:30'), + DateTime.new(2001, 2, 3, 4, 5, Rational(6789, 1000), '-05:00'), + ] + end + + def fixture_path(dir = __dir__) + File.join(dir, 'marshal_cext.dump') + end + + def generate(dir = __dir__) + File.binwrite(fixture_path(dir), Marshal.dump(objects)) + end +end + +MarshalCextFixture.generate if $PROGRAM_NAME == __FILE__ diff --git a/test/date/marshal_cext.dump b/test/date/marshal_cext.dump new file mode 100644 index 0000000000000000000000000000000000000000..c820d6385ba3d6e74dd85eb6795d2e1bb4dc418f GIT binary patch literal 225 zcmZSKh~^8m;&e$YNsZ>tWXNQGk*Nx#fG~~6$jH*t(9AH@ngJs96)we*nU@9^M(E(w zMHW9`Ed?>jfdf-5lGu`~@^E!lydal^Wac8dhN;LBBoETT264!9phK9e6d8fSOcj|( X5+J8A9jeb{anNVi&-}MxrvnE7_Le%} literal 0 HcmV?d00001 diff --git a/test/date/test_marshal_cext.rb b/test/date/test_marshal_cext.rb new file mode 100644 index 00000000..88933011 --- /dev/null +++ b/test/date/test_marshal_cext.rb @@ -0,0 +1,31 @@ +# frozen_string_literal: true +require 'test/unit' +require 'date' +require_relative 'gen_marshal_cext' + +# Verify the pure-Ruby Date/DateTime can load Marshal data produced by the C +# extension (date 3.5.1; the format is shared with 3.3.x/3.4.x), and that a +# pure-Ruby dump round-trips. See gen_marshal_cext.rb for the fixture. +class TestMarshalCext < Test::Unit::TestCase + def attrs(d) + a = [d.class, d.jd, d.start, d.to_s] + a.concat([d.hour, d.min, d.sec, d.sec_fraction, d.offset]) if d.is_a?(DateTime) + a + end + + def test_loads_c_extension_marshal + expected = MarshalCextFixture.objects + loaded = Marshal.load(File.binread(MarshalCextFixture.fixture_path(__dir__))) + assert_equal(expected.size, loaded.size) + expected.zip(loaded).each_with_index do |(exp, got), i| + assert_equal(attrs(exp), attrs(got), "object #{i} (#{exp.inspect})") + end + end + + def test_pure_ruby_round_trip + MarshalCextFixture.objects.each do |d| + got = Marshal.load(Marshal.dump(d)) + assert_equal(attrs(d), attrs(got), d.inspect) + end + end +end From 45e89295ab126ed9497d982f931ace863420ea1a Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 20:16:01 +0900 Subject: [PATCH 119/144] Honor the offset in DateTime#rfc2822 and #httpdate Both methods ignored a DateTime's offset: rfc2822 always printed "+0000" and httpdate printed the local time labelled "GMT". The C extension prints the real offset for rfc2822 and converts the instant to UTC for httpdate. Use strftime_zoff for the rfc2822 offset, and format the new_offset(0) (UTC) value for httpdate. Date (always UTC midnight) is unchanged. Verified against the C extension (date 3.5.1) across several offsets, including ones that cross the day boundary. DateTime is deprecated and these are cold paths; the correctness fix costs some speed there (the new_offset allocation in httpdate especially), while Date is unaffected. Performance (ips; higher is better; C ext = Ruby 4.0.1 system build): method C ext Ruby before Ruby after Date#rfc2822 1974374 1985895 1977742 (~1.0x) Date#httpdate 1663871 1997072 1936237 (~0.97x) DateTime#rfc2822 - 1471460 1044412 (0.71x) DateTime#httpdate - 1460089 359709 (0.25x) Full suite: 180 tests, 295258 assertions, green. --- lib/date/core.rb | 9 +++++++-- test/date/test_date_strftime.rb | 12 ++++++++++++ 2 files changed, 19 insertions(+), 2 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 32229cc8..2bb67407 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1534,7 +1534,7 @@ def rfc2822 if instance_of?(Date) "#{ABBR_DAYNAMES[w]}, #{@day} #{ABBR_MONTHNAMES[@month]} #{y_s} 00:00:00 +0000" else - "#{ABBR_DAYNAMES[w]}, #{@day} #{ABBR_MONTHNAMES[@month]} #{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} +0000" + "#{ABBR_DAYNAMES[w]}, #{@day} #{ABBR_MONTHNAMES[@month]} #{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} #{strftime_zoff}" end end alias_method :rfc822, :rfc2822 @@ -1555,7 +1555,12 @@ def httpdate if instance_of?(Date) "#{ABBR_DAYNAMES[w]}, #{PAD2[@day]} #{ABBR_MONTHNAMES[@month]} #{y_s} 00:00:00 GMT" else - "#{ABBR_DAYNAMES[w]}, #{PAD2[@day]} #{ABBR_MONTHNAMES[@month]} #{y_s} #{PAD2[internal_hour]}:#{PAD2[internal_min]}:#{PAD2[internal_sec]} GMT" + # HTTP dates are always in GMT, so convert the instant to UTC first. + u = new_offset(0) + uw = (u.jd + 1) % 7 + uy = u.year + uy_s = uy >= 1000 ? uy.to_s : (uy >= 0 ? format('%04d', uy) : format('-%04d', -uy)) + "#{ABBR_DAYNAMES[uw]}, #{PAD2[u.day]} #{ABBR_MONTHNAMES[u.mon]} #{uy_s} #{PAD2[u.hour]}:#{PAD2[u.min]}:#{PAD2[u.sec]} GMT" end end diff --git a/test/date/test_date_strftime.rb b/test/date/test_date_strftime.rb index 271c773b..27f02e8a 100644 --- a/test/date/test_date_strftime.rb +++ b/test/date/test_date_strftime.rb @@ -456,6 +456,18 @@ def test_strftime__gnuext_complex assert_equal('SAT FEB 3 04:05:06 +09:00 2001', d.strftime('%^+')) end + def test_rfc2822_httpdate_with_offset + # rfc2822 keeps local time and shows the real offset; httpdate converts + # the instant to UTC, matching the C extension. + d = DateTime.new(2001, 2, 3, 4, 5, 6, '+07:00') + assert_equal('Sat, 3 Feb 2001 04:05:06 +0700', d.rfc2822) + assert_equal('Fri, 02 Feb 2001 21:05:06 GMT', d.httpdate) + # an offset that pushes the UTC instant into the next day + d2 = DateTime.new(2001, 2, 3, 22, 5, 6, '-05:00') + assert_equal('Sat, 3 Feb 2001 22:05:06 -0500', d2.rfc2822) + assert_equal('Sun, 04 Feb 2001 03:05:06 GMT', d2.httpdate) + end + def test__different_format d = Date.new(2001,2,3) From c73d959223aa87ef36d38264045452b608e5b1c1 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 20:24:41 +0900 Subject: [PATCH 120/144] Use Regexp#match in sp_zone_to_diff and align its offset validation sp_zone_to_diff built a StringScanner only to run one anchored scan, the same single-use pattern the review asked to replace with Regexp#match (the walk-the-string scanners in internal_strftime and sp_run, which scan repeatedly, are left as they are). While converting it, align its range check with the C extension and with fast_zone_offset: only the colon form (+HH:MM) is range-checked, so strptime "%z" now accepts a compact out-of-range offset ("+9999" -> 362340) as the C extension does, instead of returning nil. Verified against the C extension (date 3.5.1). Full suite: 181 tests, 295267 assertions, green. --- lib/date/strptime.rb | 13 +++++++------ test/date/test_date_strptime.rb | 10 ++++++++++ 2 files changed, 17 insertions(+), 6 deletions(-) diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index 412c0289..85ea79ce 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -551,12 +551,13 @@ def sp_zone_to_diff(zone_str) len = zone_str.length c0 = zone_str[0] if c0 == '+' || c0 == '-' - sc = StringScanner.new(zone_str) - if sc.scan(/([+-])(\d{2}):?(\d{2})\z/) - sign = sc[1] == '-' ? -1 : 1 - h = sc[2].to_i - m = sc[3].to_i - return nil if h > 23 || m > 59 + if (md = /\A([+-])(\d{2})(:?)(\d{2})\z/.match(zone_str)) + sign = md[1] == '-' ? -1 : 1 + h = md[2].to_i + m = md[4].to_i + # Only the colon form (+HH:MM) is range-checked, matching the C + # extension; the compact form (+HHMM) is accepted as-is. + return nil if !md[3].empty? && (h > 23 || m > 59) return sign * (h * 3600 + m * 60) end elsif len == 1 && (c0 == 'Z' || c0 == 'z') diff --git a/test/date/test_date_strptime.rb b/test/date/test_date_strptime.rb index 05ae3a3a..90c1d842 100644 --- a/test/date/test_date_strptime.rb +++ b/test/date/test_date_strptime.rb @@ -67,6 +67,16 @@ class TestDateStrptime < Test::Unit::TestCase STRFTIME_2001_02_03.update(STRFTIME_2001_02_03_CVS19) STRFTIME_2001_02_03.update(STRFTIME_2001_02_03_GNUext) + def test__strptime_zone_offset_validation + # Compact +HHMM is accepted as given; the colon form +HH:MM is + # range-checked (hour > 23 or minute > 59 -> nil), matching the C ext. + assert_equal(362340, Date._strptime('2001 +9999', '%Y %z')[:offset]) + assert_equal(90000, Date._strptime('2001 +2500', '%Y %z')[:offset]) + assert_equal(25200, Date._strptime('2001 +07:00', '%Y %z')[:offset]) + assert_nil(Date._strptime('2001 +12:60', '%Y %z')[:offset]) + assert_nil(Date._strptime('2001 +99:99', '%Y %z')[:offset]) + end + def test__strptime_meridian_failure_and_invalid_ymd assert_nil(Date._strptime('zz', '%p')) # not AM/PM assert_raise(Date::Error) { Date.strptime('2001-13-45', '%F') } # bad m/d From 8c7b6ab7a0294f336c6d9208a08cb1c5c9146824 Mon Sep 17 00:00:00 2001 From: jinroq Date: Mon, 23 Nov 2026 20:52:26 +0900 Subject: [PATCH 121/144] Raise TypeError from Date#>> and Date#<< for a non-integer argument `d >> n` / `d << n` silently coerced the month count with `to_i`, so a nil or a String was treated as 0/1 (and `<<` with nil raised NoMethodError from negating nil). Coerce the argument the way the C extension does (NUM2INT): accept an Integer or anything with #to_int (a Float is truncated), otherwise raise TypeError. Covers DateTime, which inherits `<<` and shares the month-shift helper. Matches the C extension (date 3.5.1); brings in master's test_next_month__ex / test_prev_month__ex. Full suite: 183 tests, 295285 assertions, green. --- lib/date/core.rb | 13 +++++++++++-- test/date/test_date_arith.rb | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 2 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 2bb67407..7e55cafb 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1111,12 +1111,21 @@ def >>(n) self.class.__send__(:new_from_jd, month_shifted_jd(n), @start) end + # Coerce a month count to an Integer the way the C extension does (NUM2INT): + # accept an Integer or anything with #to_int (e.g. Float, truncated), + # otherwise raise TypeError rather than silently treating it as zero. + private def month_offset_int(n) + return n if Integer === n + return n.to_int if n.respond_to?(:to_int) + raise TypeError, "no implicit conversion of #{n.nil? ? 'nil' : n.class} into Integer" + end + # Julian Day number of the date +n+ months from self, clamping the day to the # last day of the target month (using the calendar that applies under the # cutover). Shared with DateTime#>> so the time of day can be preserved. private def month_shifted_jd(n) internal_civil - m2 = @month + n.to_i + m2 = @month + month_offset_int(n) y2 = @year + (m2 - 1).div(12) m2 = (m2 - 1) % 12 + 1 klass = self.class @@ -1160,7 +1169,7 @@ def >>(n) # d2 = d1 << -1 # => # # def <<(n) - self >> -n + self >> -month_offset_int(n) end # call-seq: diff --git a/test/date/test_date_arith.rb b/test/date/test_date_arith.rb index 705abba5..ddb96ae3 100644 --- a/test/date/test_date_arith.rb +++ b/test/date/test_date_arith.rb @@ -7,6 +7,20 @@ class Rat < Numeric def to_r; self; end end + def test_next_month__ex + e = TypeError + assert_raise(e) { Date.new(2000, 1, 31) >> nil } + assert_raise(e) { Date.new(2000, 1, 31) >> '1' } + assert_raise(e) { DateTime.new(2000, 1, 31) >> nil } + end + + def test_prev_month__ex + e = TypeError + assert_raise(e) { Date.new(2000, 1, 31) << nil } + assert_raise(e) { Date.new(2000, 1, 31) << '1' } + assert_raise(e) { DateTime.new(2000, 1, 31) << nil } + end + def test_step_upto_downto_additional_paths # step with a negative integer step (Date fast loop). r = []; Date.new(2001, 2, 5).step(Date.new(2001, 2, 1), -2) { |d| r << d.mday } From 5f31be6b6df95243c8946c04be7d4daa293fe6e4 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 00:55:54 +0900 Subject: [PATCH 122/144] Drop decimal-hour zone offsets Per the maintainer's direction, the pure-Ruby library drops support for all features the C extension only deprecates (a major version bump accompanies the switch). Decimal-hour zone offsets ("+3.5", "-5,5", "GMT-3.5", "+00.5", ...) are one of those: the C extension still honours them (deprecated), the pure-Ruby library no longer does. Implementation: remove the decimal-hour branch in sp_zone_to_diff, the single place every offset string (_parse, _strptime/%Z, DateTime.new string offset) resolves through. Such an offset is now unrecognised, so the zone string is kept but the offset is nil (0 for DateTime.new's `|| 0`). Tests: this intentionally diverges from the C extension (date 3.5.1, which still parses these), so the existing rows in test__parse and test__strptime__3 that asserted decimal-hour offsets are updated to expect a nil offset (zone string unchanged). This is a sanctioned change to the existing tests, approved given the maintainer's drop-deprecated directive. Full suite: 183 tests, 295269 assertions, green. --- lib/date/strptime.rb | 20 -------------------- test/date/test_date_parse.rb | 12 ++++++------ test/date/test_date_strptime.rb | 6 +++--- 3 files changed, 9 insertions(+), 29 deletions(-) diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index 85ea79ce..4942bd5a 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -607,26 +607,6 @@ def sp_zone_to_diff(zone_str) sc = m[3] ? m[3].to_i : 0 return nil if h > 23 || mn > 59 || sc > 59 sign * (h * 3600 + mn * 60 + sc) - elsif (m = t.match(/\A(\d+)[,.](\d*)/)) - h = m[1].to_i - return nil if h > 23 - frac_s = m[2] - n = [frac_s.length, 7].min - digits = frac_s[0, n].to_i - digits += 1 if frac_s.length > n && frac_s[n].to_i >= 5 - sec = digits * 36 - os = if n == 0 - h * 3600 - elsif n == 1 - sec * 10 + h * 3600 - elsif n == 2 - sec + h * 3600 - else - denom = 10**(n - 2) - r = Rational(sec, denom) + h * 3600 - r.denominator == 1 ? r.numerator : r - end - sign == -1 ? -os : os elsif t =~ /\A(\d+)\z/ digits = $1 dlen = digits.length diff --git a/test/date/test_date_parse.rb b/test/date/test_date_parse.rb index d761b000..61c6f031 100644 --- a/test/date/test_date_parse.rb +++ b/test/date/test_date_parse.rb @@ -152,8 +152,8 @@ def test__parse [['19990523235521.123[+9]',false],[1999,5,23,23,55,21,'+9',+(9*3600),nil], __LINE__], [['19990523235521.123[9]',false],[1999,5,23,23,55,21,'9',+(9*3600),nil], __LINE__], [['19990523235521.123[9 ]',false],[1999,5,23,23,55,21,'9 ',+(9*3600),nil], __LINE__], - [['19990523235521.123[-9.50]',false],[1999,5,23,23,55,21,'-9.50',-(9*3600+30*60),nil], __LINE__], - [['19990523235521.123[+9.50]',false],[1999,5,23,23,55,21,'+9.50',+(9*3600+30*60),nil], __LINE__], + [['19990523235521.123[-9.50]',false],[1999,5,23,23,55,21,'-9.50',nil,nil], __LINE__], + [['19990523235521.123[+9.50]',false],[1999,5,23,23,55,21,'+9.50',nil,nil], __LINE__], [['19990523235521.123[-5:EST]',false],[1999,5,23,23,55,21,'EST',-5*3600,nil], __LINE__], [['19990523235521.123[+9:JST]',false],[1999,5,23,23,55,21,'JST',9*3600,nil], __LINE__], [['19990523235521.123[+12:XXX YYY ZZZ]',false],[1999,5,23,23,55,21,'XXX YYY ZZZ',12*3600,nil], __LINE__], @@ -184,10 +184,10 @@ def test__parse [['2000-01-31 13:20:00-5',false],[2000,1,31,13,20,0,'-5',-5*3600,nil], __LINE__], # [-+]\d+.\d+ - [['2000-01-31 13:20:00-5.5',false],[2000,1,31,13,20,0,'-5.5',-5*3600-30*60,nil], __LINE__], - [['2000-01-31 13:20:00-5,5',false],[2000,1,31,13,20,0,'-5,5',-5*3600-30*60,nil], __LINE__], - [['2000-01-31 13:20:00+3.5',false],[2000,1,31,13,20,0,'+3.5',3*3600+30*60,nil], __LINE__], - [['2000-01-31 13:20:00+3,5',false],[2000,1,31,13,20,0,'+3,5',3*3600+30*60,nil], __LINE__], + [['2000-01-31 13:20:00-5.5',false],[2000,1,31,13,20,0,'-5.5',nil,nil], __LINE__], + [['2000-01-31 13:20:00-5,5',false],[2000,1,31,13,20,0,'-5,5',nil,nil], __LINE__], + [['2000-01-31 13:20:00+3.5',false],[2000,1,31,13,20,0,'+3.5',nil,nil], __LINE__], + [['2000-01-31 13:20:00+3,5',false],[2000,1,31,13,20,0,'+3,5',nil,nil], __LINE__], # mil [['2000-01-31 13:20:00 Z',false],[2000,1,31,13,20,0,'Z',0*3600,nil], __LINE__], diff --git a/test/date/test_date_strptime.rb b/test/date/test_date_strptime.rb index 90c1d842..f548ad49 100644 --- a/test/date/test_date_strptime.rb +++ b/test/date/test_date_strptime.rb @@ -180,8 +180,8 @@ def test__strptime__3 [['Thu Jul 29 16:39:41 GMT-09 1999', '%a %b %d %H:%M:%S %Z %Y'], [1999,7,29,16,39,41,'GMT-09',-9*3600,4], __LINE__], [['Thu Jul 29 16:39:41 GMT-09:08 1999', '%a %b %d %H:%M:%S %Z %Y'], [1999,7,29,16,39,41,'GMT-09:08',-9*3600-8*60,4], __LINE__], [['Thu Jul 29 16:39:41 GMT-09:08:07 1999', '%a %b %d %H:%M:%S %Z %Y'], [1999,7,29,16,39,41,'GMT-09:08:07',-9*3600-8*60-7,4], __LINE__], - [['Thu Jul 29 16:39:41 GMT-3.5 1999', '%a %b %d %H:%M:%S %Z %Y'], [1999,7,29,16,39,41,'GMT-3.5',-3*3600-30*60,4], __LINE__], - [['Thu Jul 29 16:39:41 GMT-3,5 1999', '%a %b %d %H:%M:%S %Z %Y'], [1999,7,29,16,39,41,'GMT-3,5',-3*3600-30*60,4], __LINE__], + [['Thu Jul 29 16:39:41 GMT-3.5 1999', '%a %b %d %H:%M:%S %Z %Y'], [1999,7,29,16,39,41,'GMT-3.5',nil,4], __LINE__], + [['Thu Jul 29 16:39:41 GMT-3,5 1999', '%a %b %d %H:%M:%S %Z %Y'], [1999,7,29,16,39,41,'GMT-3,5',nil,4], __LINE__], [['Thu Jul 29 16:39:41 Mountain Daylight Time 1999', '%a %b %d %H:%M:%S %Z %Y'], [1999,7,29,16,39,41,'Mountain Daylight Time',-6*3600,4], __LINE__], [['Thu Jul 29 16:39:41 E. Australia Standard Time 1999', '%a %b %d %H:%M:%S %Z %Y'], [1999,7,29,16,39,41,'E. Australia Standard Time',10*3600,4], __LINE__], @@ -220,7 +220,7 @@ def test__strptime__3 [['E. Australia Standard Time', '%Z'], [nil,nil,nil,nil,nil,nil,'E. Australia Standard Time',10*3600,nil], __LINE__], # out of range - [['+0.9999999999999999999999', '%Z'], [nil,nil,nil,nil,nil,nil,'+0.9999999999999999999999',+1*3600,nil], __LINE__], + [['+0.9999999999999999999999', '%Z'], [nil,nil,nil,nil,nil,nil,'+0.9999999999999999999999',nil,nil], __LINE__], [['+9999999999999999999999.0', '%Z'], [nil,nil,nil,nil,nil,nil,'+9999999999999999999999.0',nil,nil], __LINE__], ].each do |x, y| h = Date._strptime(*x) From dad8d2183947f6e496caba8b072c315a8a97f93b Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 01:00:41 +0900 Subject: [PATCH 123/144] Precompute civil/day-fraction for clone(freeze: true) A Date built from a jd computes its civil fields lazily, caching them in instance variables on first access; likewise DateTime caches its day fraction. `#freeze` already precomputes these, but `clone(freeze: true)` freezes the copy without calling `#freeze`, so reading year/mon/mday (or day_fraction) on such a clone raised FrozenError. Override `initialize_clone` (which runs on the still-unfrozen copy) to precompute them: Date computes the civil fields, DateTime additionally the day fraction. Matches the C extension; extends test_freeze with the clone(freeze: true) cases. Full suite: 183 tests, 295273 assertions, green. --- lib/date/core.rb | 8 ++++++++ lib/date/datetime.rb | 8 ++++++++ test/date/test_date.rb | 7 +++++++ 3 files changed, 23 insertions(+) diff --git a/lib/date/core.rb b/lib/date/core.rb index 7e55cafb..9d2b2f3f 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1669,6 +1669,14 @@ def freeze super end + # clone(freeze: true) freezes the copy directly, without calling #freeze, so + # precompute the civil fields here (self is not frozen yet) to keep them + # readable on the frozen clone. + def initialize_clone(other, **) + super + internal_civil + end + # --------------------------------------------------------------------------- # Private helpers # --------------------------------------------------------------------------- diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 75594e9e..65b7fbb9 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -137,6 +137,14 @@ def freeze super end + # clone(freeze: true) freezes the copy without calling #freeze, so precompute + # the day fraction (Date#initialize_clone handles the civil fields) before the + # copy is frozen. + def initialize_clone(other, **) + super + day_fraction + end + # call-seq: # day_fraction -> rational # diff --git a/test/date/test_date.rb b/test/date/test_date.rb index e002a5e6..d379bd6e 100644 --- a/test/date/test_date.rb +++ b/test/date/test_date.rb @@ -193,6 +193,13 @@ def test_freeze assert_equal(true, d.frozen?) assert_instance_of(Integer, d.yday) assert_instance_of(String, d.to_s) + + # clone(freeze: true) freezes without calling #freeze; civil fields must + # still be readable on the frozen copy. + d = Date.jd(2451944).clone(freeze: true) + assert_equal([2001, 2, 3], [d.year, d.mon, d.mday]) + dt = DateTime.new(2001, 2, 3, 4, 5, 6, '+07:00').clone(freeze: true) + assert_equal(Rational(817, 4800), dt.day_fraction) end def test_submillisecond_comparison From 2c933f99d96b242c9efb37ded5908b6ffca40f03 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 01:07:50 +0900 Subject: [PATCH 124/144] Compare, eql? and hash by the absolute instant Date#<=>, #eql? and #hash used the local jd / day fraction / start, so two DateTimes denoting the same moment with different offsets compared unequal and hashed differently, and a date's start leaked into its hash. Base all three on the absolute instant (ajd): same-instant values now compare equal, are eql?, and share a hash, across offsets and starts and across Date and DateTime (so Date and DateTime keys collide in a Hash), matching the C extension. #hash is now inherited from Date by DateTime. A fast path keeps plain Date-to-Date comparison on the integer jd (no Rational), so sorting stays close to before: op Ruby before Ruby after Date <=> Date 7083799 5985218 (0.85x) sort 1000 Dates 707 598 (0.85x) Matches the C extension; extends test_eql_p/test_hash. Full suite: 183 tests, 295277 assertions, green. --- lib/date/core.rb | 20 ++++++++++++++++---- lib/date/datetime.rb | 9 ++------- test/date/test_date.rb | 12 ++++++++++++ 3 files changed, 30 insertions(+), 11 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 9d2b2f3f..b04d764a 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -950,8 +950,15 @@ def saturday? def <=>(other) case other when Date - d = @jd <=> other.jd - d != 0 ? d : day_fraction <=> other.day_fraction + # Plain dates have no offset or day fraction, so their jd is the whole + # story (fast path). Otherwise compare the absolute instant, so two + # DateTimes that denote the same moment with different offsets compare + # equal, matching the C extension. + if instance_of?(Date) && other.instance_of?(Date) + @jd <=> other.jd + else + ajd <=> other.ajd + end when Numeric ajd <=> other else @@ -963,11 +970,16 @@ def <=>(other) # and #=== are defined explicitly. def eql?(other) - other.is_a?(Date) && @jd == other.jd && day_fraction == other.day_fraction + return false unless other.is_a?(Date) + if instance_of?(Date) && other.instance_of?(Date) + @jd == other.jd + else + ajd == other.ajd + end end def hash - [@jd, @start].hash + ajd.hash end # call-seq: diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 65b7fbb9..2397c821 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -466,13 +466,8 @@ def inspect "#" end - def hash - if @hour == 0 && @min == 0 && @sec == 0 - [@jd, @start].hash - else - [@jd, @hour, @min, @sec, @start].hash - end - end + # #hash is inherited from Date (ajd.hash), so DateTimes that denote the same + # instant hash equal regardless of offset, matching #eql?. # --------------------------------------------------------------------------- # Serialization override diff --git a/test/date/test_date.rb b/test/date/test_date.rb index d379bd6e..a53ba5a7 100644 --- a/test/date/test_date.rb +++ b/test/date/test_date.rb @@ -159,6 +159,13 @@ def test_eql_p assert_equal(d, dt) assert_equal(d2, dt2) + + # Same instant, different offset: equal, eql?, and same hash. + dt = DateTime.new(2001,2,3,9,0,0,'+09:00') + dt2 = DateTime.new(2001,2,3,0,0,0,'+00:00') + assert_equal(dt, dt2) + assert_equal(true, dt.eql?(dt2)) + assert_equal(dt.hash, dt2.hash) end def test_hash @@ -185,6 +192,11 @@ def test_hash assert_equal(9, h[DateTime.new(1999,5,25)]) assert_instance_of(String, Date.new(1999,5,25).hash.to_s) + + # The start date does not affect the hash (same instant collides). + h = {} + h[Date.new(2001,2,3)] = 0 + assert_equal(0, h[Date.new(2001,2,3,Date::GREGORIAN)]) end def test_freeze From 75ff40f006e0189111b8ae8993e99597af2ed1fd Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 01:21:02 +0900 Subject: [PATCH 125/144] Account for offsets in Date#- (and cover <=>/step NaN cases) Date#- compared the local jd and day fraction, so subtracting a DateTime with an offset ignored that offset (e.g. Date.new(2001,2,3) - DateTime.new(2001,2,3,0,0,0,'-11:00') gave 0 instead of -11/24). Use the absolute instants (ajd) when either side is not a plain Date; a plain Date-to-Date subtraction keeps the fast integer jd delta. Also adopt master's tests for behaviour the pure-Ruby library already matches: Date#<=> / #== with NaN (nil / false) and upto/downto/step with an incomparable limit (ArgumentError). Verified against the C extension (date 3.5.1; for NaN/incomparable-limit the newer master semantics, which this library already had). Full suite: 186 tests, 295292 assertions, green. --- lib/date/core.rb | 9 ++++++++- test/date/test_date_arith.rb | 23 +++++++++++++++++++++++ 2 files changed, 31 insertions(+), 1 deletion(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index b04d764a..3dd25839 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1080,7 +1080,14 @@ def +(other) def -(other) case other when Date - Rational(@jd - other.jd) + day_fraction - other.day_fraction + # Difference as a day count. Plain dates reduce to an integer jd delta + # (fast path); otherwise use the absolute instants so an offset on either + # side is accounted for, matching the C extension. + if instance_of?(Date) && other.instance_of?(Date) + Rational(@jd - other.jd) + else + ajd - other.ajd + end when Integer self.class.__send__(:new_from_jd, @jd - other, @start) when Numeric diff --git a/test/date/test_date_arith.rb b/test/date/test_date_arith.rb index ddb96ae3..48e00335 100644 --- a/test/date/test_date_arith.rb +++ b/test/date/test_date_arith.rb @@ -7,6 +7,29 @@ class Rat < Numeric def to_r; self; end end + def test__compare_nan + [Date.new(2000, 1, 1), DateTime.new(2000, 1, 1, 12)].each do |d| + assert_nil(d <=> Float::NAN) + assert_equal(false, d == Float::NAN) + end + end + + def test_step__incomparable_limit + d = Date.new(2000, 1, 1) + [Float::NAN, Object.new].each do |limit| + no = proc { flunk("yielded for #{limit.inspect}") } + assert_raise(ArgumentError) { d.upto(limit, &no) } + assert_raise(ArgumentError) { d.downto(limit, &no) } + assert_raise(ArgumentError) { d.step(limit, 1, &no) } + assert_raise(ArgumentError) { d.step(limit, -1, &no) } + end + end + + def test__minus_datetime_offset + # Date - DateTime accounts for the DateTime's offset (absolute instants). + assert_equal(-11.to_r / 24, Date.new(2001, 2, 3) - DateTime.new(2001, 2, 3, 0, 0, 0, '-11:00')) + end + def test_next_month__ex e = TypeError assert_raise(e) { Date.new(2000, 1, 31) >> nil } From 915c1bcccc4f58ebeec899e432d8bb601aa747c9 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 09:31:06 +0900 Subject: [PATCH 126/144] Validate the start argument and ignore invalid values Match the C extension: a start (calendar-reform cutover) value is valid only when it is an infinity or a finite Julian day number in 2298874..2426355 (ns 1582-01-01 .. os 1930-12-31). NaN and any finite value outside that range are ignored, falling back to ITALY with a verbose-only warning ("invalid start is ignored"), and the calendar math uses the corrected value so an out-of-range start no longer yields a wrong jd (e.g. Date.civil(2001,2,3, 3000000) now returns the Gregorian jd 2451944 instead of the Julian 2451957). Validation runs once at each public constructor that accepts start (Date.jd/civil/ordinal/commercial/today, Date#new_start, the parse/ strptime builders, and the DateTime equivalents), so internal object builders on the arithmetic hot path are untouched. The default ITALY skips the check entirely, keeping the common path dispatch-free. Adopts the upstream test_invalid_start and adds boundary/edge coverage (the 2298874/2426355 limits, infinities, NaN) plus a DateTime case. Benchmarks (i/s; C ext = Ruby 4.0.1 system build): method C ext Ruby ratio Date.civil 4,648,499 1,702,000 0.37x Date.jd 4,962,001 3,147,000 0.63x Date.ordinal 3,023,007 1,262,000 0.42x Date.commercial 2,478,941 963,000 0.39x The equal?(ITALY) guard keeps the regression versus the previous pure Ruby code to about 4-6% on these constructors. --- lib/date/constants.rb | 9 +++++ lib/date/core.rb | 33 ++++++++++++++++-- lib/date/datetime.rb | 7 ++++ lib/date/parse.rb | 1 + lib/date/strptime.rb | 1 + test/date/test_date_new.rb | 71 ++++++++++++++++++++++++++++++++++++++ 6 files changed, 120 insertions(+), 2 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index fd76beef..8e76f9a9 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -31,6 +31,15 @@ class Date # proleptic Gregorian calendar. GREGORIAN = -Float::INFINITY + # Valid range for a finite start (calendar-reform cutover) value, matching the + # C extension: the Julian day numbers of the earliest and latest supported + # reform dates (ns 1582-01-01 .. os 1930-12-31), inclusive. A finite start + # outside this range (or NaN) is ignored and falls back to ITALY; infinities + # are always valid. + VALID_START_MIN = 2298874 # ns 1582-01-01 + VALID_START_MAX = 2426355 # os 1930-12-31 + private_constant :VALID_START_MIN, :VALID_START_MAX + # Case-insensitive abbreviated name lookup tables for O(1) name matching. # Key = downcased 3-letter abbreviation, Value = [index, full_name_length]. # The length lets callers verify an optional full-name tail (e.g. the diff --git a/lib/date/core.rb b/lib/date/core.rb index 3dd25839..90920f4a 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -13,6 +13,7 @@ class Date class << self # Same as Date.new. def civil(year = -4712, month = 1, day = 1, start = ITALY) + start = validate_start(start) unless start.equal?(ITALY) if Integer === year && Integer === month && Integer === day && month >= 1 && month <= 12 && day >= 1 && day <= 28 # Days 1..28 exist in every month of both the Julian and Gregorian @@ -109,6 +110,7 @@ def valid_civil?(year, month, day, start = ITALY) # Related: Date.new. def jd(jd = 0, start = ITALY) jd = convert_numeric_to_int(jd, "jd") + start = validate_start(start) unless start.equal?(ITALY) obj = allocate obj.__send__(:initialize, jd, start) obj @@ -189,6 +191,7 @@ def julian_leap?(year) # # Related: Date.jd, Date.new. def ordinal(year = -4712, yday = 1, start = ITALY) + start = validate_start(start) unless start.equal?(ITALY) if Integer === year && Integer === yday && yday >= 1 && yday <= 365 jd1 = civil_to_jd(year, 1, 1, start) jd = jd1 + yday - 1 @@ -265,6 +268,7 @@ def valid_ordinal?(year, day, start = ITALY) # # Related: Date.jd, Date.new, Date.ordinal. def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = ITALY) + start = validate_start(start) unless start.equal?(ITALY) if Integer === cwyear && Integer === cweek && Integer === cwday && cweek >= 1 && cweek <= 52 && cwday >= 1 && cwday <= 7 # ISO 8601: every normal year has at least 52 weeks, but the @@ -310,6 +314,7 @@ def valid_commercial?(year, week, day, start = ITALY) # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # def today(start = ITALY) + start = validate_start(start) unless start.equal?(ITALY) t = Time.now jd = civil_to_jd(t.year, t.mon, t.mday, start) new_from_jd(jd, start) @@ -340,6 +345,26 @@ def convert_numeric_to_int(obj, field) r.numerator end + # Validate a start (calendar-reform cutover) value the way the C extension + # does, returning it as a Float for internal use. Infinities are always + # valid; NaN and any finite value outside VALID_START_MIN..VALID_START_MAX + # are ignored, falling back to ITALY with a (verbose-only) warning. Every + # public constructor that accepts a +start+ runs its argument through this + # before using it, so the calendar math and the stored @start agree. + def validate_start(sg) + f = sg.to_f + # Fast path: a finite value inside the supported range (the common case, + # including the ITALY/ENGLAND defaults). Ordered first so the hot path + # avoids the #infinite?/#nan? method calls below. + return f if f >= VALID_START_MIN && f <= VALID_START_MAX + # Outside the finite range: infinities (JULIAN/GREGORIAN) are valid; + # anything else -- an out-of-range finite value, or NaN (for which both + # comparisons above were false) -- is ignored and falls back to ITALY. + return f if f.infinite? + warn("invalid start is ignored", uplevel: 1) if $VERBOSE + ITALY.to_f + end + def civil_fallback(year, month, day, start) day = convert_numeric_to_int(day, "day") month = convert_numeric_to_int(month, "month") @@ -817,7 +842,9 @@ def new_start(start = ITALY) obj = self.class.allocate obj.instance_variable_set(:@jd, @jd) # Store the cutover as a Float so #start/#hash/marshal stay consistent - # (see #initialize). + # (see #initialize). An invalid start is ignored (see Date.validate_start); + # the default ITALY needs no validation and skips the dispatch. + start = self.class.__send__(:validate_start, start) unless start.equal?(ITALY) obj.instance_variable_set(:@start, start.to_f) obj end @@ -1713,7 +1740,9 @@ def initialize(jd, sg, year = nil, month = nil, day = nil) @jd = jd # Store the cutover as a Float. Keeps #start, #hash and marshal output # consistent regardless of whether the caller passed an Integer (e.g. ITALY) - # or a Float sentinel. + # or a Float sentinel. The public constructors have already validated and + # normalized +sg+ (see Date.validate_start); internal callers pass an + # already-valid @start, so no re-validation happens on this hot path. @start = sg.to_f # Cache the civil fields when the caller already knows them (Date.new via # the fast path passes them), so #year/#month/#day need not recompute them. diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 2397c821..d2ff223a 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -33,6 +33,7 @@ def initialize(year = -4712, month = 1, day = 1, hour = UNSET, minute = UNSET, s month = Integer(month) raise TypeError, "invalid year (not numeric)" unless year.is_a?(Numeric) year = Integer(year) + start = self.class.__send__(:validate_start, start) unless start.equal?(ITALY) # A fractional day/hour/minute is only allowed as the last argument given; # if a smaller unit was also supplied, the C extension rejects the fraction. @@ -265,6 +266,7 @@ def >>(n) # # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. def new_start(start = Date::ITALY) + start = self.class.__send__(:validate_start, start) unless start.equal?(Date::ITALY) self.class.__send__(:_new_dt_from_jd_time, @jd, @hour, @min, @sec, @sec_fraction, @of, start) end @@ -626,6 +628,7 @@ def jd(jd = 0, hour = UNSET, minute = UNSET, second = UNSET, offset = 0, start = of_sec = _parse_offset(offset) _check_hms_types(hour, minute, second) raise TypeError, "invalid jd (not numeric)" unless jd.is_a?(Numeric) + start = validate_start(start) unless start.equal?(Date::ITALY) jd_r = jd.to_r jd_i = jd_r.floor @@ -654,6 +657,7 @@ def ordinal(year = -4712, yday = 1, hour = UNSET, minute = UNSET, second = UNSET _check_hms_types(hour, minute, second) raise TypeError, "invalid yday (not numeric)" unless yday.is_a?(Numeric) raise TypeError, "invalid year (not numeric)" unless year.is_a?(Numeric) + start = validate_start(start) unless start.equal?(Date::ITALY) yday_r = yday.to_r yday_i = yday_r.floor @@ -685,6 +689,7 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, hour = UNSET, minute = UNSE raise TypeError, "invalid cwday (not numeric)" unless cwday.is_a?(Numeric) raise TypeError, "invalid cweek (not numeric)" unless cweek.is_a?(Numeric) raise TypeError, "invalid year (not numeric)" unless cwyear.is_a?(Numeric) + start = validate_start(start) unless start.equal?(Date::ITALY) cwday_r = cwday.to_r cwday_i = cwday_r.floor @@ -702,6 +707,7 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, hour = UNSET, minute = UNSE # # DateTime.now #=> # def now(start = Date::ITALY) + start = validate_start(start) unless start.equal?(Date::ITALY) t = Time.now jd = civil_to_jd(t.year, t.mon, t.mday, start) sec_f = Rational(t.subsec) @@ -916,6 +922,7 @@ def jisx0301(string = '-4712-01-01T00:00:00+00:00', start = Date::ITALY, limit: # but additionally extracts time components (hour, min, sec, offset, sec_fraction). def _dt_new_by_frags(hash, sg) raise Date::Error, 'invalid date' if hash.nil? + sg = validate_start(sg) unless sg.equal?(Date::ITALY) hash = sp_rewrite_frags(hash) orig_sec = hash[:sec] hash = sp_complete_frags(DateTime, hash) diff --git a/lib/date/parse.rb b/lib/date/parse.rb index 44dd7526..9207420e 100644 --- a/lib/date/parse.rb +++ b/lib/date/parse.rb @@ -1461,6 +1461,7 @@ def s3e_full_year?(num_s) # the full _sp_complete_frags pipeline and directly validate civil date. def fast_new_date(hash, sg) raise Error, 'invalid date' if hash.nil? || hash.empty? + sg = validate_start(sg) unless sg.equal?(ITALY) y = hash[:year] m = hash[:mon] d = hash[:mday] diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index 4942bd5a..cca75191 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -65,6 +65,7 @@ def _strptime(string, format = '%F') # Related: Date._strptime (returns a hash). def strptime(string = '-4712-01-01', format = '%F', start = ITALY) str = to_string_value(string) + start = validate_start(start) unless start.equal?(ITALY) if format == '%F' || format == '%Y-%m-%d' result = internal_strptime_ymd_to_date(str, start) return result if result diff --git a/test/date/test_date_new.rb b/test/date/test_date_new.rb index 6fa8ff42..9421193a 100644 --- a/test/date/test_date_new.rb +++ b/test/date/test_date_new.rb @@ -254,6 +254,77 @@ def test_civil__reform assert_equal([1582, 10, 4], [dt.year, dt.mon, dt.mday]) end + def test_invalid_start + d = nil + assert_warning(/invalid start/) do + d = Date.jd(0, 0) + end + assert_equal([-4712, 1, 1, Date::ITALY], + [d.year, d.mon, d.mday, d.start]) + assert_warning(/invalid start/) do + d = Date.civil(2001,2,3, 3000000) + end + assert_equal([2451944, Date::ITALY], [d.jd, d.start]) + assert_warning(/invalid start/) do + d = Date.civil(2001,2,3).new_start(1) + end + assert_equal(Date::ITALY, d.start) + end + + def test_invalid_start_boundaries + # The valid range for a finite start matches the C extension: + # 2298874 (ns 1582-01-01) .. 2426355 (os 1930-12-31), inclusive. + # Infinities are valid; NaN and any finite value outside the range are + # ignored (warning + fallback to ITALY). + assert_warning('') do + assert_equal(2298874, Date.jd(0, 2298874).start) + assert_equal(2426355, Date.jd(0, 2426355).start) + assert_equal(Date::ENGLAND, Date.jd(0, Date::ENGLAND).start) + assert_equal(Float::INFINITY, Date.jd(0, Date::JULIAN).start) + assert_equal(-Float::INFINITY, Date.jd(0, Date::GREGORIAN).start) + end + assert_warning(/invalid start/) do + assert_equal(Date::ITALY, Date.jd(0, 2298873).start) + end + assert_warning(/invalid start/) do + assert_equal(Date::ITALY, Date.jd(0, 2426356).start) + end + assert_warning(/invalid start/) do + assert_equal(Date::ITALY, Date.jd(0, Float::NAN).start) + end + # new_start shares the same validation. + assert_warning('') do + assert_equal(Date::ENGLAND, Date.new(2001,2,3).new_start(Date::ENGLAND).start) + end + assert_warning(/invalid start/) do + assert_equal(Date::ITALY, Date.new(2001,2,3).new_start(0).start) + end + end + + def test_invalid_start_datetime + # DateTime shares Date's start validation across all of its constructors: + # an invalid start is ignored (warning + fallback to ITALY), and the + # calendar math uses the corrected start. + assert_warning(/invalid start/) do + d = DateTime.jd(0, 0, 0, 0, 0, 0) + assert_equal(Date::ITALY, d.start) + end + assert_warning(/invalid start/) do + # With the raw start the civil fast path would pick the Julian jd; the + # corrected ITALY start must yield the Gregorian jd 2451944. + d = DateTime.civil(2001, 2, 3, 0, 0, 0, 0, 3000000) + assert_equal([2451944, Date::ITALY], [d.jd, d.start]) + end + assert_warning(/invalid start/) do + d = DateTime.new(2001, 2, 3).new_start(1) + assert_equal(Date::ITALY, d.start) + end + assert_warning('') do + assert_equal(Date::ENGLAND, DateTime.jd(0, 0, 0, 0, 0, Date::ENGLAND).start) + assert_equal(Float::INFINITY, DateTime.jd(0, 0, 0, 0, 0, Date::JULIAN).start) + end + end + def test_commercial d = Date.commercial dt = DateTime.commercial From e0abdb3e6273c842f28ca7c0a95f8345108862fe Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 09:33:26 +0900 Subject: [PATCH 127/144] Range-check the offset in the old DateTime marshal format The three-element marshal format ([ajd, offset, start]) stores the offset as a day fraction. Match the C extension's old_to_new: round it to whole seconds (warning when a sub-second fraction is dropped) and ignore an offset beyond +/-1 day, falling back to a zero offset with an "invalid offset is ignored" warning. Both warnings are verbose-only, as in the C extension. Adopts the upstream test_marshal_load_old_format_offset. --- lib/date/datetime.rb | 11 ++++++++++- test/date/test_date_marshal.rb | 22 ++++++++++++++++++++++ 2 files changed, 32 insertions(+), 1 deletion(-) diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index d2ff223a..4f357872 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -496,7 +496,16 @@ def marshal_load(array) when 3 ajd, of_r, sg = array sg = normalize_start(sg) - of_sec = (of_r * 86400).to_i + # Old marshal format stores the offset as a day fraction. Match the C + # extension: round it to whole seconds (warning if a sub-second fraction + # is dropped) and ignore an offset beyond +/-1 day. + of_sec_r = of_r * 86400 + of_sec = of_sec_r.round + warn("fraction of offset is ignored", uplevel: 0) if $VERBOSE && of_sec != of_sec_r + if of_sec < -86400 || of_sec > 86400 + of_sec = 0 + warn("invalid offset is ignored", uplevel: 0) if $VERBOSE + end # Reconstruct local JD and time from AJD local_r = ajd + 0.5r + of_r jd = local_r.floor diff --git a/test/date/test_date_marshal.rb b/test/date/test_date_marshal.rb index c330a097..c3db5777 100644 --- a/test/date/test_date_marshal.rb +++ b/test/date/test_date_marshal.rb @@ -51,6 +51,28 @@ def test_marshal assert_raise(Date::Error) { Date.new + 1/2r } end + def test_marshal_load_old_format_offset + d = DateTime.allocate + d.marshal_load([Rational(0), Rational(1, 24), Date::ITALY]) + assert_equal(Rational(1, 24), d.offset) + + d = DateTime.allocate + d.marshal_load([Rational(0), 1, Date::ITALY]) + assert_equal(1, d.offset) + + d = DateTime.allocate + assert_warning(/invalid offset/) do + d.marshal_load([Rational(0), 5, Date::ITALY]) + end + assert_equal(0, d.offset) + + d = DateTime.allocate + assert_warning(/invalid offset/) do + d.marshal_load([Rational(0), -5, Date::ITALY]) + end + assert_equal(0, d.offset) + end + def test_memsize require 'objspace' t = DateTime.new(2018, 11, 13) From ca33626b4d8b8aca1b07dbce43fa62d572dec888 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 09:35:21 +0900 Subject: [PATCH 128/144] Account for the nth field when loading marshal data Marshal data written by the C extension stores the Julian day number as an (nth, jd) pair: jd is reduced into a single canonical period (CM_PERIOD) and nth counts the whole periods, so a date in a very large (or very negative) year has a non-zero nth. Date#marshal_load and DateTime#marshal_load ignored nth and used the in-period jd directly, decoding such dumps to the wrong day. Add the whole periods back (jd += nth * CM_PERIOD) in both loaders. Our own #marshal_dump always uses nth = 0 and stores the full jd, so round-trips are unaffected; this only fixes loading foreign C-extension dumps. Adopts the upstream test_marshal_nth, which loads a stored C-extension marshal string with nth = -1. --- lib/date/constants.rb | 10 ++++++++++ lib/date/core.rb | 5 ++++- lib/date/datetime.rb | 5 ++++- test/date/test_date_marshal.rb | 9 +++++++++ 4 files changed, 27 insertions(+), 2 deletions(-) diff --git a/lib/date/constants.rb b/lib/date/constants.rb index 8e76f9a9..837c7da0 100644 --- a/lib/date/constants.rb +++ b/lib/date/constants.rb @@ -40,6 +40,16 @@ class Date VALID_START_MAX = 2426355 # os 1930-12-31 private_constant :VALID_START_MIN, :VALID_START_MAX + # Canonical period used by the C extension to split a very large Julian day + # number into an (nth, jd) marshal pair: the largest multiple of the combined + # week/Julian/Gregorian cycle length (lcm(7, 1461, 146097) = 71149239) that + # fits in 28 bits -- i.e. (0xfffffff / 71149239) * 71149239. Needed to decode + # marshal data written by the C extension, whose jd field is within one + # period and whose nth field counts whole periods. Our own #marshal_dump uses + # nth = 0 and stores the full jd, so this only affects foreign dumps. + CM_PERIOD = 213447717 + private_constant :CM_PERIOD + # Case-insensitive abbreviated name lookup tables for O(1) name matching. # Key = downcased 3-letter abbreviation, Value = [index, full_name_length]. # The length lets callers verify an optional full-name tail (e.g. the diff --git a/lib/date/core.rb b/lib/date/core.rb index 90920f4a..9fd4003d 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1462,7 +1462,10 @@ def marshal_load(array) initialize((ajd + 0.5r).floor, sg) when 6 # Current format: [nth, jd, df, sf, of, sg]; a Date ignores df/sf. - _nth, jd, _df, _sf, _of, sg = array + # The C extension's jd is within one period; add back the whole periods + # counted by nth (our own dumps use nth = 0, so this is then a no-op). + nth, jd, _df, _sf, _of, sg = array + jd += nth * CM_PERIOD unless nth == 0 initialize(jd, normalize_start(sg)) else raise TypeError, "invalid marshal data" diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 4f357872..3018fcdd 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -517,8 +517,11 @@ def marshal_load(array) s_i, s_f = _split_second(s_r) _init_datetime(jd, h, m, s_i, s_f, of_sec, sg) when 6 - _nth, jd, df, sf, of, sg = array + nth, jd, df, sf, of, sg = array sg = normalize_start(sg) + # The C extension's jd is within one period; add back the whole periods + # counted by nth (our own dumps use nth = 0, so this is then a no-op). + jd += nth * CM_PERIOD unless nth == 0 # jd/df hold the UTC instant; shift by the offset to recover local time. jd_carry, local_df = (df + of).divmod(86400) jd += jd_carry diff --git a/test/date/test_date_marshal.rb b/test/date/test_date_marshal.rb index c3db5777..f425392c 100644 --- a/test/date/test_date_marshal.rb +++ b/test/date/test_date_marshal.rb @@ -51,6 +51,15 @@ def test_marshal assert_raise(Date::Error) { Date.new + 1/2r } end + def test_marshal_nth + [Date.new(-123456,7,8), Date.new(2**40,3,31)].each do |d| + assert_equal(d, Marshal.load(Marshal.dump(d))) + end + + s = "\x04\bU:\tDate[\vi\xFAi\x04\xF4)#\ni\x00i\x00i\x00f\f2299161".b + assert_equal(Date.new(-123456,7,8), Marshal.load(s)) + end + def test_marshal_load_old_format_offset d = DateTime.allocate d.marshal_load([Rational(0), Rational(1, 24), Date::ITALY]) From 4f3d99494e1ddc2641addb682da711e1300937af Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 09:40:56 +0900 Subject: [PATCH 129/144] Handle the calendar-reform gap in month shift and negative mday Two reform-gap cases diverged from the C extension: Date#>> / Date#<< clamped the shifted day with the plain days-in-month count, so a shift landing in the reform gap produced a non-existent date (1582-09-10 >> 1 gave 1582-10-20 instead of 1582-10-04). Replace the clamp with the C extension's d_lite_rshift loop: decrement the day until the date exists, which covers both a day past month-end and a day inside the gap. A negative mday was resolved as day + days_in_month + 1, which can fall in the gap and be rejected (Date.civil(1582,10,-18) raised instead of returning 1582-10-04). Resolve it in JD space instead -- (jd of the last day of the month) + mday + 1, converted back to civil (new jd_to_civil helper) -- so counting back from month-end skips the gap, matching c_valid_civil_p. Verified against the oracle across the Italian and English reforms. Adopts the upstream test_next_month reform case and restores the test_civil__reform negative-mday cases. Benchmarks (i/s; C ext = Ruby 4.0.1 system build; perf-neutral vs the previous pure Ruby, which was already ~0.78M): method C ext Ruby ratio Date#>> 3,119,218 811,000 0.26x --- lib/date/core.rb | 50 +++++++++++++++++++++++------------- test/date/test_date_arith.rb | 4 +++ test/date/test_date_new.rb | 8 ++++++ 3 files changed, 44 insertions(+), 18 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 9fd4003d..1ae266b2 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -452,6 +452,13 @@ def jd_to_gregorian(jd) [year, mon, day] end + # JD -> (year, month, day), choosing the calendar by the start value the + # same way civil_to_jd does (Gregorian when jd >= sg, Julian otherwise; the + # infinities select a single calendar). + def jd_to_civil(jd, sg) + jd >= sg ? jd_to_gregorian(jd) : jd_to_julian(jd) + end + # Julian JD -> (year, month, day) def jd_to_julian(jd) c = jd + 32082 @@ -507,10 +514,20 @@ def internal_valid_civil?(y, m, d, sg) m += 13 if m < 0 return nil if m < 1 || m > 12 + if d < 0 + # Resolve a negative mday against the JD of the last day of the month, + # then convert back to civil. Doing the arithmetic in JD space means a + # day counted back from month-end skips the calendar-reform gap exactly + # as the C extension does (e.g. 1582-10-(-18) -> 1582-10-04). + ny, nm = m == 12 ? [y + 1, 1] : [y, m + 1] + ldom_jd = civil_to_jd(ny, nm, 1, sg) - 1 + ry, rm, d = jd_to_civil(ldom_jd + d + 1, sg) + return nil if ry != y || rm != m + end + if sg == Float::INFINITY # Proleptic Julian calendar. dim = days_in_month_julian(y, m) - d += dim + 1 if d < 0 return nil if d < 1 || d > dim return julian_to_jd(y, m, d) end @@ -519,9 +536,8 @@ def internal_valid_civil?(y, m, d, sg) # a finite cutover. Days skipped by the reform have a Gregorian JD before # the cutover (gjd < sg) and are rejected here, then handled below. gdim = days_in_month_gregorian(y, m) - gd = d < 0 ? d + gdim + 1 : d - if gd >= 1 && gd <= gdim - gjd = gregorian_to_jd(y, m, gd) + if d >= 1 && d <= gdim + gjd = gregorian_to_jd(y, m, d) return gjd if gjd >= sg end return nil if sg == -Float::INFINITY @@ -529,9 +545,8 @@ def internal_valid_civil?(y, m, d, sg) # Pre-reform (Julian) side. This also accepts Julian-only leap days such as # 1500-02-29 under ITALY. A day skipped by the reform has jjd >= sg. jdim = days_in_month_julian(y, m) - jd2 = d < 0 ? d + jdim + 1 : d - return nil if jd2 < 1 || jd2 > jdim - jjd = julian_to_jd(y, m, jd2) + return nil if d < 1 || d > jdim + jjd = julian_to_jd(y, m, d) jjd < sg ? jjd : nil end @@ -1176,17 +1191,16 @@ def >>(n) m2 = (m2 - 1) % 12 + 1 klass = self.class sg = @start - julian = if sg == Float::INFINITY - true - elsif sg == -Float::INFINITY - false - else - klass.__send__(:gregorian_to_jd, y2, m2, 1) < sg - end - dim = julian ? klass.__send__(:days_in_month_julian, y2, m2) - : klass.__send__(:days_in_month_gregorian, y2, m2) - d2 = @day < dim ? @day : dim - klass.__send__(:civil_to_jd, y2, m2, d2, sg) + d2 = @day + # Decrement the day until the date exists. This handles both a day past the + # end of the target month (e.g. Jan 31 >> 1 -> Feb 28/29) and a day that + # falls in the calendar-reform gap (e.g. 1582-09-10 >> 1 -> 1582-10-04), + # matching the C extension's d_lite_rshift. + while (jd = klass.__send__(:internal_valid_civil?, y2, m2, d2, sg)).nil? + d2 -= 1 + raise Date::Error, "invalid date" if d2 < 1 + end + jd end # call-seq: diff --git a/test/date/test_date_arith.rb b/test/date/test_date_arith.rb index 48e00335..0b2a23c7 100644 --- a/test/date/test_date_arith.rb +++ b/test/date/test_date_arith.rb @@ -247,6 +247,10 @@ def test_next_month assert_equal([2001, 1, 31], [d.year, d.mon, d.mday]) d = Date.new(2000,1,31) >> 13 assert_equal([2001, 2, 28], [d.year, d.mon, d.mday]) + # A month shift that lands in the calendar-reform gap clamps to the last + # valid day before the gap (1582-10-10 does not exist; 10-04 does). + d = Date.new(1582,9,10) >> 1 + assert_equal([1582, 10, 4], [d.year, d.mon, d.mday]) end def test_next_month__2 diff --git a/test/date/test_date_new.rb b/test/date/test_date_new.rb index 9421193a..10706ea9 100644 --- a/test/date/test_date_new.rb +++ b/test/date/test_date_new.rb @@ -252,6 +252,14 @@ def test_civil__reform dt -= 1 assert_equal([1582, 10, 4], [d.year, d.mon, d.mday]) assert_equal([1582, 10, 4], [dt.year, dt.mon, dt.mday]) + + d = Date.civil(1582,10,-17) + assert_equal([1582, 10, 15], [d.year, d.mon, d.mday]) + d = Date.civil(1582,10,-18) + assert_equal([1582, 10, 4], [d.year, d.mon, d.mday]) + d = DateTime.civil(1582,10,-21) + assert_equal([1582, 10, 1], [d.year, d.mon, d.mday]) + assert_equal(false, Date.valid_civil?(1582,10,-22)) end def test_invalid_start From a921c7a46f7cbc4f26216a1ce380adee4e71ba34 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 09:43:07 +0900 Subject: [PATCH 130/144] Normalize Date#<=> against a Numeric to its sign When the right operand is a Numeric (not a Date), Date#<=> compared the absolute instant with ajd <=> other and returned that value verbatim. A custom Numeric reached through coerce may return any integer from its own #<=> (e.g. 5), so the result could be a non-sign value. Match the C extension's cmp_gen: reduce the comparison to its sign (-1/0/1), keeping nil as nil (so a NaN still compares as nil). The common Date <=> Date path is unchanged. Extends test__compare with the coerce case and the same-instant, different-offset DateTime cases from upstream. --- lib/date/core.rb | 6 +++++- test/date/test_date_arith.rb | 6 ++++++ 2 files changed, 11 insertions(+), 1 deletion(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 1ae266b2..bfa595e9 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1002,7 +1002,11 @@ def <=>(other) ajd <=> other.ajd end when Numeric - ajd <=> other + # Compare by the absolute instant, then normalize to -1/0/1: a custom + # Numeric's #<=> (reached via coerce) may return any integer, and the C + # extension reduces it to its sign (nil stays nil, e.g. for NaN). + c = ajd <=> other + c && (c <=> 0) else nil end diff --git a/test/date/test_date_arith.rb b/test/date/test_date_arith.rb index 0b2a23c7..65fae399 100644 --- a/test/date/test_date_arith.rb +++ b/test/date/test_date_arith.rb @@ -150,6 +150,12 @@ def test__compare Date.new(2001,1,17, Date::GREGORIAN))) assert_equal(0, (DateTime.new(2001,1,4,0,0,0,0,Date::JULIAN) <=> DateTime.new(2001,1,17,0,0,0,0,Date::GREGORIAN))) + assert_equal(0, (DateTime.new(2001,2,3,9,0,0,'+09:00') <=> + DateTime.new(2001,2,3,0,0,0,'+00:00'))) + assert_equal(-1, (DateTime.new(2001,2,3,0,0,0,'+09:00') <=> + DateTime.new(2001,2,3,0,0,0,'+00:00'))) + n = Class.new(Numeric) {def coerce(x) [self, x] end; def <=>(x) 5 end}.new + assert_equal(1, (Date.new(2000,1,1) <=> n)) end def test_prev From d8c3240ff46a9b2dedd631507ac63066a98a15a6 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 09:49:48 +0900 Subject: [PATCH 131/144] Cover Date minus an offset DateTime Add the upstream test__minus case for subtracting an offset-bearing DateTime from a Date; the result already accounts for the offset since Date#- compares by the absolute instant. --- test/date/test_date_arith.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/test/date/test_date_arith.rb b/test/date/test_date_arith.rb index 65fae399..9bf8006d 100644 --- a/test/date/test_date_arith.rb +++ b/test/date/test_date_arith.rb @@ -124,6 +124,9 @@ def test__minus d = DateTime.new(2000,3,1) - 1.to_r/2 assert_equal([2000, 2, 29, 12, 0, 0], [d.year, d.mon, d.mday, d.hour, d.min, d.sec]) + + d = Date.new(2001,2,3) - DateTime.new(2001,2,3,0,0,0,'-11:00') + assert_equal(-11.to_r/24, d) end def test__minus__ex From c243f46c4ef9c8d16b9c4e3cd6bf6ee008ab9970 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 09:49:48 +0900 Subject: [PATCH 132/144] Fix strptime fallback, weekday completion and week-number validity Three strptime parity gaps with the C extension: - The %F / %Y-%m-%d fast path rejected any input it did not match exactly, so trailing text that strptime should treat as ignorable leftover raised instead of parsing (e.g. strptime('2002-03-14 11:22:33', '%Y-%m-%d')). Fall through to the general pipeline when the fast path does not match, rather than raising. - Fragment completion took the civil pattern whenever a year was present, dropping a weekday given without a month/day. A :wday now also lets the week-number pattern win when it matches more fields, so "%Y %a" completes via wnum0 (e.g. '2001 Sat' -> 2001-01-06). - Week-number dates were built without checking they round-trip, so a week-0 weekday that falls into the previous year was accepted. Validate (year, weeknum, wday) against the computed JD as c_valid_weeknum_p does, so e.g. '2001 Sun' ('%Y %a') is correctly invalid. Restores the upstream test_strptime cases for these. --- lib/date/strptime.rb | 41 ++++++++++++++++++++++++++++----- test/date/test_date_strptime.rb | 6 +++++ 2 files changed, 41 insertions(+), 6 deletions(-) diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index cca75191..09e26183 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -66,15 +66,16 @@ def _strptime(string, format = '%F') def strptime(string = '-4712-01-01', format = '%F', start = ITALY) str = to_string_value(string) start = validate_start(start) unless start.equal?(ITALY) + # Fast paths for the two most common formats. They match only when the + # whole string is exactly that shape; anything else (e.g. trailing text + # that strptime treats as ignorable leftover) falls through to the general + # pipeline below rather than being rejected. if format == '%F' || format == '%Y-%m-%d' result = internal_strptime_ymd_to_date(str, start) return result if result - raise Error, 'invalid date' - end - if format == '%a %b %d %Y' + elsif format == '%a %b %d %Y' result = internal_strptime_abdy_to_date(str, start) return result if result - raise Error, 'invalid date' end hash = _strptime(string, format) raise Error, 'invalid date' if hash.nil? @@ -677,6 +678,14 @@ def sp_complete_frags(klass, hash) wn1_n = sp_count_keys(hash, [:year, :wnum1, :wday, :hour, :min, :sec]) skip_civil = true if wn1_n > best_n end + if hash.key?(:wday) + # A :wday with no explicit week number still matches the wnum0/wnum1 + # patterns (which include :wday). If that beats the civil match, let + # the general table scan pick the week-number pattern instead of + # defaulting to civil and dropping the weekday (e.g. "%Y %a"). + wnw_n = sp_count_keys(hash, [:year, :wnum0, :wday, :hour, :min, :sec]) + skip_civil = true if wnw_n > best_n + end unless skip_civil k = :civil a = [:year, :mon, :mday, :hour, :min, :sec] @@ -766,6 +775,26 @@ def sp_weeknum_to_jd(y, w, d, f, sg) (jd_jan7 - (jd_jan7 - f + 1) % 7 - 7) + 7 * w + d end + # Inverse of sp_weeknum_to_jd: JD -> [year, weeknum, wday] for style f. + # Ported from the C c_jd_to_weeknum(). + def sp_jd_to_weeknum(jd, f, sg) + y, = jd_to_civil(jd, sg) + rjd = civil_to_jd(y, 1, 1, sg) + 6 + j = jd - (rjd - ((rjd - f) + 1) % 7) + 7 + [y, j.div(7), j % 7] + end + + # Validate a (year, weeknum, wday) triple the way c_valid_weeknum_p does: + # compute the JD, convert it back, and require the fields to round-trip + # (rejecting e.g. a week-0 day that falls into the previous year). Returns + # the JD or nil. + def sp_valid_weeknum?(y, w, d, f, sg) + jd = sp_weeknum_to_jd(y, w, d, f, sg) + ry, rw, rd = sp_jd_to_weeknum(jd, f, sg) + return nil if y != ry || w != rw || d != rd + jd + end + # Find the Julian Day number from the fragment hash. # Tries jd, ordinal, civil, commercial, wnum0, wnum1 in order. # Returns jd integer or nil. @@ -800,7 +829,7 @@ def sp_valid_date_frags_p(hash, sg) wday = 0 if !wday.nil? && wday == 7 end if wday && (week = hash[:wnum0]) && (year = hash[:year]) - jd = sp_weeknum_to_jd(year, week, wday, 0, sg) + jd = sp_valid_weeknum?(year, week, wday, 0, sg) return jd if jd end @@ -810,7 +839,7 @@ def sp_valid_date_frags_p(hash, sg) wday = hash[:cwday] if wday.nil? wday = (wday - 1) % 7 if wday if wday && (week = hash[:wnum1]) && (year = hash[:year]) - jd = sp_weeknum_to_jd(year, week, wday, 1, sg) + jd = sp_valid_weeknum?(year, week, wday, 1, sg) return jd if jd end diff --git a/test/date/test_date_strptime.rb b/test/date/test_date_strptime.rb index f548ad49..dbfcccc9 100644 --- a/test/date/test_date_strptime.rb +++ b/test/date/test_date_strptime.rb @@ -346,6 +346,8 @@ def test_strptime d = Date.new(2002,3,14) assert_equal(d, Date.strptime(d.to_s)) assert_equal(Date.new(2002,3,14), Date.strptime('2002-03-14')) + assert_equal(Date.new(2002,3,14), Date.strptime('2002-03-14 11:22:33', '%Y-%m-%d')) + assert_equal(Date.new(2002,3,14), Date.strptime('2002-03-14T11:22:33Z', '%F')) d = DateTime.new(2002,3,14,11,22,33, 0) assert_equal(d, DateTime.strptime(d.to_s)) @@ -359,6 +361,10 @@ def test_strptime DateTime.strptime('2002-03-14T11:22:33-09:00', '%FT%T%Z')) assert_equal(DateTime.new(2002,3,14,11,22,33, -9.to_r/24) + 123456789.to_r/1000000000/86400, DateTime.strptime('2002-03-14T11:22:33.123456789-09:00', '%FT%T.%N%Z')) + + d = DateTime.strptime('2001 Sat', '%Y %a') + assert_equal([2001, 1, 6, 0, 0, 0], + [d.year, d.mon, d.mday, d.hour, d.min, d.sec]) end def test_strptime__2 From 980798e1e9be2c9bf214cf2200b2dd4ff5528e9a Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 09:55:29 +0900 Subject: [PATCH 133/144] Match the C extension for cross-class initialize_copy Ruby's default initialize_copy rejects a different class, so DateTime#initialize_copy(Date) raised a TypeError. The C extension instead lets a DateTime absorb a plain Date as midnight UTC (keeping the Date's start), while a Date cannot take a DateTime's time-of-day and raises ArgumentError ("cannot load complex into simple"). Define initialize_copy on both classes to reproduce this: DateTime copies a Date via _init_datetime (reusing the existing object shape, so memsize is unchanged), a plain Date rejects a DateTime with ArgumentError, and same-class copies (dup/clone) and non-Date sources defer to the default. Restores the upstream cross-class test_memsize. --- lib/date/core.rb | 13 +++++++++++++ lib/date/datetime.rb | 14 ++++++++++++++ test/date/test_date_new.rb | 2 +- 3 files changed, 28 insertions(+), 1 deletion(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index bfa595e9..03317ed0 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1744,6 +1744,19 @@ def initialize_clone(other, **) internal_civil end + # :nodoc: + # + # A plain Date cannot absorb a DateTime's time-of-day, matching the C + # extension ("cannot load complex into simple"). Same-class copies (and a + # DateTime copying a Date, handled in DateTime#initialize_copy) go through + # the default copy. + def initialize_copy(other) + if other.is_a?(DateTime) && !is_a?(DateTime) + raise ArgumentError, "cannot load complex into simple" + end + super + end + # --------------------------------------------------------------------------- # Private helpers # --------------------------------------------------------------------------- diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 3018fcdd..17e01d12 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -146,6 +146,20 @@ def initialize_clone(other, **) day_fraction end + # :nodoc: + # + # A DateTime can absorb a plain Date, taking it as midnight UTC with the + # Date's start (matching the C extension). Any other source (another + # DateTime, or a non-Date) falls back to the inherited copy, which handles + # same-class copies and raises for incompatible types. + def initialize_copy(other) + if !other.is_a?(DateTime) && other.is_a?(Date) + _init_datetime(other.jd, 0, 0, 0, 0r, 0, other.start) + return self + end + super + end + # call-seq: # day_fraction -> rational # diff --git a/test/date/test_date_new.rb b/test/date/test_date_new.rb index 10706ea9..bbdbef2a 100644 --- a/test/date/test_date_new.rb +++ b/test/date/test_date_new.rb @@ -451,7 +451,7 @@ def test_memsize require 'objspace' t = DateTime.now size = ObjectSpace.memsize_of(t) - t.__send__(:initialize_copy, DateTime.now) + t.__send__(:initialize_copy, Date.today) assert_instance_of(DateTime, t) assert_equal(size, ObjectSpace.memsize_of(t), "not reallocated but memsize changed") end From f5173e69328dd4494851425065502871d4ca39e2 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 21:02:41 +0900 Subject: [PATCH 134/144] Find the month's last day by scanning for a negative mday A negative mday resolved the month end as "the next month's first day minus one". Under a custom cutover whose reform gap sits near the end of the month, the next month's first day can itself be a skipped date, so that jd was wrong: e.g. with a Gregorian start of 1900-02-05, Date.new(1900,1,-1) raised instead of returning 1900-01-23, and Date.new(1900,1,-14) returned the wrong day. Find the last existing day of the month the way the C extension's c_find_ldom does: scan down from 31 for the last valid day, then move (mday + 1) days earlier in jd space and convert back to civil. The positive-mday validation is factored into valid_civil_positive_jd and reused for the scan. Verified against the C extension (date 3.6.0) across ITALY/ENGLAND, the proleptic calendars, and custom cutovers. --- lib/date/core.rb | 34 +++++++++++++++++++++++----------- test/date/test_date_new.rb | 12 ++++++++++++ 2 files changed, 35 insertions(+), 11 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index d9a04882..64636b90 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -515,16 +515,31 @@ def internal_valid_civil?(y, m, d, sg) return nil if m < 1 || m > 12 if d < 0 - # Resolve a negative mday against the JD of the last day of the month, - # then convert back to civil. Doing the arithmetic in JD space means a - # day counted back from month-end skips the calendar-reform gap exactly - # as the C extension does (e.g. 1582-10-(-18) -> 1582-10-04). - ny, nm = m == 12 ? [y + 1, 1] : [y, m + 1] - ldom_jd = civil_to_jd(ny, nm, 1, sg) - 1 + # Count back from the last existing day of the month. Find that day the + # way the C extension's c_find_ldom does -- scan down from 31 for the + # last valid day -- then move (d + 1) days earlier in JD space and + # convert back to civil. This handles a calendar-reform gap near the end + # of the month under any cutover, including a custom one whose next + # month begins inside the gap (where "next month's 1st minus 1" fails). + ldom_jd = nil + day = 31 + while day >= 1 + ldom_jd = valid_civil_positive_jd(y, m, day, sg) + break if ldom_jd + day -= 1 + end + return nil unless ldom_jd ry, rm, d = jd_to_civil(ldom_jd + d + 1, sg) return nil if ry != y || rm != m end + valid_civil_positive_jd(y, m, d, sg) + end + + # Validate a positive mday (d >= 1) under the given start and return its JD, + # or nil. Days skipped by the reform are rejected (their Gregorian JD is + # before the cutover and their Julian JD is at/after it). + def valid_civil_positive_jd(y, m, d, sg) if sg == Float::INFINITY # Proleptic Julian calendar. dim = days_in_month_julian(y, m) @@ -532,9 +547,6 @@ def internal_valid_civil?(y, m, d, sg) return julian_to_jd(y, m, d) end - # Gregorian reckoning: valid for GREGORIAN and for the post-reform side of - # a finite cutover. Days skipped by the reform have a Gregorian JD before - # the cutover (gjd < sg) and are rejected here, then handled below. gdim = days_in_month_gregorian(y, m) if d >= 1 && d <= gdim gjd = gregorian_to_jd(y, m, d) @@ -542,8 +554,8 @@ def internal_valid_civil?(y, m, d, sg) end return nil if sg == -Float::INFINITY - # Pre-reform (Julian) side. This also accepts Julian-only leap days such as - # 1500-02-29 under ITALY. A day skipped by the reform has jjd >= sg. + # Pre-reform (Julian) side; also accepts Julian-only leap days such as + # 1500-02-29 under ITALY. jdim = days_in_month_julian(y, m) return nil if d < 1 || d > jdim jjd = julian_to_jd(y, m, d) diff --git a/test/date/test_date_new.rb b/test/date/test_date_new.rb index bbdbef2a..c230ea42 100644 --- a/test/date/test_date_new.rb +++ b/test/date/test_date_new.rb @@ -262,6 +262,18 @@ def test_civil__reform assert_equal(false, Date.valid_civil?(1582,10,-22)) end + def test_civil__reform_negative_mday_custom_cutover + # A custom Gregorian cutover whose reform gap falls near the end of the + # month: the last existing day of the month must be found by scanning down + # (as the C extension's c_find_ldom does), not by taking the next month's + # first day minus one. sg = 1900-02-05 (Gregorian) leaves 1900-01-23 as the + # last day of January 1900. + sg = Date.new(1900, 2, 5, Date::GREGORIAN).jd + assert_equal([1900, 1, 23], Date.new(1900, 1, -1, sg).then { |d| [d.year, d.mon, d.mday] }) + assert_equal([1900, 1, 10], Date.new(1900, 1, -14, sg).then { |d| [d.year, d.mon, d.mday] }) + assert_equal(true, Date.valid_civil?(1900, 1, -1, sg)) + end + def test_invalid_start d = nil assert_warning(/invalid start/) do From f6ff6e47f4f8064f718e816b0d156b4315b743b1 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 21:06:23 +0900 Subject: [PATCH 135/144] Reject a non-numeric start with a TypeError validate_start used sg.to_f, so a nil or String start was silently coerced (to 0.0) and then treated as an out-of-range value that fell back to ITALY. The C extension's NUM2DBL raises a TypeError for a non-numeric start; match that, with the same messages ("no implicit conversion of nil/String/Symbol into Float", "can't convert into Float"). Also route the validity predicates (valid_civil?, valid_ordinal?, valid_commercial?, valid_jd?) through validate_start so they raise the same TypeError for a non-numeric start instead of an ArgumentError or silently ignoring it, while an out-of-range numeric start still only warns and is clamped to ITALY. Verified against the C extension (date 3.6.0). --- lib/date/core.rb | 14 +++++++++++++- test/date/test_date_new.rb | 24 ++++++++++++++++++++++++ 2 files changed, 37 insertions(+), 1 deletion(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 64636b90..09e86ab4 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -80,6 +80,7 @@ def civil(year = -4712, month = 1, day = 1, start = ITALY) # Related: Date.jd, Date.new. def valid_civil?(year, month, day, start = ITALY) return false unless year.is_a?(Numeric) && month.is_a?(Numeric) && day.is_a?(Numeric) + start = validate_start(start) unless start.equal?(ITALY) !!internal_valid_civil?(year, month, day, start) end alias_method :valid_date?, :valid_civil? @@ -127,7 +128,8 @@ def jd(jd = 0, start = ITALY) # See argument {start}[rdoc-ref:language/calendars.rdoc@Argument+start]. # # Related: Date.jd. - def valid_jd?(jd, _start = ITALY) + def valid_jd?(jd, start = ITALY) + validate_start(start) unless start.equal?(ITALY) jd.is_a?(Numeric) end @@ -222,6 +224,7 @@ def ordinal(year = -4712, yday = 1, start = ITALY) # Related: Date.jd, Date.ordinal. def valid_ordinal?(year, day, start = ITALY) return false unless year.is_a?(Numeric) && day.is_a?(Numeric) + start = validate_start(start) unless start.equal?(ITALY) !!internal_valid_ordinal?(year, day, start) end @@ -301,6 +304,7 @@ def commercial(cwyear = -4712, cweek = 1, cwday = 1, start = ITALY) # Related: Date.jd, Date.commercial. def valid_commercial?(year, week, day, start = ITALY) return false unless year.is_a?(Numeric) && week.is_a?(Numeric) && day.is_a?(Numeric) + start = validate_start(start) unless start.equal?(ITALY) !!internal_valid_commercial?(year, week, day, start) end @@ -352,6 +356,14 @@ def convert_numeric_to_int(obj, field) # public constructor that accepts a +start+ runs its argument through this # before using it, so the calendar math and the stored @start agree. def validate_start(sg) + unless sg.is_a?(Numeric) + # Reject a non-numeric start with a TypeError, as the C extension's + # NUM2DBL does, rather than silently coercing it via #to_f. + if sg.nil? || sg.is_a?(String) || sg.is_a?(Symbol) + raise TypeError, "no implicit conversion of #{sg.nil? ? 'nil' : sg.class} into Float" + end + raise TypeError, "can't convert #{sg.class} into Float" + end f = sg.to_f # Fast path: a finite value inside the supported range (the common case, # including the ITALY/ENGLAND defaults). Ordered first so the hot path diff --git a/test/date/test_date_new.rb b/test/date/test_date_new.rb index c230ea42..147ad27a 100644 --- a/test/date/test_date_new.rb +++ b/test/date/test_date_new.rb @@ -321,6 +321,30 @@ def test_invalid_start_boundaries end end + def test_non_numeric_start_raises + # A non-numeric start is a TypeError, not a silent fallback (the C + # extension's NUM2DBL). This holds across the constructors, new_start, the + # parse/strptime entry points, and the validity predicates. + assert_raise(TypeError) { Date.new(2001, 1, 1, nil) } + assert_raise(TypeError) { Date.jd(1, "x") } + assert_raise(TypeError) { Date.ordinal(2001, 34, nil) } + assert_raise(TypeError) { Date.commercial(2001, 5, 3, nil) } + assert_raise(TypeError) { Date.new(2001, 1, 1).new_start(nil) } + assert_raise(TypeError) { Date.parse("2001-02-03", true, nil) } + assert_raise(TypeError) { Date.strptime("2001-02-03", "%F", nil) } + assert_raise(TypeError) { Date.valid_civil?(2001, 2, 3, nil) } + assert_raise(TypeError) { Date.valid_ordinal?(2001, 34, nil) } + assert_raise(TypeError) { Date.valid_commercial?(2001, 5, 3, nil) } + assert_raise(TypeError) { Date.valid_jd?(1, nil) } + assert_raise(TypeError) { DateTime.new(2001, 1, 1, 0, 0, 0, 0, nil) } + + # An out-of-range numeric start is still only a warning + fallback, so the + # predicate holds (clamped to ITALY). + assert_warning(/invalid start/) do + assert_equal(true, Date.valid_civil?(2001, 2, 3, 3000000)) + end + end + def test_invalid_start_datetime # DateTime shares Date's start validation across all of its constructors: # an invalid start is ignored (warning + fallback to ITALY), and the From 66ac8b9ec4a6523c9d559691cbaa93f1ae7f1daa Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 21:09:06 +0900 Subject: [PATCH 136/144] Floor a fractional month count in Date#>> and Date#<< month_offset_int used #to_int, which truncates toward zero, so a negative fractional month count was off by one (Date.new(2001,3,31) << 1.5 gave 2001-02-28 instead of 2001-01-31). The C extension floors the count. Floor a Numeric count instead, and let Date#<< negate the raw count before the shift so the floor applies to -n (<< 1.5 is -2 months). A non-numeric count now raises the same " can't be coerced into Integer" TypeError that Integer#+ coercion raises (previously "no implicit conversion"). Verified against the C extension (date 3.6.0) across integer and fractional counts for both operators. --- lib/date/core.rb | 17 +++++++++++------ test/date/test_date_arith.rb | 14 ++++++++++++++ 2 files changed, 25 insertions(+), 6 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 09e86ab4..5162ddf5 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1200,13 +1200,14 @@ def >>(n) self.class.__send__(:new_from_jd, month_shifted_jd(n), @start) end - # Coerce a month count to an Integer the way the C extension does (NUM2INT): - # accept an Integer or anything with #to_int (e.g. Float, truncated), - # otherwise raise TypeError rather than silently treating it as zero. + # Coerce a month count to an Integer the way the C extension does: a + # fractional count is floored (the shift is applied in month-index space, so + # e.g. -1.5 moves two months back, not one), and a non-numeric count raises + # the same TypeError that Integer#+ coercion would. private def month_offset_int(n) return n if Integer === n - return n.to_int if n.respond_to?(:to_int) - raise TypeError, "no implicit conversion of #{n.nil? ? 'nil' : n.class} into Integer" + return n.floor if Numeric === n + raise TypeError, "#{n.nil? ? 'nil' : n.class} can't be coerced into Integer" end # Julian Day number of the date +n+ months from self, clamping the day to the @@ -1257,7 +1258,11 @@ def >>(n) # d2 = d1 << -1 # => # # def <<(n) - self >> -month_offset_int(n) + # Negate the raw count before the shift so the floor is applied to -n + # (<< 1.5 is -2 months, not -1); a non-numeric count is left for #>> to + # reject with the right TypeError. + n = -n if Numeric === n + self >> n end # call-seq: diff --git a/test/date/test_date_arith.rb b/test/date/test_date_arith.rb index 9bf8006d..58caccbc 100644 --- a/test/date/test_date_arith.rb +++ b/test/date/test_date_arith.rb @@ -37,6 +37,20 @@ def test_next_month__ex assert_raise(e) { DateTime.new(2000, 1, 31) >> nil } end + def test_month_shift_fractional + # A fractional month count is floored (not truncated toward zero), matching + # the C extension. << n shifts by floor(-n), so << 1.5 is -2 months. + d = Date.new(2001, 6, 15) + assert_equal([2001, 7, 15], (d >> 1.5).then { |x| [x.year, x.mon, x.mday] }) + assert_equal([2001, 4, 15], (d >> -1.5).then { |x| [x.year, x.mon, x.mday] }) + assert_equal([2001, 3, 15], (d >> -2.9).then { |x| [x.year, x.mon, x.mday] }) + assert_equal([2001, 6, 15], (d >> 0.5).then { |x| [x.year, x.mon, x.mday] }) + assert_equal([2001, 7, 15], (d >> Rational(3, 2)).then { |x| [x.year, x.mon, x.mday] }) + e = Date.new(2001, 3, 31) + assert_equal([2001, 1, 31], (e << 1.5).then { |x| [x.year, x.mon, x.mday] }) + assert_equal([2001, 1, 31], (e << Rational(3, 2)).then { |x| [x.year, x.mon, x.mday] }) + end + def test_prev_month__ex e = TypeError assert_raise(e) { Date.new(2000, 1, 31) << nil } From 25578e0f030566fc65f4fc0048822525f92eed20 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 21:11:10 +0900 Subject: [PATCH 137/144] Hash the instant as an integer triple, not via ajd Date#hash became ajd.hash in the eql?/hash-by-instant change, which builds a Rational on every call and dropped Date#hash to about a third of its former speed (and well below the C extension). Hash the absolute instant the way the C extension's d_lite_hash does instead: the integer triple (jd, seconds-in-day, sub-second nanoseconds) in UTC. Date, having no time or offset, hashes (jd, 0, 0); DateTime converts its local time to UTC first, so same-instant/different-offset DateTimes -- and a Date and a DateTime at the same instant -- still hash equal (they are #eql?). No Rational is allocated. Benchmarks (i/s; C ext date 3.6.0, both with YJIT off): Date#hash before: 3,625,540 after: 10,115,000 --- lib/date/core.rb | 6 +++++- lib/date/datetime.rb | 14 ++++++++++++++ 2 files changed, 19 insertions(+), 1 deletion(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 5162ddf5..95cdf6e0 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1049,7 +1049,11 @@ def eql?(other) end def hash - ajd.hash + # Hash the absolute instant as the integer triple (jd, seconds-in-day, + # sub-second nanoseconds) in UTC, the way the C extension does, so values + # that are #eql? hash equal without building a Rational (as ajd.hash did). + # A plain Date has no time or offset, so the triple is simply (jd, 0, 0). + [@jd, 0, 0].hash end # call-seq: diff --git a/lib/date/datetime.rb b/lib/date/datetime.rb index 17e01d12..d82d211d 100644 --- a/lib/date/datetime.rb +++ b/lib/date/datetime.rb @@ -160,6 +160,20 @@ def initialize_copy(other) super end + # :nodoc: + # + # Hash the absolute instant as the integer triple (jd, seconds-in-day, + # sub-second nanoseconds) in UTC, matching the C extension. Two DateTimes + # that denote the same moment with different offsets -- and a Date and a + # DateTime at the same instant -- hash equal (as they are #eql?), without + # building a Rational. + def hash + secs = @hour * 3600 + @min * 60 + @sec - @of + carry, df = secs.divmod(86400) + sf = (@sec_fraction * 1_000_000_000).to_i + [@jd + carry, df, sf].hash + end + # call-seq: # day_fraction -> rational # From e2f98e61850e53bdb3c4ba88ff35e3621c7d5dd3 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 21:12:15 +0900 Subject: [PATCH 138/144] Round a fractional start to even in Date#inspect inspect_sg printed a fractional start with #to_i, which truncates toward zero (2299160.7 showed as 2299160j). The C extension formats it with "%.0f", which rounds to the nearest integer with ties to even. Use round(half: :even) so inspect matches (2299160.7 -> 2299161j, 2299161.5 -> 2299162j). Verified against the C extension (date 3.6.0). --- lib/date/core.rb | 4 +++- test/date/test_date.rb | 6 +++++- 2 files changed, 8 insertions(+), 2 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 95cdf6e0..ee1b4bfe 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1766,7 +1766,9 @@ def inspect elsif sg == -Float::INFINITY '-Inf' else - sg.to_i.to_s + # Round to the nearest integer, ties to even, matching the C extension's + # "%.0f" output (not a truncation). + sg.round(half: :even).to_s end end diff --git a/test/date/test_date.rb b/test/date/test_date.rb index a53ba5a7..3c21a880 100644 --- a/test/date/test_date.rb +++ b/test/date/test_date.rb @@ -11,9 +11,13 @@ def test_inspect_start_variants Date.new(2001, 2, 3, Date::JULIAN).inspect) assert_equal('#', Date.new(2001, 2, 3, Date::GREGORIAN).inspect) - # A fractional start prints as a whole jd, matching the C extension. + # A fractional start prints as a whole jd, rounded to even like the C + # extension's %.0f (not truncated). assert_equal('#', Date.new(2001, 2, 3, 2400000.5).inspect) + assert_match(/,2299161j\)>\z/, Date.new(2001, 2, 3, 2299160.7).inspect) + assert_match(/,2299162j\)>\z/, Date.new(2001, 2, 3, 2299161.5).inspect) + assert_match(/,2299160j\)>\z/, Date.new(2001, 2, 3, 2299160.5).inspect) end def test_spaceship_and_equal_with_incomparable From 73d4915d3ebccd09e0bae7523a2bd4d66c307a49 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 21:14:04 +0900 Subject: [PATCH 139/144] Reject a cwday with no week number in strptime Fragment completion let the civil pattern win for {year, cwday} (from e.g. "%Y %u"), defaulting the month/day and dropping the weekday, so Date.strptime('2001 5', '%Y %u') returned 2001-01-01 instead of raising. As with the earlier %a/%w fix, let a :cwday steer completion to the (year, wnum, cwday) patterns; with no week number those cannot form a date, so it is reported invalid, matching the C extension (date 3.6.0). A cwday with a week number (%W %u, %G %V %u) still resolves. --- lib/date/strptime.rb | 8 ++++++++ test/date/test_date_strptime.rb | 9 +++++++++ 2 files changed, 17 insertions(+) diff --git a/lib/date/strptime.rb b/lib/date/strptime.rb index 09e26183..697ecfb1 100644 --- a/lib/date/strptime.rb +++ b/lib/date/strptime.rb @@ -686,6 +686,14 @@ def sp_complete_frags(klass, hash) wnw_n = sp_count_keys(hash, [:year, :wnum0, :wday, :hour, :min, :sec]) skip_civil = true if wnw_n > best_n end + if hash.key?(:cwday) + # Likewise a :cwday (e.g. "%Y %u") matches the (year, wnum, cwday) + # patterns. Letting those win means a cwday with no week number is + # left unsatisfiable and reported as an invalid date, as in the C + # extension, rather than silently defaulting to civil. + cwd_n = sp_count_keys(hash, [:year, :wnum0, :cwday, :hour, :min, :sec]) + skip_civil = true if cwd_n > best_n + end unless skip_civil k = :civil a = [:year, :mon, :mday, :hour, :min, :sec] diff --git a/test/date/test_date_strptime.rb b/test/date/test_date_strptime.rb index dbfcccc9..e1bab1e8 100644 --- a/test/date/test_date_strptime.rb +++ b/test/date/test_date_strptime.rb @@ -97,6 +97,15 @@ def test__strptime_rejects_non_string assert_raise(TypeError) { Date._strptime(false, '%F') } end + def test__strptime_cwday_without_week + # A %u (ISO weekday) with no week number cannot form a date, so it is + # invalid -- like %a/%w, it must not silently default to civil (year only). + assert_raise(Date::Error) { Date.strptime('2001 5', '%Y %u') } + # With a week number it resolves normally. + assert_equal(Date.new(2001, 1, 26), Date.strptime('2001 04 5', '%Y %W %u')) + assert_equal(Date.new(2001, 1, 26), Date.strptime('2001 04 5', '%G %V %u')) + end + def test__strptime_abdy_fast_path # "%a %b %d %Y" has a dedicated fast path in _strptime/strptime. assert_equal({wday: 6, mon: 2, mday: 3, year: 2001}, From 0f1dd90a6c9d950e16d744a9d17e3f76efdcd6d8 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 21:14:59 +0900 Subject: [PATCH 140/144] Match the C extension's initialize_copy type error message A non-Date argument to initialize_copy fell through to the default Object#initialize_copy, raising "initialize_copy should take same class object". The C extension raises "wrong argument type (expected Date)" (with "nil" for nil). Raise that instead, before the existing cross-class handling, so dup/clone and the Date/DateTime cross-class copy are unaffected. Verified against the C extension (date 3.6.0). --- lib/date/core.rb | 3 +++ 1 file changed, 3 insertions(+) diff --git a/lib/date/core.rb b/lib/date/core.rb index ee1b4bfe..349304a4 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1793,6 +1793,9 @@ def initialize_clone(other, **) # DateTime copying a Date, handled in DateTime#initialize_copy) go through # the default copy. def initialize_copy(other) + unless other.is_a?(Date) + raise TypeError, "wrong argument type #{other.nil? ? 'nil' : other.class} (expected Date)" + end if other.is_a?(DateTime) && !is_a?(DateTime) raise ArgumentError, "cannot load complex into simple" end From 3f526170842e6b5786b321e08049e8d180c788d5 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 21:37:48 +0900 Subject: [PATCH 141/144] Match NUM2DBL exactly for a non-numeric start The TypeError refinement in the previous commit was too strict. Follow the C extension's NUM2DBL precisely: nil, true, false, String and Symbol are rejected as "no implicit conversion of into Float" (true/false were previously reported as "can't convert TrueClass/FalseClass"), while any other object is accepted through #to_f -- a non-numeric object that defines #to_f is valid, not a TypeError (which the previous code wrongly raised). An object with no usable #to_f still raises "can't convert into Float". Verified against the C extension (date 3.6.0). --- lib/date/core.rb | 20 +++++++++++++------- test/date/test_date_new.rb | 16 ++++++++++++++++ 2 files changed, 29 insertions(+), 7 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 349304a4..454c4e0f 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -356,15 +356,21 @@ def convert_numeric_to_int(obj, field) # public constructor that accepts a +start+ runs its argument through this # before using it, so the calendar math and the stored @start agree. def validate_start(sg) - unless sg.is_a?(Numeric) - # Reject a non-numeric start with a TypeError, as the C extension's - # NUM2DBL does, rather than silently coercing it via #to_f. - if sg.nil? || sg.is_a?(String) || sg.is_a?(Symbol) - raise TypeError, "no implicit conversion of #{sg.nil? ? 'nil' : sg.class} into Float" - end + # Convert the start the way the C extension's NUM2DBL does: a Numeric via + # #to_f; nil/true/false and the builtin non-numerics (String, Symbol) are + # rejected outright ("no implicit conversion"); any other object is + # accepted through #to_f and otherwise rejected ("can't convert"). + if sg.is_a?(Numeric) + f = sg.to_f + elsif sg.nil? || sg.equal?(true) || sg.equal?(false) || + sg.is_a?(String) || sg.is_a?(Symbol) + name = sg.nil? ? "nil" : (sg.equal?(true) ? "true" : (sg.equal?(false) ? "false" : sg.class)) + raise TypeError, "no implicit conversion of #{name} into Float" + elsif sg.respond_to?(:to_f) && (v = sg.to_f).is_a?(Float) + f = v + else raise TypeError, "can't convert #{sg.class} into Float" end - f = sg.to_f # Fast path: a finite value inside the supported range (the common case, # including the ITALY/ENGLAND defaults). Ordered first so the hot path # avoids the #infinite?/#nan? method calls below. diff --git a/test/date/test_date_new.rb b/test/date/test_date_new.rb index 147ad27a..fb0f0b45 100644 --- a/test/date/test_date_new.rb +++ b/test/date/test_date_new.rb @@ -343,6 +343,22 @@ def test_non_numeric_start_raises assert_warning(/invalid start/) do assert_equal(true, Date.valid_civil?(2001, 2, 3, 3000000)) end + + # The NUM2DBL error wording follows the C extension: nil/true/false and the + # builtin non-numerics report "no implicit conversion of into + # Float", other objects "can't convert into Float". + assert_raise_with_message(TypeError, "no implicit conversion of nil into Float") { Date.new(2001, 1, 1, nil) } + assert_raise_with_message(TypeError, "no implicit conversion of true into Float") { Date.new(2001, 1, 1, true) } + assert_raise_with_message(TypeError, "no implicit conversion of false into Float") { Date.new(2001, 1, 1, false) } + assert_raise_with_message(TypeError, "no implicit conversion of String into Float") { Date.new(2001, 1, 1, "x") } + assert_raise_with_message(TypeError, "no implicit conversion of Symbol into Float") { Date.new(2001, 1, 1, :x) } + assert_raise_with_message(TypeError, "can't convert Object into Float") { Date.new(2001, 1, 1, Object.new) } + + # A non-numeric object that defines #to_f is accepted via #to_f, as the C + # extension does. + to_f_obj = Object.new + def to_f_obj.to_f; Date::ITALY.to_f; end + assert_equal(Date::ITALY, Date.new(2001, 1, 1, to_f_obj).start) end def test_invalid_start_datetime From 506ada1f20b8706568ae91cdc9606150b4d2e996 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 21:37:57 +0900 Subject: [PATCH 142/144] Raise "expected numeric" from Date#<< for a non-numeric count The C extension's d_lite_lshift rejects a non-numeric count up front with TypeError "expected numeric", whereas Date#>> lets Integer coercion fail with " can't be coerced into Integer". Date#<< (and Date#prev_month, which delegates to it) was giving the >> wording. Check Numeric first and raise "expected numeric"; >> is unchanged. Verified against the C extension (date 3.6.0). --- lib/date/core.rb | 10 +++++----- test/date/test_date_arith.rb | 5 +++++ 2 files changed, 10 insertions(+), 5 deletions(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 454c4e0f..22b8f86d 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -1268,11 +1268,11 @@ def >>(n) # d2 = d1 << -1 # => # # def <<(n) - # Negate the raw count before the shift so the floor is applied to -n - # (<< 1.5 is -2 months, not -1); a non-numeric count is left for #>> to - # reject with the right TypeError. - n = -n if Numeric === n - self >> n + # The C extension's d_lite_lshift rejects a non-numeric count up front + # (TypeError "expected numeric"), unlike #>>. Negate the raw count so the + # floor is applied to -n (<< 1.5 is -2 months, not -1). + raise TypeError, "expected numeric" unless Numeric === n + self >> -n end # call-seq: diff --git a/test/date/test_date_arith.rb b/test/date/test_date_arith.rb index 58caccbc..36eac463 100644 --- a/test/date/test_date_arith.rb +++ b/test/date/test_date_arith.rb @@ -56,6 +56,11 @@ def test_prev_month__ex assert_raise(e) { Date.new(2000, 1, 31) << nil } assert_raise(e) { Date.new(2000, 1, 31) << '1' } assert_raise(e) { DateTime.new(2000, 1, 31) << nil } + # Date#<< rejects a non-numeric up front ("expected numeric"), unlike Date#>> + # (which lets Integer coercion fail with "... can't be coerced ..."). + assert_raise_with_message(TypeError, "expected numeric") { Date.new(2000, 1, 31) << nil } + assert_raise_with_message(TypeError, "expected numeric") { Date.new(2000, 1, 31).prev_month(nil) } + assert_raise_with_message(TypeError, /can't be coerced into Integer/) { Date.new(2000, 1, 31) >> nil } end def test_step_upto_downto_additional_paths From 4ccb5a7eb6c9c88ea9e32576f6b5424440b956c5 Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 21:38:06 +0900 Subject: [PATCH 143/144] Start the last-day scan at the month length The negative-mday fix scanned down from day 31, so an ordinary month ran several validity checks before hitting its last day (February needed four), roughly halving Date.new(y, m, -1). Start the scan at the month's nominal length -- the longer of the Gregorian and Julian counts -- so an ordinary month resolves in one check; only a month truncated by a reform gap steps down further. Behavior is unchanged (verified against the C extension, date 3.6.0); Date.new(2001, 2, -1) is back to ~1.5x its post-fix speed. --- lib/date/core.rb | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/lib/date/core.rb b/lib/date/core.rb index 22b8f86d..6c28d1d2 100644 --- a/lib/date/core.rb +++ b/lib/date/core.rb @@ -539,8 +539,13 @@ def internal_valid_civil?(y, m, d, sg) # convert back to civil. This handles a calendar-reform gap near the end # of the month under any cutover, including a custom one whose next # month begins inside the gap (where "next month's 1st minus 1" fails). + # Start the scan at the month's nominal length (the longer of the two + # calendars' counts) so an ordinary month resolves in one check; only a + # month truncated by a reform gap needs to step down further. ldom_jd = nil - day = 31 + day = days_in_month_gregorian(y, m) + jdim = days_in_month_julian(y, m) + day = jdim if jdim > day while day >= 1 ldom_jd = valid_civil_positive_jd(y, m, day, sg) break if ldom_jd From 85e86128a80f8ee68450dabbbe6f745a55f031ce Mon Sep 17 00:00:00 2001 From: jinroq Date: Tue, 24 Nov 2026 21:38:06 +0900 Subject: [PATCH 144/144] Add a hash test for the UTC-instant rewrite Cover the hash change directly: same-instant/different-offset DateTimes hash equal (and are #eql?), a sub-second difference is #eql?-distinct, and a DateTime at midnight UTC hashes like the plain Date for that day. --- test/date/test_date.rb | 17 +++++++++++++++++ 1 file changed, 17 insertions(+) diff --git a/test/date/test_date.rb b/test/date/test_date.rb index 3c21a880..ee6fbca4 100644 --- a/test/date/test_date.rb +++ b/test/date/test_date.rb @@ -203,6 +203,23 @@ def test_hash assert_equal(0, h[Date.new(2001,2,3,Date::GREGORIAN)]) end + def test_hash_by_utc_instant + # The hash is computed from the UTC instant, so different offsets that + # denote the same moment hash equal (and are #eql?), while a sub-second + # difference is #eql?-distinct (its hash may collide, which is allowed). + a = DateTime.new(2001, 2, 3, 9, 0, 0, '+09:00') + b = DateTime.new(2001, 2, 3, 0, 0, 0, '+00:00') + assert_equal(a.hash, b.hash) + assert_operator(a, :eql?, b) + + c = DateTime.new(2001, 2, 3, 0, 0, Rational(1, 1000), '+00:00') + assert_not_operator(a, :eql?, c) + + # A DateTime at midnight UTC hashes like the plain Date for that day. + assert_equal(Date.new(2001, 2, 3).hash, b.hash) + assert_operator(Date.new(2001, 2, 3), :eql?, b) + end + def test_freeze d = Date.new d.freeze