diff --git a/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go b/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go index 8d718945d06..2395656cc90 100644 --- a/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go +++ b/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity.go @@ -696,6 +696,15 @@ func (q *Quantity) UnmarshalJSON(value []byte) error { return nil } +// NewDecimalQuantity returns a new Quantity representing the given +// value in the given format. +func NewDecimalQuantity(b inf.Dec, format Format) *Quantity { + return &Quantity{ + d: infDecAmount{&b}, + Format: format, + } +} + // NewQuantity returns a new Quantity representing the given // value in the given format. func NewQuantity(value int64, format Format) *Quantity { diff --git a/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_test.go b/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_test.go index 3c341d056f8..cb459b69d45 100644 --- a/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_test.go +++ b/staging/src/k8s.io/apimachinery/pkg/api/resource/quantity_test.go @@ -392,6 +392,16 @@ func TestQuantityParse(t *testing.T) { got.AsDec() } + for _, format := range []Format{DecimalSI, BinarySI, DecimalExponent} { + // ensure we are not simply checking pointer equality by creating a new inf.Dec + var copied inf.Dec + copied.Add(inf.NewDec(0, inf.Scale(0)), got.AsDec()) + q := NewDecimalQuantity(copied, format) + if c := q.Cmp(got); c != 0 { + t.Errorf("%v: round trip from decimal back to quantity is not comparable: %d: %#v vs %#v", item.input, c, got, q) + } + } + // verify that we can decompose the input and get the same result by building up from the base. positive, _, num, denom, suffix, err := parseQuantityString(item.input) if err != nil {