time_as_int64_codec.go 956 B

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