/
timestamp_codec.go
89 lines (82 loc) · 2.27 KB
/
timestamp_codec.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
package known
import (
"fmt"
"reflect"
"time"
"go.mongodb.org/mongo-driver/bson/bsoncodec"
"go.mongodb.org/mongo-driver/bson/bsonrw"
"go.mongodb.org/mongo-driver/bson/bsontype"
"google.golang.org/protobuf/types/known/timestamppb"
)
// Timestamp type.
var TypeTimestamp = reflect.TypeOf((*timestamppb.Timestamp)(nil))
// TimestampCodec is the Codec used for *timestamppb.Timestamp values.
type TimestampCodec struct{}
// EncodeValue is the ValueEncoderFunc for *timestamppb.Timestamp.
func (c *TimestampCodec) EncodeValue(ec bsoncodec.EncodeContext, vw bsonrw.ValueWriter, v reflect.Value) error {
if !v.IsValid() || v.Type() != TypeTimestamp {
return bsoncodec.ValueEncoderError{
Name: "TimestampCodec.EncodeValue",
Types: []reflect.Type{TypeTimestamp},
Received: v,
}
}
ts := v.Interface().(*timestamppb.Timestamp)
if ts == nil {
return vw.WriteNull()
}
return vw.WriteDateTime(ts.AsTime().UnixMilli())
}
// DecodeValue is the ValueDecoderFunc for *timestamppb.Timestamp.
func (c *TimestampCodec) DecodeValue(dc bsoncodec.DecodeContext, vr bsonrw.ValueReader, v reflect.Value) error {
if !v.CanSet() || v.Type() != TypeTimestamp {
return bsoncodec.ValueDecoderError{
Name: "TimestampCodec.DecodeValue",
Types: []reflect.Type{TypeTimestamp},
Received: v,
}
}
var ts *timestamppb.Timestamp
switch bsonTyp := vr.Type(); bsonTyp {
case bsontype.DateTime:
msec, err := vr.ReadDateTime()
if err != nil {
return err
}
ts = timestamppb.New(time.UnixMilli(msec))
case bsontype.Int64:
msec, err := vr.ReadInt64()
if err != nil {
return err
}
ts = timestamppb.New(time.UnixMilli(msec))
case bsontype.String:
s, err := vr.ReadString()
if err != nil {
return err
}
t, err := time.Parse(time.RFC3339Nano, s)
if err != nil {
return err
}
ts = timestamppb.New(t)
case bsontype.Null:
if err := vr.ReadNull(); err != nil {
return err
}
ts = nil
case bsontype.Undefined:
if err := vr.ReadUndefined(); err != nil {
return err
}
ts = ×tamppb.Timestamp{}
default:
return fmt.Errorf("cannot decode %v into a *timestamppb.Timestamp", bsonTyp)
}
v.Set(reflect.ValueOf(ts))
return nil
}
// NewTimestampCodec returns a TimestampCodec.
func NewTimestampCodec() *TimestampCodec {
return &TimestampCodec{}
}