github.com/spotmaxtech/k8s-apimachinery-v0260@v0.0.1/pkg/api/resource/scale_int_test.go (about)

     1  /*
     2  Copyright 2015 The Kubernetes Authors.
     3  
     4  Licensed under the Apache License, Version 2.0 (the "License");
     5  you may not use this file except in compliance with the License.
     6  You may obtain a copy of the License at
     7  
     8      http://www.apache.org/licenses/LICENSE-2.0
     9  
    10  Unless required by applicable law or agreed to in writing, software
    11  distributed under the License is distributed on an "AS IS" BASIS,
    12  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
    13  See the License for the specific language governing permissions and
    14  limitations under the License.
    15  */
    16  
    17  package resource
    18  
    19  import (
    20  	"math"
    21  	"math/big"
    22  	"testing"
    23  )
    24  
    25  func TestScaledValueInternal(t *testing.T) {
    26  	tests := []struct {
    27  		unscaled *big.Int
    28  		scale    int
    29  		newScale int
    30  
    31  		want int64
    32  	}{
    33  		// remain scale
    34  		{big.NewInt(1000), 0, 0, 1000},
    35  
    36  		// scale down
    37  		{big.NewInt(1000), 0, -3, 1},
    38  		{big.NewInt(1000), 3, 0, 1},
    39  		{big.NewInt(0), 3, 0, 0},
    40  
    41  		// always round up
    42  		{big.NewInt(999), 3, 0, 1},
    43  		{big.NewInt(500), 3, 0, 1},
    44  		{big.NewInt(499), 3, 0, 1},
    45  		{big.NewInt(1), 3, 0, 1},
    46  		// large scaled value does not lose precision
    47  		{big.NewInt(0).Sub(maxInt64, bigOne), 1, 0, (math.MaxInt64-1)/10 + 1},
    48  		// large intermediate result.
    49  		{big.NewInt(1).Exp(big.NewInt(10), big.NewInt(100), nil), 100, 0, 1},
    50  
    51  		// scale up
    52  		{big.NewInt(0), 0, 3, 0},
    53  		{big.NewInt(1), 0, 3, 1000},
    54  		{big.NewInt(1), -3, 0, 1000},
    55  		{big.NewInt(1000), -3, 2, 100000000},
    56  		{big.NewInt(0).Div(big.NewInt(math.MaxInt64), bigThousand), 0, 3,
    57  			(math.MaxInt64 / 1000) * 1000},
    58  	}
    59  
    60  	for i, tt := range tests {
    61  		old := (&big.Int{}).Set(tt.unscaled)
    62  		got := scaledValue(tt.unscaled, tt.scale, tt.newScale)
    63  		if got != tt.want {
    64  			t.Errorf("#%d: got = %v, want %v", i, got, tt.want)
    65  		}
    66  		if tt.unscaled.Cmp(old) != 0 {
    67  			t.Errorf("#%d: unscaled = %v, want %v", i, tt.unscaled, old)
    68  		}
    69  	}
    70  }
    71  
    72  func BenchmarkScaledValueSmall(b *testing.B) {
    73  	s := big.NewInt(1000)
    74  	for i := 0; i < b.N; i++ {
    75  		scaledValue(s, 3, 0)
    76  	}
    77  }
    78  
    79  func BenchmarkScaledValueLarge(b *testing.B) {
    80  	s := big.NewInt(math.MaxInt64)
    81  	s.Mul(s, big.NewInt(1000))
    82  	for i := 0; i < b.N; i++ {
    83  		scaledValue(s, 10, 0)
    84  	}
    85  }