Skip to content

Commit 5cf9bf2

Browse files
committed
Preserve string form if the original value can be fully represented
Signed-off-by: Tamal Saha <[email protected]>
1 parent 6c34b56 commit 5cf9bf2

File tree

3 files changed

+32
-5
lines changed

3 files changed

+32
-5
lines changed

demo/main.go

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,16 @@
1+
package main
2+
3+
import (
4+
"encoding/json"
5+
"fmt"
6+
"gomodules.xyz/resource-quantity"
7+
)
8+
9+
func main() {
10+
q := resource.MustParse("1.1Gi")
11+
if data, err := json.Marshal(q); err != nil {
12+
panic(err)
13+
} else {
14+
fmt.Println(string(data))
15+
}
16+
}

quantity.go

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -365,6 +365,13 @@ func ParseQuantity(str string) (Quantity, error) {
365365
amount.Neg(amount)
366366
}
367367

368+
copyAmount := new(inf.Dec)
369+
if sign == -1 {
370+
copyAmount.Neg(amount)
371+
} else {
372+
copyAmount.Set(amount)
373+
}
374+
368375
// This rounds non-zero values up to the minimum representable value, under the theory that
369376
// if you want some resources, you should get some resources, even if you asked for way too small
370377
// of an amount. Arguably, this should be inf.RoundHalfUp (normal rounding), but that would have
@@ -387,7 +394,11 @@ func ParseQuantity(str string) (Quantity, error) {
387394
amount.Neg(amount)
388395
}
389396

390-
return Quantity{d: infDecAmount{amount}, Format: format}, nil
397+
q := Quantity{d: infDecAmount{amount}, Format: format}
398+
if copyAmount.Cmp(amount) == 0 {
399+
q.s = str
400+
}
401+
return q, nil
391402
}
392403

393404
// DeepCopy returns a deep-copy of the Quantity value. Note that the method

quantity_test.go

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -725,7 +725,7 @@ func TestQuantityString(t *testing.T) {
725725
{decQuantity(0, 0, BinarySI), "0", ""},
726726
{decQuantity(1, 9, DecimalExponent), "1e9", ".001e12"},
727727
{decQuantity(1, -3, DecimalExponent), "1e-3", "0.001e0"},
728-
{decQuantity(1, -9, DecimalExponent), "1e-9", "1000e-12"},
728+
{decQuantity(1, -9, DecimalExponent), "1e-9", ""},
729729
{decQuantity(80, -3, DecimalExponent), "80e-3", ""},
730730
{decQuantity(300, 6, DecimalExponent), "300e6", ""},
731731
{decQuantity(1, 12, DecimalExponent), "1e12", ""},
@@ -796,9 +796,9 @@ func TestQuantityParseEmit(t *testing.T) {
796796
{"1Gi", "1Gi"},
797797
{"1024Mi", "1Gi"},
798798
{"1000M", "1G"},
799-
{".001Ki", "1024m"},
800-
{".000001Ki", "1024u"},
801-
{".000000001Ki", "1024n"},
799+
{".001Ki", ".001Ki"},
800+
{".000001Ki", ".000001Ki"},
801+
{".000000001Ki", ".000000001Ki"},
802802
{".000000000001Ki", "2n"},
803803
}
804804

0 commit comments

Comments
 (0)