github.com/mvdan/u-root-coreutils@v0.0.0-20230122170626-c2eef2898555/pkg/rand/random_std.go (about) 1 // Copyright 2020 the u-root Authors. All rights reserved 2 // Use of this source code is governed by a BSD-style 3 // license that can be found in the LICENSE file. 4 5 //go:build plan9 || windows 6 // +build plan9 windows 7 8 package rand 9 10 import ( 11 "context" 12 "crypto/rand" 13 ) 14 15 var defaultContextReader = &cryptoRandReader{} 16 17 type cryptoRandReader struct{} 18 19 // ReadContext implements a cancelable read. 20 func (r *cryptoRandReader) ReadContext(ctx context.Context, b []byte) (n int, err error) { 21 ch := make(chan struct{}) 22 go func() { 23 n, err = rand.Reader.Read(b) 24 close(ch) 25 }() 26 select { 27 case <-ctx.Done(): 28 return 0, ctx.Err() 29 case <-ch: 30 return n, err 31 } 32 }