pgregory.net/rand@v1.0.3-0.20230808192358-a0b8ce02f4da/rand_generic_test.go (about) 1 // Copyright 2022 Gregory Petrosyan <gregory.petrosyan@gmail.com> 2 // 3 // This Source Code Form is subject to the terms of the Mozilla Public 4 // License, v. 2.0. If a copy of the MPL was not distributed with this 5 // file, You can obtain one at https://mozilla.org/MPL/2.0/. 6 7 //go:build go1.18 8 9 package rand_test 10 11 import ( 12 "bytes" 13 "pgregory.net/rand" 14 "pgregory.net/rapid" 15 "testing" 16 ) 17 18 func BenchmarkShuffleSlice(b *testing.B) { 19 r := rand.New(1) 20 a := make([]int, tiny) 21 for i := 0; i < b.N; i++ { 22 rand.ShuffleSlice(r, a) 23 } 24 } 25 26 func TestShuffleSlice(t *testing.T) { 27 rapid.Check(t, func(t *rapid.T) { 28 s := rapid.Uint64().Draw(t, "s").(uint64) 29 r := rand.New(s) 30 n := rapid.IntRange(0, small).Draw(t, "n").(int) 31 buf1 := make([]byte, n) 32 _, _ = r.Read(buf1) 33 buf2 := append([]byte(nil), buf1...) 34 r.Seed(s) 35 r.Shuffle(n, func(i, j int) { 36 buf1[i], buf1[j] = buf1[j], buf1[i] 37 }) 38 r.Seed(s) 39 rand.ShuffleSlice(r, buf2) 40 if !bytes.Equal(buf1, buf2) { 41 t.Fatalf("shuffle results differ: %q vs %q", buf1, buf2) 42 } 43 }) 44 }