Skip to content

Commit

Permalink
add more docs comments
Browse files Browse the repository at this point in the history
Change-Id: I8ff1fe961bf1619a6dde85f079e8f195d29f5c2b
  • Loading branch information
mateusz834 committed Apr 17, 2024
1 parent 1d9bc96 commit bfdb438
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 11 deletions.
11 changes: 5 additions & 6 deletions src/crypto/rand/internal/getrand/getrand.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,19 @@ package getrand

import "math"

// GetRandom populates out with cryptographically secure random data.
func GetRandom(out []byte) error {
if maxGetRandomRead == math.MaxInt {
return getRandom(out)
}

// Batch random read operations up to maxGetRandomRead.
for len(out) > 0 {
read := len(out)
if read > maxGetRandomRead {
read = maxGetRandomRead
}
if err := getRandom(out[:read]); err != nil {
readBytes := min(len(out), maxGetRandomRead)
if err := getRandom(out[:readBytes]); err != nil {
return err
}
out = out[read:]
out = out[readBytes:]
}
return nil
}
14 changes: 9 additions & 5 deletions src/crypto/rand/rand.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,15 +21,19 @@ import "io"
// - On wasip1/wasm, Reader uses random_get from wasi_snapshot_preview1.
var Reader io.Reader = randReader

// Read is a helper function that calls Reader.Read using io.ReadFull.
// Read is a helper function that reads data from the [Reader] and populates
// the entire out byte slice with cryptographically secure random data.
// It has the same behaviour as calling io.ReadFull with the [Reader].
// On return, n == len(b) if and only if err == nil.
func Read(b []byte) (n int, err error) {
for n < len(b) && err == nil {
func Read(out []byte) (n int, err error) {
// To avoid escaping the out slice, inline the io.ReadFull function.
// The following code has the same behaviour as: io.ReadFull(Reader, out).
for n < len(out) && err == nil {
var nn int
nn, err = randReader.Read(b[n:])
nn, err = randReader.Read(out[n:])
n += nn
}
if n >= len(b) {
if n >= len(out) {
err = nil
} else if n > 0 && err == io.EOF {
err = io.ErrUnexpectedEOF
Expand Down
2 changes: 2 additions & 0 deletions src/crypto/rand/rand_unix.go
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,8 @@ func (hr hideAgainFileReader) Read(p []byte) (n int, err error) {
}

func (hr hideAgainFileReader) ReadFull(p []byte) (n int, err error) {
// To avoid escaping the p slice, inline the io.ReadFull function.
// The following code has the same behaviour as: io.ReadFull(hr.f, out).
for n < len(p) && err == nil {
var nn int
nn, err = hr.Read(p[n:])
Expand Down

0 comments on commit bfdb438

Please sign in to comment.