diff options
Diffstat (limited to 'pkg/bits')
-rw-r--r-- | pkg/bits/bits_template.go | 8 | ||||
-rw-r--r-- | pkg/bits/uint64_test.go | 18 |
2 files changed, 26 insertions, 0 deletions
diff --git a/pkg/bits/bits_template.go b/pkg/bits/bits_template.go index 93a435b80..998645388 100644 --- a/pkg/bits/bits_template.go +++ b/pkg/bits/bits_template.go @@ -42,3 +42,11 @@ func Mask(is ...int) T { func MaskOf(i int) T { return T(1) << T(i) } + +// IsPowerOfTwo returns true if v is power of 2. +func IsPowerOfTwo(v T) bool { + if v == 0 { + return false + } + return v&(v-1) == 0 +} diff --git a/pkg/bits/uint64_test.go b/pkg/bits/uint64_test.go index 1b018d808..193d1ebcd 100644 --- a/pkg/bits/uint64_test.go +++ b/pkg/bits/uint64_test.go @@ -114,3 +114,21 @@ func TestIsOn(t *testing.T) { } } } + +func TestIsPowerOfTwo(t *testing.T) { + for _, tc := range []struct { + v uint64 + want bool + }{ + {v: 0, want: false}, + {v: 1, want: true}, + {v: 2, want: true}, + {v: 3, want: false}, + {v: 4, want: true}, + {v: 5, want: false}, + } { + if got := IsPowerOfTwo64(tc.v); got != tc.want { + t.Errorf("IsPowerOfTwo(%d) = %t, want: %t", tc.v, got, tc.want) + } + } +} |