timestamp.go 744 B

12345678910111213141516171819202122232425262728293031323334353637383940
  1. package sarama
  2. import (
  3. "fmt"
  4. "time"
  5. )
  6. type Timestamp struct {
  7. *time.Time
  8. }
  9. func (t Timestamp) encode(pe packetEncoder) error {
  10. timestamp := int64(-1)
  11. if !t.Before(time.Unix(0, 0)) {
  12. timestamp = t.UnixNano() / int64(time.Millisecond)
  13. } else if !t.IsZero() {
  14. return PacketEncodingError{fmt.Sprintf("invalid timestamp (%v)", t)}
  15. }
  16. pe.putInt64(timestamp)
  17. return nil
  18. }
  19. func (t Timestamp) decode(pd packetDecoder) error {
  20. millis, err := pd.getInt64()
  21. if err != nil {
  22. return err
  23. }
  24. // negative timestamps are invalid, in these cases we should return
  25. // a zero time
  26. timestamp := time.Time{}
  27. if millis >= 0 {
  28. timestamp = time.Unix(millis/1000, (millis%1000)*int64(time.Millisecond))
  29. }
  30. *t.Time = timestamp
  31. return nil
  32. }