From 2d77efdafb3c3ee17ea8448028b535ea77457cd3 Mon Sep 17 00:00:00 2001 From: Clayton Coleman Date: Wed, 28 Apr 2021 13:07:50 -0400 Subject: [PATCH] quantity: Allow a new quantity to be created directly from inf.Dec The normal way to do complex math for quantities would be with inf.Dec which we allow you to get from a quantity. Once you perform that math it should be easier to go back to a quantity. --- .../k8s.io/apimachinery/pkg/api/resource/quantity.go | 9 +++++++++ .../apimachinery/pkg/api/resource/quantity_test.go | 10 ++++++++++ 2 files changed, 19 insertions(+) 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 {