Skip to content

Commit

Permalink
Add read/write duration tests
Browse files Browse the repository at this point in the history
  • Loading branch information
arl authored and philhofer committed Jul 19, 2022
1 parent 222902d commit f3635b9
Show file tree
Hide file tree
Showing 4 changed files with 47 additions and 0 deletions.
5 changes: 5 additions & 0 deletions msgp/read.go
Original file line number Diff line number Diff line change
Expand Up @@ -36,6 +36,7 @@ const (
IntType
UintType
NilType
DurationType
ExtensionType

// pseudo-types provided
Expand Down Expand Up @@ -1308,6 +1309,10 @@ func (m *Reader) ReadIntf() (i interface{}, err error) {
i, err = m.ReadTime()
return

case DurationType:
i, err = m.ReadDuration()
return

case ExtensionType:
var t int8
t, err = m.peekExtensionType()
Expand Down
7 changes: 7 additions & 0 deletions msgp/read_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ func TestReadIntf(t *testing.T) {
int64(-40),
uint64(9082981),
time.Now(),
48*time.Hour + 3*time.Minute + 2*time.Second + 3*time.Nanosecond,
"hello!",
[]byte("hello!"),
map[string]interface{}{
Expand Down Expand Up @@ -66,6 +67,12 @@ func TestReadIntf(t *testing.T) {
if !tm.Equal(v.(time.Time)) {
t.Errorf("%v != %v", ts, v)
}
} else if intd, ok := ts.(time.Duration); ok {
/* for time.Duration, cast before comparing */
outtd := time.Duration(v.(int64))
if intd != outtd {
t.Errorf("%v in; %v out", intd, outtd)
}
} else if !reflect.DeepEqual(v, ts) {
t.Errorf("%v in; %v out", ts, v)
}
Expand Down
2 changes: 2 additions & 0 deletions msgp/write.go
Original file line number Diff line number Diff line change
Expand Up @@ -687,6 +687,8 @@ func (mw *Writer) WriteIntf(v interface{}) error {
return mw.WriteMapStrIntf(v)
case time.Time:
return mw.WriteTime(v)
case time.Duration:
return mw.WriteDuration(v)
}

val := reflect.ValueOf(v)
Expand Down
33 changes: 33 additions & 0 deletions msgp/write_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -214,6 +214,39 @@ func TestWriteFloat64(t *testing.T) {
}
}

func TestReadWriterDuration(t *testing.T) {
var buf bytes.Buffer
wr := NewWriter(&buf)

for i := 0; i < 10000; i++ {
buf.Reset()
dur := time.Duration(rand.Int63())
err := wr.WriteDuration(dur)
if err != nil {
t.Errorf("Error with %v: %s", dur, err)
}
err = wr.Flush()
if err != nil {
t.Fatal(err)
}

bts := buf.Bytes()

if bts[0] != mint64 {
t.Errorf("Leading byte was %x and not %x", bts[0], mint64)
}

wr := NewReader(&buf)
d, err := wr.ReadDuration()
if err != nil {
t.Errorf("Error reading duration: %v", err)
}
if d != dur {
t.Errorf("Got duration %v, want %v", d, dur)
}
}
}

func BenchmarkWriteFloat64(b *testing.B) {
f := rand.Float64()
wr := NewWriter(Nowhere)
Expand Down

0 comments on commit f3635b9

Please sign in to comment.