blob: 372278d0bfa2288e2c02033996f1829e5b696025 [file] [log] [blame]
Dinesh Belwalkare63f7f92019-11-22 23:11:16 +00001package sarama
2
3import (
4 "fmt"
5 "time"
6)
7
8type Timestamp struct {
9 *time.Time
10}
11
12func (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
25func (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}