github.com/mtsmfm/go/src@v0.0.0-20221020090648-44bdcb9f8fde/crypto/rand/rand_batched_test.go (about) 1 // Copyright 2014 The Go 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 unix 6 7 package rand 8 9 import ( 10 "bytes" 11 "encoding/binary" 12 "errors" 13 prand "math/rand" 14 "testing" 15 ) 16 17 func TestBatched(t *testing.T) { 18 fillBatched := batched(func(p []byte) error { 19 for i := range p { 20 p[i] = byte(i) 21 } 22 return nil 23 }, 5) 24 25 p := make([]byte, 13) 26 if err := fillBatched(p); err != nil { 27 t.Fatalf("batched function returned error: %s", err) 28 } 29 expected := []byte{0, 1, 2, 3, 4, 0, 1, 2, 3, 4, 0, 1, 2} 30 if !bytes.Equal(expected, p) { 31 t.Errorf("incorrect batch result: got %x, want %x", p, expected) 32 } 33 } 34 35 func TestBatchedBuffering(t *testing.T) { 36 var prandSeed [8]byte 37 Read(prandSeed[:]) 38 prand.Seed(int64(binary.LittleEndian.Uint64(prandSeed[:]))) 39 40 backingStore := make([]byte, 1<<23) 41 prand.Read(backingStore) 42 backingMarker := backingStore[:] 43 output := make([]byte, len(backingStore)) 44 outputMarker := output[:] 45 46 fillBatched := batched(func(p []byte) error { 47 n := copy(p, backingMarker) 48 backingMarker = backingMarker[n:] 49 return nil 50 }, 731) 51 52 for len(outputMarker) > 0 { 53 max := 9200 54 if max > len(outputMarker) { 55 max = len(outputMarker) 56 } 57 howMuch := prand.Intn(max + 1) 58 if err := fillBatched(outputMarker[:howMuch]); err != nil { 59 t.Fatalf("batched function returned error: %s", err) 60 } 61 outputMarker = outputMarker[howMuch:] 62 } 63 if !bytes.Equal(backingStore, output) { 64 t.Error("incorrect batch result") 65 } 66 } 67 68 func TestBatchedError(t *testing.T) { 69 b := batched(func(p []byte) error { return errors.New("failure") }, 5) 70 if b(make([]byte, 13)) == nil { 71 t.Fatal("batched function should have returned an error") 72 } 73 } 74 75 func TestBatchedEmpty(t *testing.T) { 76 b := batched(func(p []byte) error { return errors.New("failure") }, 5) 77 if b(make([]byte, 0)) != nil { 78 t.Fatal("empty slice should always return successful") 79 } 80 }