Skip to content
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

crypto/rand: Read should not escape the input buffer #67897

Closed
dsnet opened this issue Jun 7, 2024 · 3 comments
Closed

crypto/rand: Read should not escape the input buffer #67897

dsnet opened this issue Jun 7, 2024 · 3 comments

Comments

@dsnet
Copy link
Member

dsnet commented Jun 7, 2024

Go version

go1.22

Output of go env in your module/workspace:

n/a

What did you do?

Ran this benchmark:

func Benchmark(b *testing.B) {
	b.ReportAllocs()
	for range b.N {
		sink = cryptoRandRead()
	}
}

//go:noinline
func cryptoRandRead() (out [8]byte) {
	rand.Read(out[:])
	return out
}

What did you see happen?

Benchmark-24    	 1877874	       616.4 ns/op	       8 B/op	       1 allocs/op

What did you expect to see?

Benchmark-24    	 1877874	       616.4 ns/op	       0 B/op	       0 allocs/op

The Read function is a static function. With some work to the underlying implementation (and avoid going through an io.Reader), we should be able to make it not escape the input.

Thus, you could do something like:

var arr [32]byte
rand.Read(arr[:])

and know that it doesn't allocate.

@thepudds
Copy link
Contributor

thepudds commented Jun 8, 2024

See also #66779 and https://go.dev/cl/578516.

@gabyhelp
Copy link

gabyhelp commented Jun 8, 2024

Related Issues

(Emoji vote if this was helpful or unhelpful; more detailed feedback welcome in this discussion.)

@rsc
Copy link
Contributor

rsc commented Jun 8, 2024

Duplicate of #66779.

@rsc rsc closed this as completed Jun 8, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

4 participants