2017-06-20 11:43:47 +02:00
|
|
|
package extra
|
|
|
|
|
|
|
|
import (
|
|
|
|
"github.com/json-iterator/go"
|
|
|
|
"time"
|
2017-06-20 18:26:18 +02:00
|
|
|
"unsafe"
|
2017-06-20 11:43:47 +02:00
|
|
|
)
|
|
|
|
|
2017-07-09 08:17:40 +02:00
|
|
|
// RegisterTimeAsInt64Codec encode/decode time since number of unit since epoch. the precision is the unit.
|
2017-06-20 11:46:29 +02:00
|
|
|
func RegisterTimeAsInt64Codec(precision time.Duration) {
|
|
|
|
jsoniter.RegisterTypeEncoder("time.Time", &timeAsInt64Codec{precision})
|
2017-06-20 11:52:41 +02:00
|
|
|
jsoniter.RegisterTypeDecoder("time.Time", &timeAsInt64Codec{precision})
|
2017-06-20 11:43:47 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
type timeAsInt64Codec struct {
|
2017-06-20 11:46:29 +02:00
|
|
|
precision time.Duration
|
2017-06-20 11:43:47 +02:00
|
|
|
}
|
2017-06-20 18:26:18 +02:00
|
|
|
|
2017-06-20 11:52:41 +02:00
|
|
|
func (codec *timeAsInt64Codec) Decode(ptr unsafe.Pointer, iter *jsoniter.Iterator) {
|
|
|
|
nanoseconds := iter.ReadInt64() * codec.precision.Nanoseconds()
|
|
|
|
*((*time.Time)(ptr)) = time.Unix(0, nanoseconds)
|
|
|
|
}
|
2017-06-20 11:43:47 +02:00
|
|
|
|
|
|
|
func (codec *timeAsInt64Codec) IsEmpty(ptr unsafe.Pointer) bool {
|
|
|
|
ts := *((*time.Time)(ptr))
|
|
|
|
return ts.UnixNano() == 0
|
|
|
|
}
|
|
|
|
func (codec *timeAsInt64Codec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
|
|
|
|
ts := *((*time.Time)(ptr))
|
2017-06-20 11:46:29 +02:00
|
|
|
stream.WriteInt64(ts.UnixNano() / codec.precision.Nanoseconds())
|
2017-06-20 11:43:47 +02:00
|
|
|
}
|