Skip to content

Commit 9b8dc63

Browse files
authored
Merge pull request #91 from microsoft/hash-noalloc
Add tests for confirming struct and oneshot hashes are not allocating
2 parents 97653fc + 7f33032 commit 9b8dc63

File tree

2 files changed

+56
-1
lines changed

2 files changed

+56
-1
lines changed

.github/workflows/test.yml

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@ jobs:
55
strategy:
66
fail-fast: false
77
matrix:
8-
go-version: [1.22.x, 1.23.x]
8+
go-version: [1.23.x, 1.24.x]
99
venv: [windows-2019, windows-2022]
1010
fips: [1, 0]
1111
runs-on: ${{ matrix.venv }}

cng/hash_test.go

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -181,6 +181,61 @@ func TestHash_OneShot(t *testing.T) {
181181
}
182182
}
183183

184+
func TestHashAllocations(t *testing.T) {
185+
msg := []byte("testing")
186+
n := int(testing.AllocsPerRun(10, func() {
187+
sink ^= cng.MD4(msg)[0]
188+
sink ^= cng.MD5(msg)[0]
189+
sink ^= cng.SHA1(msg)[0]
190+
sink ^= cng.SHA256(msg)[0]
191+
sink ^= cng.SHA384(msg)[0]
192+
sink ^= cng.SHA512(msg)[0]
193+
}))
194+
want := 0
195+
if n > want {
196+
t.Errorf("allocs = %d, want %d", n, want)
197+
}
198+
}
199+
200+
func TestHashStructAllocations(t *testing.T) {
201+
msg := []byte("testing")
202+
203+
md4Hash := cng.NewMD4()
204+
md5Hash := cng.NewMD5()
205+
sha1Hash := cng.NewSHA1()
206+
sha256Hash := cng.NewSHA256()
207+
sha384Hash := cng.NewSHA384()
208+
sha512Hash := cng.NewSHA512()
209+
210+
sum := make([]byte, sha512Hash.Size())
211+
n := int(testing.AllocsPerRun(10, func() {
212+
md4Hash.Write(msg)
213+
md5Hash.Write(msg)
214+
sha1Hash.Write(msg)
215+
sha256Hash.Write(msg)
216+
sha384Hash.Write(msg)
217+
sha512Hash.Write(msg)
218+
219+
md4Hash.Sum(sum[:0])
220+
md5Hash.Sum(sum[:0])
221+
sha1Hash.Sum(sum[:0])
222+
sha256Hash.Sum(sum[:0])
223+
sha384Hash.Sum(sum[:0])
224+
sha512Hash.Sum(sum[:0])
225+
226+
md4Hash.Reset()
227+
md5Hash.Reset()
228+
sha1Hash.Reset()
229+
sha256Hash.Reset()
230+
sha384Hash.Reset()
231+
sha512Hash.Reset()
232+
}))
233+
want := 0
234+
if n > want {
235+
t.Errorf("allocs = %d, want %d", n, want)
236+
}
237+
}
238+
184239
func BenchmarkSHA256_8Bytes(b *testing.B) {
185240
b.StopTimer()
186241
h := cng.NewSHA256()

0 commit comments

Comments
 (0)