resource

package
v0.32.0-rc.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 5, 2024 License: Apache-2.0 Imports: 13 Imported by: 14,084

Documentation

Index

Examples

Constants

View Source
const (
	DecimalExponent = Format("DecimalExponent") // e.g., 12e6
	BinarySI        = Format("BinarySI")        // e.g., 12Mi (12 * 2^20)
	DecimalSI       = Format("DecimalSI")       // e.g., 12M  (12 * 10^6)
)

Variables

View Source
var (
	// Errors that could happen while parsing a string.
	ErrFormatWrong = errors.New("quantities must match the regular expression '" + splitREString + "'")
	ErrNumeric     = errors.New("unable to parse numeric part of quantity")
	ErrSuffix      = errors.New("unable to parse quantity's suffix")
)
View Source
var (
	ErrInvalidLengthGenerated = fmt.Errorf("proto: negative length found during unmarshaling")
	ErrIntOverflowGenerated   = fmt.Errorf("proto: integer overflow")
)
View Source
var (

	// The maximum value we can represent milli-units for.
	// Compare with the return value of Quantity.Value() to
	// see if it's safe to use Quantity.MilliValue().
	MaxMilliValue = int64(((1 << 63) - 1) / 1000)
)
View Source
var (
	Zero = int64Amount{}
)

Functions

This section is empty.

Types

type CanonicalValue

type CanonicalValue interface {
	// AsCanonicalBytes returns a byte array representing the string representation
	// of the value mantissa and an int32 representing its exponent in base-10. Callers may
	// pass a byte slice to the method to avoid allocations.
	AsCanonicalBytes(out []byte) ([]byte, int32)
	// AsCanonicalBase1024Bytes returns a byte array representing the string representation
	// of the value mantissa and an int32 representing its exponent in base-1024. Callers
	// may pass a byte slice to the method to avoid allocations.
	AsCanonicalBase1024Bytes(out []byte) ([]byte, int32)
}

CanonicalValue allows a quantity amount to be converted to a string.

type Format

type Format string

Format lists the three possible formattings of a quantity.

Example
package main

import (
	"fmt"

	"k8s.io/apimachinery/pkg/api/resource"
)

func main() {
	memorySize := resource.NewQuantity(5*1024*1024*1024, resource.BinarySI)
	fmt.Printf("memorySize = %v\n", memorySize)

	diskSize := resource.NewQuantity(5*1000*1000*1000, resource.DecimalSI)
	fmt.Printf("diskSize = %v\n", diskSize)

	cores := resource.NewMilliQuantity(5300, resource.DecimalSI)
	fmt.Printf("cores = %v\n", cores)

}
Output:

memorySize = 5Gi
diskSize = 5G
cores = 5300m

type Quantity

type Quantity struct {

	// Change Format at will. See the comment for Canonicalize for
	// more details.
	Format
	// contains filtered or unexported fields
}

Quantity is a fixed-point representation of a number. It provides convenient marshaling/unmarshaling in JSON and YAML, in addition to String() and AsInt64() accessors.

The serialization format is:

``` <quantity> ::= <signedNumber><suffix>

(Note that <suffix> may be empty, from the "" case in <decimalSI>.)

<digit> ::= 0 | 1 | ... | 9 <digits> ::= <digit> | <digit><digits> <number> ::= <digits> | <digits>.<digits> | <digits>. | .<digits> <sign> ::= "+" | "-" <signedNumber> ::= <number> | <sign><number> <suffix> ::= <binarySI> | <decimalExponent> | <decimalSI> <binarySI> ::= Ki | Mi | Gi | Ti | Pi | Ei

(International System of units; See: http://physics.nist.gov/cuu/Units/binary.html)

<decimalSI> ::= m | "" | k | M | G | T | P | E

(Note that 1024 = 1Ki but 1000 = 1k; I didn't choose the capitalization.)

<decimalExponent> ::= "e" <signedNumber> | "E" <signedNumber> ```

No matter which of the three exponent forms is used, no quantity may represent a number greater than 2^63-1 in magnitude, nor may it have more than 3 decimal places. Numbers larger or more precise will be capped or rounded up. (E.g.: 0.1m will rounded up to 1m.) This may be extended in the future if we require larger or smaller quantities.

When a Quantity is parsed from a string, it will remember the type of suffix it had, and will use the same type again when it is serialized.

Before serializing, Quantity will be put in "canonical form". This means that Exponent/suffix will be adjusted up or down (with a corresponding increase or decrease in Mantissa) such that:

- No precision is lost - No fractional digits will be emitted - The exponent (or suffix) is as large as possible.

The sign will be omitted unless the number is negative.

Examples:

- 1.5 will be serialized as "1500m" - 1.5Gi will be serialized as "1536Mi"

