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

feat(lang/fastrand): add Read([]byte) function #90

Merged
merged 1 commit into from
Oct 12, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions lang/fastrand/fastrand.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,8 @@
package fastrand

import (
"unsafe"

"github.com/bytedance/gopkg/internal/runtimex"
)

Expand Down Expand Up @@ -121,3 +123,28 @@ func Uint32n(n uint32) uint32 {
func Uint64n(n uint64) uint64 {
return Uint64() % n
}

// Read generates len(p) random bytes and writes them into p.
// It always returns len(p) and a nil error. And it is safe
// for concurrent use.
func Read(p []byte) (n int, err error) {
l := len(p)

if l >= 4 {
i := 0
uint32p := *(*[]uint32)(unsafe.Pointer(&p))
for ; l >= 4; l -= 4 {
uint32p[i] = Uint32()
i++
}
}

if l > 0 {
r := Uint32()
for ; l > 0; l-- {
p[len(p)-l] = byte(r >> (l * 8))
}
}

return len(p), nil
}
3 changes: 3 additions & 0 deletions lang/fastrand/fastrand_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,9 @@ import (

func TestAll(t *testing.T) {
_ = Uint32()

bytes := make([]byte, 1000)
_, _ = Read(bytes)
}

func BenchmarkSingleCore(b *testing.B) {
Expand Down