summaryrefslogtreecommitdiff
path: root/vendor/k8s.io/apimachinery/pkg/api/resource/quantity.go
diff options
context:
space:
mode:
Diffstat (limited to 'vendor/k8s.io/apimachinery/pkg/api/resource/quantity.go')
-rw-r--r--vendor/k8s.io/apimachinery/pkg/api/resource/quantity.go36
1 files changed, 35 insertions, 1 deletions
diff --git a/vendor/k8s.io/apimachinery/pkg/api/resource/quantity.go b/vendor/k8s.io/apimachinery/pkg/api/resource/quantity.go
index d95e03aa9..8d718945d 100644
--- a/vendor/k8s.io/apimachinery/pkg/api/resource/quantity.go
+++ b/vendor/k8s.io/apimachinery/pkg/api/resource/quantity.go
@@ -20,6 +20,7 @@ import (
"bytes"
"errors"
"fmt"
+ "math"
"math/big"
"strconv"
"strings"
@@ -120,7 +121,7 @@ const (
)
// MustParse turns the given string into a quantity or panics; for tests
-// or others cases where you know the string is valid.
+// or other cases where you know the string is valid.
func MustParse(str string) Quantity {
q, err := ParseQuantity(str)
if err != nil {
@@ -442,6 +443,36 @@ func (q *Quantity) CanonicalizeBytes(out []byte) (result, suffix []byte) {
}
}
+// AsApproximateFloat64 returns a float64 representation of the quantity which may
+// lose precision. If the value of the quantity is outside the range of a float64
+// +Inf/-Inf will be returned.
+func (q *Quantity) AsApproximateFloat64() float64 {
+ var base float64
+ var exponent int
+ if q.d.Dec != nil {
+ base, _ = big.NewFloat(0).SetInt(q.d.Dec.UnscaledBig()).Float64()
+ exponent = int(-q.d.Dec.Scale())
+ } else {
+ base = float64(q.i.value)
+ exponent = int(q.i.scale)
+ }
+ if exponent == 0 {
+ return base
+ }
+
+ // multiply by the appropriate exponential scale
+ switch q.Format {
+ case DecimalExponent, DecimalSI:
+ return base * math.Pow10(exponent)
+ default:
+ // fast path for exponents that can fit in 64 bits
+ if exponent > 0 && exponent < 7 {
+ return base * float64(int64(1)<<(exponent*10))
+ }
+ return base * math.Pow(2, float64(exponent*10))
+ }
+}
+
// AsInt64 returns a representation of the current value as an int64 if a fast conversion
// is possible. If false is returned, callers must use the inf.Dec form of this quantity.
func (q *Quantity) AsInt64() (int64, bool) {
@@ -598,6 +629,9 @@ const int64QuantityExpectedBytes = 18
// String is an expensive operation and caching this result significantly reduces the cost of
// normal parse / marshal operations on Quantity.
func (q *Quantity) String() string {
+ if q == nil {
+ return "<nil>"
+ }
if len(q.s) == 0 {
result := make([]byte, 0, int64QuantityExpectedBytes)
number, suffix := q.CanonicalizeBytes(result)