github.com/graybobo/golang.org-package-offline-cache@v0.0.0-20200626051047-6608995c132f/x/tools/container/intsets/util_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 package intsets 6 7 import ( 8 "math/rand" 9 "testing" 10 ) 11 12 func TestNLZ(t *testing.T) { 13 // Test the platform-specific edge case. 14 // NB: v must be a var (not const) so that the word() conversion is dynamic. 15 // Otherwise the compiler will report an error. 16 v := uint64(0x0000801000000000) 17 n := nlz(word(v)) 18 want := 32 // (on 32-bit) 19 if bitsPerWord == 64 { 20 want = 16 21 } 22 if n != want { 23 t.Errorf("%d-bit nlz(%d) = %d, want %d", bitsPerWord, v, n, want) 24 } 25 } 26 27 // Backdoor for testing. 28 func (s *Sparse) Check() error { return s.check() } 29 30 func dumbPopcount(x word) int { 31 var popcnt int 32 for i := uint(0); i < bitsPerWord; i++ { 33 if x&(1<<i) != 0 { 34 popcnt++ 35 } 36 } 37 return popcnt 38 } 39 40 func TestPopcount(t *testing.T) { 41 for i := 0; i < 1e5; i++ { 42 x := word(rand.Uint32()) 43 if bitsPerWord == 64 { 44 x = x | (word(rand.Uint32()) << 32) 45 } 46 want := dumbPopcount(x) 47 got := popcount(x) 48 if got != want { 49 t.Errorf("popcount(%d) = %d, want %d", x, got, want) 50 } 51 } 52 } 53 54 func BenchmarkPopcount(b *testing.B) { 55 for i := 0; i < b.N; i++ { 56 popcount(word(i)) 57 } 58 }