Skip to content
This repository has been archived by the owner on Jul 22, 2024. It is now read-only.

Commit

Permalink
Fix time.Time hashes
Browse files Browse the repository at this point in the history
  • Loading branch information
F21 committed Feb 13, 2019
1 parent a38c501 commit 20ffafb
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
15 changes: 15 additions & 0 deletions hashstructure.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"hash"
"hash/fnv"
"reflect"
"time"
)

// ErrNotStringer is returned when there's an error with hash:"string"
Expand Down Expand Up @@ -104,6 +105,8 @@ type visitOpts struct {
StructField string
}

var timeType = reflect.TypeOf(time.Time{})

func (w *walker) visit(v reflect.Value, opts *visitOpts) (uint64, error) {
t := reflect.TypeOf(0)

Expand Down Expand Up @@ -159,6 +162,18 @@ func (w *walker) visit(v reflect.Value, opts *visitOpts) (uint64, error) {
return w.h.Sum64(), err
}

switch v.Type() {
case timeType:
w.h.Reset()
b, err := v.Interface().(time.Time).MarshalBinary()
if err != nil {
return 0, err
}

err = binary.Write(w.h, binary.LittleEndian, b)
return w.h.Sum64(), err
}

switch k {
case reflect.Array:
var h uint64
Expand Down
15 changes: 15 additions & 0 deletions hashstructure_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -66,6 +66,8 @@ func TestHash_equal(t *testing.T) {
type testFoo struct{ Name string }
type testBar struct{ Name string }

now := time.Now()

cases := []struct {
One, Two interface{}
Match bool
Expand Down Expand Up @@ -155,6 +157,12 @@ func TestHash_equal(t *testing.T) {
},
true,
},
{
now, // contains monotonic clock
time.Date(now.Year(), now.Month(), now.Day(), now.Hour(),
now.Minute(), now.Second(), now.Nanosecond(), now.Location()), // does not contain monotonic clock
true,
},
}

for i, tc := range cases {
Expand Down Expand Up @@ -247,6 +255,13 @@ func TestHash_equalIgnore(t *testing.T) {
{
TestTime2{Name: "foo", Time: now},
TestTime2{Name: "foo", Time: time.Time{}},
false,
},
{
TestTime2{Name: "foo", Time: now},
TestTime2{Name: "foo", Time: time.Date(now.Year(), now.Month(), now.Day(), now.Hour(),
now.Minute(), now.Second(), now.Nanosecond(), now.Location()),
},
true,
},
}
Expand Down

0 comments on commit 20ffafb

Please sign in to comment.