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

Fix time.Time hashes #21

Merged
merged 1 commit into from
Nov 22, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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