Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 14 additions & 6 deletions lib/elixir/lib/kernel.ex
Original file line number Diff line number Diff line change
Expand Up @@ -6421,12 +6421,20 @@ defmodule Kernel do
{microsecond, _precision} = duration.microsecond
millisecond = :erlang.convert_time_unit(microsecond, :microsecond, :millisecond)

duration.week * unquote(week_in_ms) +
duration.day * unquote(day_in_ms) +
duration.hour * unquote(hour_in_ms) +
duration.minute * 60_000 +
duration.second * 1000 +
millisecond
total =
duration.week * unquote(week_in_ms) +
duration.day * unquote(day_in_ms) +
duration.hour * unquote(hour_in_ms) +
duration.minute * 60_000 +
duration.second * 1000 +
millisecond

if total < 0 do
raise ArgumentError,
"duration must be positive, got: #{inspect(duration)}"
end

total
end
end

Expand Down
10 changes: 10 additions & 0 deletions lib/elixir/test/elixir/kernel_test.exs
Original file line number Diff line number Diff line change
Expand Up @@ -1550,6 +1550,16 @@ defmodule KernelTest do
end
end

test "raises on durations that result in a negative timeout" do
assert_raise ArgumentError,
~r"duration must be positive",
fn -> to_timeout(Duration.new!(second: -1)) end

assert_raise ArgumentError,
~r"duration must be positive",
fn -> to_timeout(Duration.new!(hour: 1, minute: -61)) end
end

test "works with timeouts" do
assert to_timeout(1_000) == 1_000
assert to_timeout(0) == 0
Expand Down
Loading