Skip to content

Commit

Permalink
common api returns value aligned with page size
Browse files Browse the repository at this point in the history
Signed-off-by: Robin Lu <robin.lu@bytedance.com>
  • Loading branch information
lubinszARM committed Mar 1, 2024
1 parent 48165f3 commit 8dbc7d5
Show file tree
Hide file tree
Showing 2 changed files with 23 additions and 0 deletions.
8 changes: 8 additions & 0 deletions pkg/util/general/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ import (
"sort"
"strconv"
"strings"
"syscall"
"time"

"k8s.io/apimachinery/pkg/api/resource"
Expand Down Expand Up @@ -348,6 +349,13 @@ func Clamp(value, min, max float64) float64 {
return math.Max(math.Min(value, max), min)
}

// AlignToPageSize returns the value aligned with page size
func AlignToPageSize(number uint64) uint64 {
pageSize := uint64(syscall.Getpagesize())
alignedNumber := (number + pageSize - 1) &^ (pageSize - 1)
return alignedNumber
}

// FormatMemoryQuantity aligned to Gi Mi Ki
func FormatMemoryQuantity(q float64) string {
value := int64(q)
Expand Down
15 changes: 15 additions & 0 deletions pkg/util/general/common_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,10 @@ limitations under the License.
package general

import (
"syscall"
"testing"

"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"k8s.io/apimachinery/pkg/util/sets"
)
Expand Down Expand Up @@ -149,3 +151,16 @@ func TestFormatMemoryQutantity(t *testing.T) {
as.Equal("1.048576e+06[1Mi]", FormatMemoryQuantity(1<<20))
as.Equal("1.073741824e+09[1Gi]", FormatMemoryQuantity(1<<30))
}

func TestAlignToPageSize(t *testing.T) {
t.Parallel()
pageSize := uint64(syscall.Getpagesize())

// Test case 1: Number already aligned to page size
result := AlignToPageSize(pageSize * 2)
assert.Equal(t, pageSize*2, result, "Unexpected result for aligned number")

// Test case 2: Number smaller than page size
result = AlignToPageSize(pageSize - 1)
assert.Equal(t, pageSize, result, "Unexpected result for number smaller than page size")
}

0 comments on commit 8dbc7d5

Please sign in to comment.