Note that the quantity will NEVER be internally represented by a floating point number. That is the whole point of this exercise.

Non-canonical values will still parse as long as they are well formed, but will be re-emitted in their canonical form. (So always use canonical form, or don't diff.)

This format is intended to make it difficult to use these numbers without writing some sort of special handling code in the hopes that that will cause implementors to also use a fixed point implementation.

+protobuf=true +protobuf.embed=string +protobuf.options.marshal=false +protobuf.options.(gogoproto.goproto_stringer)=false +k8s:deepcopy-gen=true +k8s:openapi-gen=true

func MustParse

func MustParse(str string) Quantity

MustParse turns the given string into a quantity or panics; for tests or other cases where you know the string is valid.

Example
package main

import (
	"fmt"

	"k8s.io/apimachinery/pkg/api/resource"
)

func main() {
	memorySize := resource.MustParse("5Gi")
	fmt.Printf("memorySize = %v (%v)\n", memorySize.Value(), memorySize.Format)

	diskSize := resource.MustParse("5G")
	fmt.Printf("diskSize = %v (%v)\n", diskSize.Value(), diskSize.Format)

	cores := resource.MustParse("5300m")
	fmt.Printf("milliCores = %v (%v)\n", cores.MilliValue(), cores.Format)

	cores2 := resource.MustParse("5.4")
	fmt.Printf("milliCores = %v (%v)\n", cores2.MilliValue(), cores2.Format)

}
Output:

memorySize = 5368709120 (BinarySI)
diskSize = 5000000000 (DecimalSI)
milliCores = 5300 (DecimalSI)
milliCores = 5400 (DecimalSI)

func NewDecimalQuantity added in v0.22.0

func NewDecimalQuantity(b inf.Dec, format Format) *Quantity

NewDecimalQuantity returns a new Quantity representing the given value in the given format.

func NewMilliQuantity

func NewMilliQuantity(value int64, format Format) *Quantity

NewMilliQuantity returns a new Quantity representing the given value * 1/1000 in the given format. Note that BinarySI formatting will round fractional values, and will be changed to DecimalSI for values x where (-1 < x < 1) && (x != 0).

func NewQuantity

func NewQuantity(value int64, format Format) *Quantity

NewQuantity returns a new Quantity representing the given value in the given format.

func NewScaledQuantity

func NewScaledQuantity(value int64, scale Scale) *Quantity

NewScaledQuantity returns a new Quantity representing the given value * 10^scale in DecimalSI format.

func ParseQuantity

func ParseQuantity(str string) (Quantity, error)

ParseQuantity turns str into a Quantity, or returns an error.

func (*Quantity) Add

func (q *Quantity) Add(y Quantity)

Add adds the provide y quantity to the current value. If the current value is zero, the format of the quantity will be updated to the format of y.

func (*Quantity) AsApproximateFloat64 added in v0.20.0

func (q *Quantity) AsApproximateFloat64() float64

AsApproximateFloat64 returns a float64 representation of the quantity which may lose precision. If precision matter more than performance, see AsFloat64Slow. If the value of the quantity is outside the range of a float64 +Inf/-Inf will be returned.

func (*Quantity) AsCanonicalBytes

func (q *Quantity) AsCanonicalBytes(out []byte) (result []byte, exponent int32)

AsCanonicalBytes returns the canonical byte representation of this quantity as a mantissa and base 10 exponent. The out byte slice may be passed to the method to avoid an extra allocation.

func (*Quantity) AsDec

func (q *Quantity) AsDec() *inf.Dec

AsDec returns the quantity as represented by a scaled inf.Dec.

func (*Quantity) AsFloat64Slow added in v0.32.0

func (q *Quantity) AsFloat64Slow() float64

AsFloat64Slow returns a float64 representation of the quantity. This is more precise than AsApproximateFloat64 but significantly slower. If the value of the quantity is outside the range of a float64 +Inf/-Inf will be returned.

func (*Quantity) AsInt64

func (q *Quantity) AsInt64() (int64, bool)

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 (*Quantity) AsScale

func (q *Quantity) AsScale(scale Scale) (CanonicalValue, bool)

AsScale returns the current value, rounded up to the provided scale, and returns false if the scale resulted in a loss of precision.

func (*Quantity) CanonicalizeBytes

func (q *Quantity) CanonicalizeBytes(out []byte) (result, suffix []byte)

CanonicalizeBytes returns the canonical form of q and its suffix (see comment on Quantity).

Note about BinarySI:

  • If q.Format is set to BinarySI and q.Amount represents a non-zero value between -1 and +1, it will be emitted as if q.Format were DecimalSI.
  • Otherwise, if q.Format is set to BinarySI, fractional parts of q.Amount will be rounded up. (1.1i becomes 2i.)

func (*Quantity) Cmp

func (q *Quantity) Cmp(y Quantity) int

Cmp returns 0 if the quantity is equal to y, -1 if the quantity is less than y, or 1 if the quantity is greater than y.

func (*Quantity) CmpInt64

func (q *Quantity) CmpInt64(y int64) int

CmpInt64 returns 0 if the quantity is equal to y, -1 if the quantity is less than y, or 1 if the quantity is greater than y.

func (Quantity) DeepCopy

func (q Quantity) DeepCopy() Quantity

DeepCopy returns a deep-copy of the Quantity value. Note that the method receiver is a value, so we can mutate it in-place and return it.

func (*Quantity) DeepCopyInto

func (in *Quantity) DeepCopyInto(out *Quantity)

DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.

func (*Quantity) Descriptor

func (*Quantity) Descriptor() ([]byte, []int)

func (Quantity) Equal

func (q Quantity) Equal(v Quantity) bool

Equal checks equality of two Quantities. This is useful for testing with cmp.Equal.

func (*Quantity) IsZero

func (q *Quantity) IsZero() bool

IsZero returns true if the quantity is equal to zero.

func (*Quantity) Marshal

func (m *Quantity) Marshal() (data []byte, err error)

func (Quantity) MarshalCBOR added in v0.31.0

func (q Quantity) MarshalCBOR() ([]byte, error)

func (Quantity) MarshalJSON

func (q Quantity) MarshalJSON() ([]byte, error)

MarshalJSON implements the json.Marshaller interface.

func (*Quantity) MarshalTo

func (m *Quantity) MarshalTo(data []byte) (int, error)

MarshalTo is a customized version of the generated Protobuf unmarshaler for a struct with a single string field.

func (*Quantity) MarshalToSizedBuffer added in v0.16.4

func (m *Quantity) MarshalToSizedBuffer(data []byte) (int, error)

MarshalToSizedBuffer is a customized version of the generated Protobuf unmarshaler for a struct with a single string field.

func (*Quantity) MilliValue

func (q *Quantity) MilliValue() int64

MilliValue returns the value of ceil(q * 1000); this could overflow an int64; if that's a concern, call Value() first to verify the number is small enough.

func (*Quantity) Mul added in v0.29.0

func (q *Quantity) Mul(y int64) bool

Mul multiplies the provided y to the current value. It will return false if the result is inexact. Otherwise, it will return true.

func (*Quantity) Neg

func (q *Quantity) Neg()

Neg sets quantity to be the negative value of itself.

func (Quantity) OpenAPISchemaFormat

func (_ Quantity) OpenAPISchemaFormat() string

OpenAPISchemaFormat is used by the kube-openapi generator when constructing the OpenAPI spec of this type.

func (Quantity) OpenAPISchemaType

func (_ Quantity) OpenAPISchemaType() []string

OpenAPISchemaType is used by the kube-openapi generator when constructing the OpenAPI spec of this type.

See: https://github.com/kubernetes/kube-openapi/tree/master/pkg/generators

func (Quantity) OpenAPIV3OneOfTypes added in v0.24.0

func (Quantity) OpenAPIV3OneOfTypes() []string

OpenAPIV3OneOfTypes is used by the kube-openapi generator when constructing the OpenAPI v3 spec of this type.

func (*Quantity) ProtoMessage

func (*Quantity) ProtoMessage()

func (*Quantity) Reset

func (m *Quantity) Reset()

func (*Quantity) RoundUp

func (q *Quantity) RoundUp(scale Scale) bool

RoundUp updates the quantity to the provided scale, ensuring that the value is at least 1. False is returned if the rounding operation resulted in a loss of precision. Negative numbers are rounded away from zero (-9 scale 1 rounds to -10).

func (*Quantity) ScaledValue

func (q *Quantity) ScaledValue(scale Scale) int64

ScaledValue returns the value of ceil(q / 10^scale). For example, NewQuantity(1, DecimalSI).ScaledValue(Milli) returns 1000. This could overflow an int64. To detect overflow, call Value() first and verify the expected magnitude.

func (*Quantity) Set

func (q *Quantity) Set(value int64)

Set sets q's value to be value.

func (*Quantity) SetMilli

func (q *Quantity) SetMilli(value int64)

SetMilli sets q's value to be value * 1/1000.

func (*Quantity) SetScaled

func (q *Quantity) SetScaled(value int64, scale Scale)

SetScaled sets q's value to be value * 10^scale

func (*Quantity) Sign

func (q *Quantity) Sign() int

Sign returns 0 if the quantity is zero, -1 if the quantity is less than zero, or 1 if the quantity is greater than zero.

func (*Quantity) Size

func (m *Quantity) Size() (n int)

func (*Quantity) String

func (q *Quantity) String() string

String formats the Quantity as a string, caching the result if not calculated. String is an expensive operation and caching this result significantly reduces the cost of normal parse / marshal operations on Quantity.

func (*Quantity) Sub

func (q *Quantity) Sub(y Quantity)

Sub subtracts the provided quantity from the current value in place. If the current value is zero, the format of the quantity will be updated to the format of y.

func (*Quantity) ToDec

func (q *Quantity) ToDec() *Quantity

ToDec promotes the quantity in place to use an inf.Dec representation and returns itself.

func (Quantity) ToUnstructured added in v0.18.0

func (q Quantity) ToUnstructured() interface{}

ToUnstructured implements the value.UnstructuredConverter interface.

func (*Quantity) Unmarshal

func (m *Quantity) Unmarshal(data []byte) error

Unmarshal is a customized version of the generated Protobuf unmarshaler for a struct with a single string field.

func (*Quantity) UnmarshalCBOR added in v0.31.0

func (q *Quantity) UnmarshalCBOR(value []byte) error

func (*Quantity) UnmarshalJSON

func (q *Quantity) UnmarshalJSON(value []byte) error

UnmarshalJSON implements the json.Unmarshaller interface. TODO: Remove support for leading/trailing whitespace

func (*Quantity) Value

func (q *Quantity) Value() int64

Value returns the unscaled value of q rounded up to the nearest integer away from 0.

func (*Quantity) XXX_DiscardUnknown added in v0.16.4

func (m *Quantity) XXX_DiscardUnknown()

func (*Quantity) XXX_Marshal added in v0.16.4

func (m *Quantity) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*Quantity) XXX_Merge added in v0.16.4

