util/deephash: tighten up SelfHasher API (#11012)

Providing a hash.Block512 is an implementation detail of how deephash
works today, but providing an opaque type with mostly equivalent API
(i.e., HashUint8, HashBytes, etc. methods) is still sensible.
Thus, define a public Hasher type that exposes exactly the API
that an implementation of SelfHasher would want to call.
This gives us freedom to change the hashing algorithm of deephash
at some point in the future.

Also, this type is likely going to be called by types that are
going to memoize their own hash results, we additionally add
a HashSum method to simplify this use case.

Add documentation to SelfHasher on how a type might implement it.

Updates: corp#16409

Signed-off-by: Joe Tsai <joetsai@digital-static.net>
This commit is contained in:
Joe Tsai
2024-02-01 17:07:41 -08:00
committed by GitHub
parent 84f8311bcd
commit 60657ac83f
4 changed files with 85 additions and 36 deletions

View File

@ -42,11 +42,19 @@ func (p appendBytes) AppendTo(b []byte) []byte {
return append(b, p...)
}
type implsSelfHasherValueRecv struct {
type selfHasherValueRecv struct {
emit uint64
}
func (s implsSelfHasherValueRecv) Hash(h *hashx.Block512) {
func (s selfHasherValueRecv) Hash(h *hashx.Block512) {
h.HashUint64(s.emit)
}
type selfHasherPointerRecv struct {
emit uint64
}
func (s *selfHasherPointerRecv) Hash(h *hashx.Block512) {
h.HashUint64(s.emit)
}
@ -178,12 +186,12 @@ func TestHash(t *testing.T) {
b[0] = 1
return b
}()))}, wantEq: false},
{in: tuple{&implsSelfHasher{}, &implsSelfHasher{}}, wantEq: true},
{in: tuple{(*implsSelfHasher)(nil), (*implsSelfHasher)(nil)}, wantEq: true},
{in: tuple{(*implsSelfHasher)(nil), &implsSelfHasher{}}, wantEq: false},
{in: tuple{&implsSelfHasher{emit: 1}, &implsSelfHasher{emit: 2}}, wantEq: false},
{in: tuple{implsSelfHasherValueRecv{emit: 1}, implsSelfHasherValueRecv{emit: 2}}, wantEq: false},
{in: tuple{implsSelfHasherValueRecv{emit: 2}, implsSelfHasherValueRecv{emit: 2}}, wantEq: true},
{in: tuple{&selfHasherPointerRecv{}, &selfHasherPointerRecv{}}, wantEq: true},
{in: tuple{(*selfHasherPointerRecv)(nil), (*selfHasherPointerRecv)(nil)}, wantEq: true},
{in: tuple{(*selfHasherPointerRecv)(nil), &selfHasherPointerRecv{}}, wantEq: false},
{in: tuple{&selfHasherPointerRecv{emit: 1}, &selfHasherPointerRecv{emit: 2}}, wantEq: false},
{in: tuple{selfHasherValueRecv{emit: 1}, selfHasherValueRecv{emit: 2}}, wantEq: false},
{in: tuple{selfHasherValueRecv{emit: 2}, selfHasherValueRecv{emit: 2}}, wantEq: true},
}
for _, tt := range tests {