-
Notifications
You must be signed in to change notification settings - Fork 22
Expand file tree
/
Copy pathduration.pb.ex
More file actions
69 lines (53 loc) · 1.74 KB
/
duration.pb.ex
File metadata and controls
69 lines (53 loc) · 1.74 KB
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
65
66
67
68
69
defmodule Google.Protobuf.Duration do
@moduledoc false
use Protobuf, syntax: :proto3, protoc_gen_elixir_version: "0.12.0"
field :seconds, 1, type: :int64
field :nanos, 2, type: :int32
@doc """
Converts a `Google.Protobuf.Duration` to a value and `System.time_unit()`.
## Examples
iex> Duration.to_time_unit(%Duration{seconds: 10})
{10, :second}
iex> Duration.to_time_unit(%Duration{seconds: 20, nanos: 100})
{20_000_000_100, :nanosecond}
"""
@spec to_time_unit(__MODULE__.t()) :: {integer(), System.time_unit()}
def to_time_unit(%{seconds: seconds, nanos: 0}) do
{seconds, :second}
end
def to_time_unit(%{seconds: seconds, nanos: nanos}) do
{seconds * 1_000_000_000 + nanos, :nanosecond}
end
@doc """
Converts a value and `System.time_unit()` to a `Google.Protobuf.Duration`.
## Examples
iex> Duration.from_time_unit(11, :second)
%Duration{seconds: 11}
iex> Duration.from_time_unit(11_111_111, :microsecond)
%Duration{seconds: 11, nanos: 111_111_000}
"""
@spec from_time_unit(integer(), System.time_unit()) :: __MODULE__.t()
def from_time_unit(seconds, :second) do
struct(__MODULE__, %{
seconds: seconds
})
end
def from_time_unit(millisecond, :millisecond) do
struct(__MODULE__, %{
seconds: div(millisecond, 1_000),
nanos: rem(millisecond, 1_000) * 1_000_000
})
end
def from_time_unit(millisecond, :microsecond) do
struct(__MODULE__, %{
seconds: div(millisecond, 1_000_000),
nanos: rem(millisecond, 1_000_000) * 1_000
})
end
def from_time_unit(millisecond, :nanosecond) do
struct(__MODULE__, %{
seconds: div(millisecond, 1_000_000_000),
nanos: rem(millisecond, 1_000_000_000)
})
end
end