本文整理汇总了Golang中math/rand.Read函数的典型用法代码示例。如果您正苦于以下问题:Golang Read函数的具体用法?Golang Read怎么用?Golang Read使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了Read函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Golang代码示例。
示例1: actorWriteFile
func actorWriteFile(d *Directory) error {
fi, err := randomFile(d)
if err != nil {
return err
}
if fi == nil {
return nil
}
size := rand.Intn(1024) + 1
buf := make([]byte, size)
rand.Read(buf)
s, err := fi.Size()
if err != nil {
return err
}
wfd, err := fi.Open(OpenWriteOnly, true)
if err != nil {
return err
}
offset := rand.Int63n(s)
n, err := wfd.WriteAt(buf, offset)
if err != nil {
return err
}
if n != size {
return fmt.Errorf("didnt write enough")
}
return wfd.Close()
}
示例2: mustWriteRandFile
func mustWriteRandFile(path string, size int, seed int64) *os.File {
p := make([]byte, size)
rand.Seed(seed)
_, err := rand.Read(p)
if err != nil {
panic(err)
}
f, err := os.Create(path)
if err != nil {
panic(err)
}
_, err = f.Write(p)
if err != nil {
panic(err)
}
_, err = f.Seek(0, 0)
if err != nil {
panic(err)
}
return f
}
示例3: ReadReader
// Read n bytes from a pipe and pass bytes read to a callback. If an error occurs
// error is passed to the callback. The callback signature is:
// Func(err error, bs []byte, done bool).
func ReadReader(reader io.Reader, nBytes int, cb func(err error, bs []byte, done bool) bool) {
r := bufio.NewReader(reader)
buf := make([]byte, 0, nBytes)
for {
n, err := r.Read(buf[:cap(buf)])
buf = buf[:n]
if n == 0 {
if err == nil {
continue
}
if err == io.EOF {
break
}
if cb(err, buf, false) == false {
return
}
}
// process buf
if err != nil && err != io.EOF {
if cb(err, buf, false) == false {
return
}
}
if cb(err, buf, false) == false {
return
}
}
cb(nil, buf, true)
}
示例4: allocateUniqueUid
// allocateUniqueUid returns an integer in range:
// [minIdx, maxIdx] derived based on numInstances and instanceIdx.
// which hasn't already been allocated to other xids. It does this by
// taking the fingerprint of the xid appended with zero or more spaces
// until the obtained integer is unique.
func allocateUniqueUid(instanceIdx uint64, numInstances uint64) uint64 {
mod := math.MaxUint64 / numInstances
minIdx := instanceIdx * mod
buf := make([]byte, 128)
for {
_, err := rand.Read(buf)
x.Checkf(err, "rand.Read shouldn't throw an error")
uidb := farm.Fingerprint64(buf) // Generate from hash.
uid := (uidb % mod) + minIdx
if uid == math.MaxUint64 || !lmgr.isNew(uid) {
continue
}
// Check if this uid has already been allocated.
key := x.DataKey("_uid_", uid)
pl, decr := posting.GetOrCreate(key)
defer decr()
if pl.Length(0) == 0 {
return uid
}
}
log.Fatalf("This shouldn't be reached.")
return 0
}
示例5: newRandomID
func newRandomID() *dht.ID {
id := new(dht.ID)
n, err := rand.Read(id[:])
if err != nil || n != dht.IDLen {
return dht.ZeroID
}
return id
}
示例6: Challenge13
func Challenge13() {
fmt.Println("\nSet 2 challenge 13\n==================")
profile := ProfileFor("[email protected]")
key := make([]byte, 16)
rand.Read(key)
EncryptAes128Ecb([]byte(profile), key)
}
示例7: makeTestData
func makeTestData(size int) []byte {
out := make([]byte, size)
_, err := rand.Read(out)
if err != nil {
panic(err)
}
return out
}
示例8: SecureRandomBytes
// SecureRandomBytes returns the requested number of bytes using crypto/rand
func SecureRandomBytes(length int) []byte {
var randomBytes = make([]byte, length)
_, err := rand.Read(randomBytes)
if err != nil {
log.Fatal("Unable to generate random bytes")
}
return randomBytes
}
示例9: rnd
func rnd(t *testing.T, n int) []byte {
b := make([]byte, n)
i, err := rand.Read(b)
if err != nil || i != n {
t.Fatal("rand failed")
}
return b
}
示例10: Sum
func (p *Encryptor) Sum(plain string, size int) (string, error) {
salt := make([]byte, size)
_, err := rand.Read(salt)
if err != nil {
return "", err
}
return p.sum(plain, salt), nil
}
示例11: generateString
// https://www.ietf.org/rfc/rfc4648.txt - use "Base 64 Encoding with URL and Filename Safe Alphabet"
// No need to worry about '+' and '/' according to the above RFC
func generateString(size int) string {
rb := make([]byte, size)
_, err := rand.Read(rb)
if err != nil {
fmt.Println(err)
}
return base64.URLEncoding.EncodeToString(rb)
}
示例12: TestCodec_ReceiveLimited
func TestCodec_ReceiveLimited(t *testing.T) {
const limit = 2048
var payloads [][]byte
for _, size := range []int{
1024,
2048,
4096, // receive of this message would be interrupted due to limit
2048, // this one is to make sure next receive recovers discarding leftovers
} {
b := make([]byte, size)
rand.Read(b)
payloads = append(payloads, b)
}
handlerDone := make(chan struct{})
limitedHandler := func(ws *Conn) {
defer close(handlerDone)
ws.MaxPayloadBytes = limit
defer ws.Close()
for i, p := range payloads {
t.Logf("payload #%d (size %d, exceeds limit: %v)", i, len(p), len(p) > limit)
var recv []byte
err := Message.Receive(ws, &recv)
switch err {
case nil:
case ErrFrameTooLarge:
if len(p) <= limit {
t.Fatalf("unexpected frame size limit: expected %d bytes of payload having limit at %d", len(p), limit)
}
continue
default:
t.Fatalf("unexpected error: %v (want either nil or ErrFrameTooLarge)", err)
}
if len(recv) > limit {
t.Fatalf("received %d bytes of payload having limit at %d", len(recv), limit)
}
if !bytes.Equal(p, recv) {
t.Fatalf("received payload differs:\ngot:\t%v\nwant:\t%v", recv, p)
}
}
}
server := httptest.NewServer(Handler(limitedHandler))
defer server.CloseClientConnections()
defer server.Close()
addr := server.Listener.Addr().String()
ws, err := Dial("ws://"+addr+"/", "", "http://localhost/")
if err != nil {
t.Fatal(err)
}
defer ws.Close()
for i, p := range payloads {
if err := Message.Send(ws, p); err != nil {
t.Fatalf("payload #%d (size %d): %v", i, len(p), err)
}
}
<-handlerDone
}
示例13: init
func init() {
testContent = make([]byte, maxTestContent)
n, err := rand.Read(testContent)
if err != nil {
panic(err)
}
if n != len(testContent) {
panic(errors.New("failed to generate random content"))
}
}
示例14: TestMoveWithMultipartCopy
func TestMoveWithMultipartCopy(t *testing.T) {
if skipS3() != "" {
t.Skip(skipS3())
}
rootDir, err := ioutil.TempDir("", "driver-")
if err != nil {
t.Fatalf("unexpected error creating temporary directory: %v", err)
}
defer os.Remove(rootDir)
d, err := s3DriverConstructor(rootDir, s3.StorageClassStandard)
if err != nil {
t.Fatalf("unexpected error creating driver: %v", err)
}
ctx := context.Background()
sourcePath := "/source"
destPath := "/dest"
defer d.Delete(ctx, sourcePath)
defer d.Delete(ctx, destPath)
// An object larger than d's MultipartCopyThresholdSize will cause d.Move() to perform a multipart copy.
multipartCopyThresholdSize := d.baseEmbed.Base.StorageDriver.(*driver).MultipartCopyThresholdSize
contents := make([]byte, 2*multipartCopyThresholdSize)
rand.Read(contents)
err = d.PutContent(ctx, sourcePath, contents)
if err != nil {
t.Fatalf("unexpected error creating content: %v", err)
}
err = d.Move(ctx, sourcePath, destPath)
if err != nil {
t.Fatalf("unexpected error moving file: %v", err)
}
received, err := d.GetContent(ctx, destPath)
if err != nil {
t.Fatalf("unexpected error getting content: %v", err)
}
if !bytes.Equal(contents, received) {
t.Fatal("content differs")
}
_, err = d.GetContent(ctx, sourcePath)
switch err.(type) {
case storagedriver.PathNotFoundError:
default:
t.Fatalf("unexpected error getting content: %v", err)
}
}
示例15: getRandomUint64Set
func getRandomUint64Set(n int) []uint64 {
seed := int64(42)
p("seed is %v", seed)
rand.Seed(seed)
var buf [8]byte
var o []uint64
for i := 0; i < n; i++ {
rand.Read(buf[:])
o = append(o, binary.LittleEndian.Uint64(buf[:]))
}
return o
}