Skip to content

Commit

Permalink
Fix Time#add_span boundary check
Browse files Browse the repository at this point in the history
Previously, this method did not handle times at the min or max range with positive or
negative offsets correctly because `@seconds` can legitimately be `< 0` or `> MAX_SECONDS`
when the offset is taken into account.
  • Loading branch information
straight-shoota committed Mar 8, 2018
1 parent 163c0cb commit 1864bc2
Show file tree
Hide file tree
Showing 2 changed files with 32 additions and 1 deletion.
31 changes: 31 additions & 0 deletions spec/std/time/time_spec.cr
Original file line number Diff line number Diff line change
Expand Up @@ -121,6 +121,37 @@ describe Time do
end
end

it "#add_span checks boundary at time min" do
{5 * 3600, 1, 0, -1, -5 * 3600}.each do |offset|
location = Time::Location.fixed(offset)

time = Time.new(1, 1, 1, location: location)
time.add_span(0, 1).should eq Time.new(1, 1, 1, nanosecond: 1, location: location)
time.add_span(0, 0).should eq time
expect_raises(ArgumentError) do
time.add_span(0, -1)
end
end
end

it "#add_span checks boundary at time max" do
{5 * 3600, 1, 0, -1, -5 * 3600}.each do |offset|
location = Time::Location.fixed(offset)

time = Time.new(9999, 12, 31, 23, 59, 59, nanosecond: 999_999_999, location: location)
time.add_span(0, -1).should eq Time.new(9999, 12, 31, 23, 59, 59, nanosecond: 999_999_998, location: location)
time.add_span(0, 0).should eq time
expect_raises(ArgumentError) do
time.add_span(0, 1)
end
end
end

it "adds zero span" do
time = Time.now
time.add_span(0, 0).should eq time
end

it "add days" do
t1 = Time.utc(2002, 2, 25, 15, 25, 13)
t1 = t1 + 3.days
Expand Down
2 changes: 1 addition & 1 deletion src/time.cr
Original file line number Diff line number Diff line change
Expand Up @@ -297,7 +297,7 @@ struct Time
nanoseconds += NANOSECONDS_PER_SECOND
end

unless 0 <= seconds <= MAX_SECONDS
unless 0 <= seconds + offset <= MAX_SECONDS
raise ArgumentError.new "Invalid time"
end

Expand Down

0 comments on commit 1864bc2

Please sign in to comment.