This repository has been archived by the owner on Sep 18, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
clock.go
61 lines (51 loc) · 1.46 KB
/
clock.go
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
package clock
import (
"time"
"github.com/golang/protobuf/ptypes/duration"
"github.com/golang/protobuf/ptypes/timestamp"
)
func DurationToPB(in time.Duration) *duration.Duration {
// the duration as an integer nanosecond count
nsTotal := in.Nanoseconds()
var seconds int64
var nanos int32
if time.Duration(nsTotal) > time.Second {
nanos = int32(nsTotal % int64(time.Second))
seconds = int64(time.Duration(nsTotal-int64(nanos)) / time.Second)
} else if time.Duration(nsTotal) == time.Second {
seconds = 1
} else {
nanos = int32(nsTotal)
}
return &duration.Duration{
Seconds: seconds,
Nanos: nanos,
}
}
func DurationFromPB(in *duration.Duration) time.Duration {
sec := time.Duration(in.Seconds) * time.Second
ns := time.Duration(in.Nanos) * time.Nanosecond
return sec + ns
}
// TimestampToTime converts a Timestamp (from Google's well-known Protocol Buffer types) to a time.Time.
func TimestampToTime(pb *timestamp.Timestamp) time.Time {
if pb != nil {
if pb.Seconds != 0 {
return time.Unix(pb.Seconds, int64(pb.Nanos))
}
}
return time.Time{}
}
// TimeToTimestamp converts a time.Time into Timestamp (from Google's well-known Protocol Buffer types).
func TimeToTimestamp(t time.Time) *timestamp.Timestamp {
if t.IsZero() {
return nil
}
return ×tamp.Timestamp{
Seconds: t.Unix(),
Nanos: timeToNanosecondSecondFraction(t),
}
}
func timeToNanosecondSecondFraction(in time.Time) int32 {
return int32(in.UnixNano() % 1000000000)
}