]> Cypherpunks repositories - gostls13.git/commitdiff
[release-branch.go1.14] hash/maphash: don't discard data on random seed init
authorvovapi <evgrafov.vladimir@gmail.com>
Thu, 20 Feb 2020 19:29:22 +0000 (19:29 +0000)
committerDmitri Shuralyov <dmitshur@golang.org>
Mon, 24 Feb 2020 15:47:07 +0000 (15:47 +0000)
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: 48b2f963e86c1b37d49b838a050cc4128bb01266
GitHub-Pull-Request: golang/go#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 638df87fa4f927763f99ebf0c6bc9c4a5380d1f9)
Reviewed-on: https://go-review.googlesource.com/c/go/+/220617
Run-TryBot: Dmitri Shuralyov <dmitshur@golang.org>

src/hash/maphash/maphash.go
src/hash/maphash/maphash_test.go

index 4fef88e8ee5344ecba842efc67c89ae2f80c6c51..071dc04b5489566720e0725ac631f541f4ff8a38 100644 (file)
@@ -69,7 +69,7 @@ type Hash struct {
 // which does call h.initSeed.)
 func (h *Hash) initSeed() {
        if h.seed.s == 0 {
-               h.SetSeed(MakeSeed())
+               h.setSeed(MakeSeed())
        }
 }
 
@@ -124,12 +124,17 @@ func (h *Hash) Seed() Seed {
 // Two Hash objects with different seeds will very likely behave differently.
 // Any bytes added to h before this call will be discarded.
 func (h *Hash) SetSeed(seed Seed) {
+       h.setSeed(seed)
+       h.n = 0
+}
+
+// setSeed sets seed without discarding accumulated data.
+func (h *Hash) setSeed(seed Seed) {
        if seed.s == 0 {
                panic("maphash: use of uninitialized Seed")
        }
        h.seed = seed
        h.state = seed
-       h.n = 0
 }
 
 // Reset discards all bytes added to h.
index 31d84a3b50a74fd0f4802a86d595be3279d0e29a..0164a9e20ae48212c553b93d00f9efed4fa7ade2 100644 (file)
@@ -83,6 +83,29 @@ func TestHashHighBytes(t *testing.T) {
        }
 }
 
+func TestRepeat(t *testing.T) {
+       h1 := new(Hash)
+       h1.WriteString("testing")
+       sum1 := h1.Sum64()
+
+       h1.Reset()
+       h1.WriteString("testing")
+       sum2 := h1.Sum64()
+
+       if sum1 != sum2 {
+               t.Errorf("different sum after reseting: %#x != %#x", sum1, sum2)
+       }
+
+       h2 := new(Hash)
+       h2.SetSeed(h1.Seed())
+       h2.WriteString("testing")
+       sum3 := h2.Sum64()
+
+       if sum1 != sum3 {
+               t.Errorf("different sum on the same seed: %#x != %#x", sum1, sum3)
+       }
+}
+
 // Make sure a Hash implements the hash.Hash and hash.Hash64 interfaces.
 var _ hash.Hash = &Hash{}
 var _ hash.Hash64 = &Hash{}