Skip to content

Commit 17acbdb

Browse files
vovapidmitshur
authored andcommitted
[release-branch.go1.14] hash/maphash: don't discard data on random seed init
Hash initializes seed on the first usage of seed or state with initSeed. initSeed uses SetSeed which discards accumulated data. This causes hash to return different sums for the same data in the first use and after reset. This CL fixes this issue by separating the seed set from data discard. Updates #37315 Change-Id: Ic7020702c2ce822eb700af462e37efab12f72054 GitHub-Last-Rev: 48b2f96 GitHub-Pull-Request: #37328 Reviewed-on: https://go-review.googlesource.com/c/go/+/220259 Run-TryBot: Emmanuel Odeke <emm.odeke@gmail.com> TryBot-Result: Gobot Gobot <gobot@golang.org> Reviewed-by: Keith Randall <khr@golang.org> (cherry picked from commit 638df87) Reviewed-on: https://go-review.googlesource.com/c/go/+/220617 Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>
1 parent babeec2 commit 17acbdb

File tree

2 files changed

+30
-2
lines changed

2 files changed

+30
-2
lines changed

src/hash/maphash/maphash.go

+7-2
Original file line numberDiff line numberDiff line change
@@ -69,7 +69,7 @@ type Hash struct {
6969
// which does call h.initSeed.)
7070
func (h *Hash) initSeed() {
7171
if h.seed.s == 0 {
72-
h.SetSeed(MakeSeed())
72+
h.setSeed(MakeSeed())
7373
}
7474
}
7575

@@ -124,12 +124,17 @@ func (h *Hash) Seed() Seed {
124124
// Two Hash objects with different seeds will very likely behave differently.
125125
// Any bytes added to h before this call will be discarded.
126126
func (h *Hash) SetSeed(seed Seed) {
127+
h.setSeed(seed)
128+
h.n = 0
129+
}
130+
131+
// setSeed sets seed without discarding accumulated data.
132+
func (h *Hash) setSeed(seed Seed) {
127133
if seed.s == 0 {
128134
panic("maphash: use of uninitialized Seed")
129135
}
130136
h.seed = seed
131137
h.state = seed
132-
h.n = 0
133138
}
134139

135140
// Reset discards all bytes added to h.

src/hash/maphash/maphash_test.go

+23
Original file line numberDiff line numberDiff line change
@@ -83,6 +83,29 @@ func TestHashHighBytes(t *testing.T) {
8383
}
8484
}
8585

86+
func TestRepeat(t *testing.T) {
87+
h1 := new(Hash)
88+
h1.WriteString("testing")
89+
sum1 := h1.Sum64()
90+
91+
h1.Reset()
92+
h1.WriteString("testing")
93+
sum2 := h1.Sum64()
94+
95+
if sum1 != sum2 {
96+
t.Errorf("different sum after reseting: %#x != %#x", sum1, sum2)
97+
}
98+
99+
h2 := new(Hash)
100+
h2.SetSeed(h1.Seed())
101+
h2.WriteString("testing")
102+
sum3 := h2.Sum64()
103+
104+
if sum1 != sum3 {
105+
t.Errorf("different sum on the same seed: %#x != %#x", sum1, sum3)
106+
}
107+
}
108+
86109
// Make sure a Hash implements the hash.Hash and hash.Hash64 interfaces.
87110
var _ hash.Hash = &Hash{}
88111
var _ hash.Hash64 = &Hash{}

0 commit comments

Comments
 (0)