-
Notifications
You must be signed in to change notification settings - Fork 0
/
timestamp.go
90 lines (77 loc) · 1.98 KB
/
timestamp.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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
package timestamppb
import (
"errors"
"strconv"
"strings"
time "time"
"github.com/aperturerobotics/protobuf-go-lite/json"
)
// ErrEmptyTimestamp is returned from Validate if the timestamp was empty.
var ErrEmptyTimestamp = errors.New("empty timestamp")
// ToTimestamp constructs a new Timestamp from the provided time.Time.
func ToTimestamp(t time.Time) *Timestamp {
return New(t)
}
// GetEmpty checks if the timestamp is empty.
func (x *Timestamp) GetEmpty() bool {
return x.SizeVT() == 0
}
// Validate is an alias to CheckValid.
func (x *Timestamp) Validate(allowEmpty bool) error {
isEmpty := x.GetEmpty()
if isEmpty {
if allowEmpty {
return nil
}
return ErrEmptyTimestamp
}
return x.CheckValid()
}
// MarshalJSON marshals the Timestamp to JSON.
func (x *Timestamp) MarshalJSON() ([]byte, error) {
return json.DefaultMarshalerConfig.Marshal(x)
}
// UnmarshalJSON unmarshals the Timestamp from JSON.
func (x *Timestamp) UnmarshalJSON(b []byte) error {
return json.DefaultUnmarshalerConfig.Unmarshal(b, x)
}
// UnmarshalProtoJSON unmarshals a Timestamp from JSON.
func (x *Timestamp) UnmarshalProtoJSON(s *json.UnmarshalState) {
if s.ReadNil() {
return
}
t := s.ReadTime()
if s.Err() != nil {
return
}
*x = *New(*t)
}
// MarshalProtoJSON marshals a Timestamp to JSON.
func (x *Timestamp) MarshalProtoJSON(s *json.MarshalState) {
if x == nil {
s.WriteNil()
return
}
s.WriteTime(x.AsTime())
}
// String formats the timestamp to a string.
func (t *Timestamp) String() string {
var out strings.Builder
secs, nanos := t.GetSeconds(), t.GetNanos()
if secs != 0 {
_, _ = out.WriteString("seconds:")
_, _ = out.WriteString(strconv.FormatInt(secs, 10))
}
if nanos != 0 {
if out.Len() != 0 {
_, _ = out.WriteString(" ")
}
_, _ = out.WriteString("nanos:")
_, _ = out.WriteString(strconv.Itoa(int(nanos)))
}
return out.String()
}
// MarshalProtoText formats the Timestamp to a proto text string.
func (t *Timestamp) MarshalProtoText() string {
return t.String()
}