github.com/tunabay/go-bitarray@v1.3.1/bitarray_iterate_test.go (about) 1 // Copyright (c) 2021 Hirotsuna Mizuno. All rights reserved. 2 // Use of this source code is governed by the MIT license that can be found in 3 // the LICENSE file. 4 5 package bitarray_test 6 7 import ( 8 "errors" 9 "fmt" 10 "math/rand" 11 "testing" 12 "time" 13 14 "github.com/tunabay/go-bitarray" 15 ) 16 17 func TestBitArray_Iterate_rand(t *testing.T) { 18 const testIterations = 10000 19 rand.Seed(time.Now().UnixNano()) 20 21 for i := 0; i < testIterations; i++ { 22 var ba *bitarray.BitArray 23 switch rand.Intn(20) { 24 case 0, 1, 2, 3: 25 nBits := rand.Intn(64) 26 ba = bitarray.PseudoRand(nBits, nil) 27 case 4, 5, 6, 7: 28 nBits := 8*(1+rand.Intn(64)) - 1 + rand.Intn(3) 29 ba = bitarray.PseudoRand(nBits, nil) 30 case 8: 31 nBits := rand.Intn(1024) 32 ba = bitarray.NewZeroFilled(nBits) 33 case 9: 34 nBits := rand.Intn(1024) 35 ba = bitarray.NewOneFilled(nBits) 36 default: 37 nBits := rand.Intn(1024) 38 ba = bitarray.PseudoRand(nBits, nil) 39 } 40 lim := ba.Len() 41 if rand.Intn(20) == 0 { 42 lim = ba.Len() - rand.Intn(ba.Len()>>1+1) 43 } 44 var myErr error 45 if lim < ba.Len() && rand.Intn(5) == 0 { 46 myErr = fmt.Errorf("custom error %d", i) 47 } 48 49 baS := ba.String() 50 51 fn := func(i, b int) error { 52 t.Helper() 53 if baS[i] != '0'+byte(b) { 54 return fmt.Errorf("%d: got %d, want %c", i, b, baS[i]) 55 } 56 if lim < i { 57 if myErr == nil { 58 return bitarray.BreakIteration 59 } 60 return fmt.Errorf("test error: %d: %w", i, myErr) 61 } 62 return nil 63 } 64 if err := ba.Iterate(fn); err != nil { 65 if myErr == nil || !errors.Is(err, myErr) { 66 t.Errorf("unexpected error: %s", err) 67 t.FailNow() 68 } 69 } 70 if err := ba.ZExpand().Iterate(fn); err != nil { 71 if myErr == nil || !errors.Is(err, myErr) { 72 t.Errorf("unexpected bit (e): %s", err) 73 t.FailNow() 74 } 75 } 76 // if i < 32 { 77 // t.Logf("pass: %#b", ba) 78 // } 79 } 80 }