time_as_int64_codec.go 736 B

12345678910111213141516171819202122232425262728
  1. package extra
  2. import (
  3. "github.com/json-iterator/go"
  4. "unsafe"
  5. "time"
  6. )
  7. // keep epoch milliseconds
  8. func RegisterTimeAsInt64Codec(precision time.Duration) {
  9. jsoniter.RegisterTypeEncoder("time.Time", &timeAsInt64Codec{precision})
  10. }
  11. type timeAsInt64Codec struct {
  12. precision time.Duration
  13. }
  14. func (codec *timeAsInt64Codec) IsEmpty(ptr unsafe.Pointer) bool {
  15. ts := *((*time.Time)(ptr))
  16. return ts.UnixNano() == 0
  17. }
  18. func (codec *timeAsInt64Codec) Encode(ptr unsafe.Pointer, stream *jsoniter.Stream) {
  19. ts := *((*time.Time)(ptr))
  20. stream.WriteInt64(ts.UnixNano() / codec.precision.Nanoseconds())
  21. }
  22. func (codec *timeAsInt64Codec) EncodeInterface(val interface{}, stream *jsoniter.Stream) {
  23. jsoniter.WriteToStream(val, stream, codec)
  24. }