Skip to content

Commit

Permalink
Fix Time::Span multiply and divide (#5563)
Browse files Browse the repository at this point in the history
  • Loading branch information
petoem authored and asterite committed Jan 10, 2018
1 parent 5f1440d commit a3ca37e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 3 deletions.
4 changes: 4 additions & 0 deletions spec/std/time/span_spec.cr
Expand Up @@ -198,17 +198,21 @@ describe Time::Span do
it "test multiply" do
t1 = Time::Span.new 5, 4, 3, 2, 1_000_000
t2 = t1 * 61
t3 = t1 * 0.5

t2.should eq(Time::Span.new 315, 7, 5, 2, 61_000_000)
t3.should eq(Time::Span.new 2, 14, 1, 31, 500_000)

# TODO check overflow
end

it "test divide" do
t1 = Time::Span.new 3, 3, 3, 3, 3_000_000
t2 = t1 / 2
t3 = t1 / 1.5

t2.should eq(Time::Span.new(1, 13, 31, 31, 501_000_000) + Time::Span.new(nanoseconds: 500_000))
t3.should eq(Time::Span.new 2, 2, 2, 2, 2_000_000)

# TODO check overflow
end
Expand Down
17 changes: 14 additions & 3 deletions src/time/span.cr
Expand Up @@ -291,15 +291,21 @@ struct Time::Span
end

# Returns a `Time::Span` that is *number* times longer.
def *(number : Number) : Time::Span
def *(number : Int) : Time::Span
# TODO check overflow
Span.new(
seconds: to_i.to_i64 * number,
seconds: to_i * number,
nanoseconds: nanoseconds.to_i64 * number,
)
end

def /(number : Number) : Time::Span
# Returns a `Time::Span` that is *number* times longer.
def *(number : Float) : Time::Span
(total_nanoseconds * number).nanoseconds
end

# Returns a `Time::Span` that is divided by *number*.
def /(number : Int) : Time::Span
seconds = to_i.tdiv(number)
nanoseconds = self.nanoseconds.tdiv(number)

Expand All @@ -313,6 +319,11 @@ struct Time::Span
)
end

# Returns a `Time::Span` that is divided by *number*.
def /(number : Float) : Time::Span
(total_nanoseconds / number).nanoseconds
end

def /(other : self) : Float64
total_nanoseconds.to_f64 / other.total_nanoseconds.to_f64
end
Expand Down

0 comments on commit a3ca37e

Please sign in to comment.