func (m *Quantity) XXX_Merge(src proto.Message)

func (*Quantity) XXX_Size added in v0.16.4

func (m *Quantity) XXX_Size() int

func (*Quantity) XXX_Unmarshal added in v0.16.4

func (m *Quantity) XXX_Unmarshal(b []byte) error

type QuantityValue added in v0.23.0

type QuantityValue struct {
	Quantity
}

QuantityValue makes it possible to use a Quantity as value for a command line parameter.

+protobuf=true +protobuf.embed=string +protobuf.options.marshal=false +protobuf.options.(gogoproto.goproto_stringer)=false +k8s:deepcopy-gen=true

Example
q := QuantityValue{
	Quantity: MustParse("1Mi"),
}
fs := pflag.FlagSet{}
fs.SetOutput(os.Stdout)
fs.Var(&q, "mem", "sets amount of memory")
fs.PrintDefaults()
Output:

--mem quantity   sets amount of memory (default 1Mi)

func (*QuantityValue) DeepCopy added in v0.23.0

func (in *QuantityValue) DeepCopy() *QuantityValue

DeepCopy is an autogenerated deepcopy function, copying the receiver, creating a new QuantityValue.

func (*QuantityValue) DeepCopyInto added in v0.23.0

func (in *QuantityValue) DeepCopyInto(out *QuantityValue)

