Skip to content

Commit

Permalink
Add test for util.NextPowerOfTwo() (open-telemetry#130)
Browse files Browse the repository at this point in the history
  • Loading branch information
rockdaboot authored Aug 23, 2024
1 parent 6df2d3c commit 9671707
Show file tree
Hide file tree
Showing 2 changed files with 37 additions and 10 deletions.
17 changes: 7 additions & 10 deletions util/util.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@
package util

import (
"math/bits"
"strconv"
"sync/atomic"
"unicode"
Expand Down Expand Up @@ -60,17 +61,13 @@ func IsValidString(s string) bool {
return true
}

// NextPowerOfTwo returns the next highest power of 2 for a given value v or v,
// if v is a power of 2.
// NextPowerOfTwo returns input value if it's a power of two,
// otherwise it returns the next power of two.
func NextPowerOfTwo(v uint32) uint32 {
v--
v |= v >> 1
v |= v >> 2
v |= v >> 4
v |= v >> 8
v |= v >> 16
v++
return v
if v == 0 {
return 1
}
return 1 << bits.Len32(v-1)
}

// AtomicUpdateMaxUint32 updates the value in store using atomic memory primitives. newValue will
Expand Down
30 changes: 30 additions & 0 deletions util/util_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
package util

import (
"testing"

"github.com/stretchr/testify/require"
)

func TestNextPowerOfTwo(t *testing.T) {
tests := []struct {
name string
input uint32
want uint32
}{
{name: "zero", input: 0, want: 1},
{name: "one", input: 1, want: 1},
{name: "two", input: 2, want: 2},
{name: "three", input: 3, want: 4},
{name: "four", input: 4, want: 4},
{name: "five", input: 5, want: 8},
{name: "six", input: 6, want: 8},
{name: "0x370", input: 0x370, want: 0x400},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
require.Equalf(t, tt.want, NextPowerOfTwo(tt.input),
"NextPowerOfTwo() = %v, want %v", tt.want, tt.want)
})
}
}

0 comments on commit 9671707

Please sign in to comment.