...
1 package extra
2
3 import (
4 "github.com/json-iterator/go"
5 "time"
6 "unsafe"
7 )
8
9
10 func RegisterTimeAsInt64Codec(precision time.Duration) {
11 jsoniter.RegisterTypeEncoder("time.Time", &timeAsInt64Codec{precision})
12 jsoniter.RegisterTypeDecoder("time.Time", &timeAsInt64Codec{precision})
13 }
14
15 type timeAsInt64Codec struct {
16 precision time.Duration
17 }
18
19 func (codec *timeAsInt64Codec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
20 nanoseconds := iter.ReadInt64() * codec.precision.Nanoseconds()
21 *((*time.Time)(ptr)) = time.Unix(0, nanoseconds)
22 }
23
24 func (codec *timeAsInt64Codec) IsEmpty(ptr unsafe.Pointer) bool {
25 ts := *((*time.Time)(ptr))
26 return ts.UnixNano() == 0
27 }
28 func (codec *timeAsInt64Codec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
29 ts := *((*time.Time)(ptr))
30 stream.WriteInt64(ts.UnixNano() / codec.precision.Nanoseconds())
31 }
32
View as plain text