mirror of
https://github.com/tailscale/tailscale.git
synced 2025-04-21 06:01:42 +00:00
util/deephash: add AppendSum method (#5768)
This method can be used to obtain the hex-formatted deephash.Sum instance without allocations. Signed-off-by: Andrew Dunham <andrew@du.nham.ca>
This commit is contained in:
parent
ebd1637e50
commit
4b996ad5e3
@ -106,9 +106,20 @@ func (s1 *Sum) xor(s2 Sum) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
func (s Sum) String() string {
|
func (s Sum) String() string {
|
||||||
|
// Note: if we change this, keep in sync with AppendTo
|
||||||
return hex.EncodeToString(s.sum[:])
|
return hex.EncodeToString(s.sum[:])
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// AppendTo appends the string encoding of this sum (as returned by the String
|
||||||
|
// method) to the provided byte slice and returns the extended buffer.
|
||||||
|
func (s Sum) AppendTo(b []byte) []byte {
|
||||||
|
// TODO: switch to upstream implementation if accepted:
|
||||||
|
// https://github.com/golang/go/issues/53693
|
||||||
|
var lb [len(s.sum) * 2]byte
|
||||||
|
hex.Encode(lb[:], s.sum[:])
|
||||||
|
return append(b, lb[:]...)
|
||||||
|
}
|
||||||
|
|
||||||
var (
|
var (
|
||||||
seedOnce sync.Once
|
seedOnce sync.Once
|
||||||
seed uint64
|
seed uint64
|
||||||
|
@ -1050,3 +1050,25 @@ func FuzzAddr(f *testing.F) {
|
|||||||
}
|
}
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestAppendTo(t *testing.T) {
|
||||||
|
v := getVal()
|
||||||
|
h := Hash(v)
|
||||||
|
sum := h.AppendTo(nil)
|
||||||
|
|
||||||
|
if s := h.String(); s != string(sum) {
|
||||||
|
t.Errorf("hash sum mismatch; h.String()=%q h.AppendTo()=%q", s, string(sum))
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
func BenchmarkAppendTo(b *testing.B) {
|
||||||
|
b.ReportAllocs()
|
||||||
|
v := getVal()
|
||||||
|
h := Hash(v)
|
||||||
|
|
||||||
|
hashBuf := make([]byte, 0, 100)
|
||||||
|
b.ResetTimer()
|
||||||
|
for i := 0; i < b.N; i++ {
|
||||||
|
hashBuf = h.AppendTo(hashBuf[:0])
|
||||||
|
}
|
||||||
|
}
|
||||||
|
Loading…
x
Reference in New Issue
Block a user