Skip to content

Commit

Permalink
feat: add fastrand.Read() (#90)
Browse files Browse the repository at this point in the history
Co-authored-by: liyichao <[email protected]>
  • Loading branch information
ziposcar and liyichao authored Oct 12, 2021
1 parent 2462551 commit 9968b6c
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 0 deletions.
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

0 comments on commit 9968b6c

Please sign in to comment.