Skip to content

hash/maphash: don't discard data on random seed init #37328

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 2 commits into from
Closed
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
9 changes: 7 additions & 2 deletions src/hash/maphash/maphash.go
Original file line number Diff line number Diff line change
Expand Up @@ -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())
}
}

Expand Down Expand Up @@ -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.
Expand Down
23 changes: 23 additions & 0 deletions src/hash/maphash/maphash_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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{}