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