| 1 |
package mem |
| 2 |
|
| 3 |
import ( |
| 4 |
"bytes" |
| 5 |
"encoding/hex" |
| 6 |
"fmt" |
| 7 |
"io" |
| 8 |
"math/rand" |
| 9 |
"testing" |
| 10 |
) |
| 11 |
|
| 12 |
var ( |
| 13 |
testSizes = [...]int{ |
| 14 |
0, 1, 2, 3, 4, 6, 8, 10, 31, 32, 33, 64, 100, 1024, 4096, |
| 15 |
} |
| 16 |
|
| 17 |
benchmarkSizes = [...]int{ |
| 18 |
7, 10, 31, 32, 100, 1024, 4096, |
| 19 |
} |
| 20 |
) |
| 21 |
|
| 22 |
func testCopy(t *testing.T, test, init func(dst, src []byte) int) { |
| 23 |
for _, N := range testSizes { |
| 24 |
t.Run(fmt.Sprintf("N=%d", N), func(t *testing.T) { |
| 25 |
src := make([]byte, N) |
| 26 |
dst := make([]byte, N) |
| 27 |
exp := make([]byte, N) |
| 28 |
|
| 29 |
prng := rand.New(rand.NewSource(0)) |
| 30 |
io.ReadFull(prng, src) |
| 31 |
io.ReadFull(prng, dst) |
| 32 |
|
| 33 |
copy(exp, dst) |
| 34 |
init(exp, src) |
| 35 |
|
| 36 |
n := test(dst, src) |
| 37 |
if n != N { |
| 38 |
t.Errorf("copying did not apply to enough bytes: %d != %d", n, N) |
| 39 |
} |
| 40 |
|
| 41 |
if !bytes.Equal(dst, exp) { |
| 42 |
t.Error("copying produced the wrong output") |
| 43 |
t.Logf("expected:\n%s", hex.Dump(exp)) |
| 44 |
t.Logf("found: \n%s", hex.Dump(dst)) |
| 45 |
t.Logf("source: \n%s", hex.Dump(src)) |
| 46 |
} |
| 47 |
}) |
| 48 |
} |
| 49 |
} |
| 50 |
|
| 51 |
func benchmarkCopy(b *testing.B, test func(dst, src []byte) int) { |
| 52 |
for _, N := range benchmarkSizes { |
| 53 |
b.Run(fmt.Sprintf("N=%d", N), func(b *testing.B) { |
| 54 |
dst := make([]byte, N) |
| 55 |
src := make([]byte, N) |
| 56 |
io.ReadFull(rand.New(rand.NewSource(0)), src) |
| 57 |
b.SetBytes(int64(N)) |
| 58 |
b.ResetTimer() |
| 59 |
|
| 60 |
for i := 0; i < b.N; i++ { |
| 61 |
test(dst, src) |
| 62 |
} |
| 63 |
}) |
| 64 |
} |
| 65 |
} |