DeepCopyInto is an autogenerated deepcopy function, copying the receiver, writing into out. in must be non-nil.

func (*QuantityValue) Descriptor added in v0.23.0

func (*QuantityValue) Descriptor() ([]byte, []int)

func (*QuantityValue) ProtoMessage added in v0.23.0

func (*QuantityValue) ProtoMessage()

func (*QuantityValue) Reset added in v0.23.0

func (m *QuantityValue) Reset()

func (*QuantityValue) Set added in v0.23.0

func (q *QuantityValue) Set(s string) error

Set implements pflag.Value.Set and Go flag.Value.Set.

func (QuantityValue) Type added in v0.23.0

func (q QuantityValue) Type() string

Type implements pflag.Value.Type.

func (*QuantityValue) XXX_DiscardUnknown added in v0.23.0

func (m *QuantityValue) XXX_DiscardUnknown()

func (*QuantityValue) XXX_Marshal added in v0.23.0

func (m *QuantityValue) XXX_Marshal(b []byte, deterministic bool) ([]byte, error)

func (*QuantityValue) XXX_Merge added in v0.23.0

func (m *QuantityValue) XXX_Merge(src proto.Message)

func (*QuantityValue) XXX_Size added in v0.23.0

func (m *QuantityValue) XXX_Size() int

func (*QuantityValue) XXX_Unmarshal added in v0.23.0

func (m *QuantityValue) XXX_Unmarshal(b []byte) error

type Scale

type Scale int32

Scale is used for getting and setting the base-10 scaled value. Base-2 scales are omitted for mathematical simplicity. See Quantity.ScaledValue for more details.

const (
	Nano  Scale = -9
	Micro Scale = -6
	Milli Scale = -3
	Kilo  Scale = 3
	Mega  Scale = 6
	Giga  Scale = 9
	Tera  Scale = 12
	Peta  Scale = 15
	Exa   Scale = 18
)

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL