Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 16 additions & 0 deletions demo/main.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
package main

import (
"encoding/json"
"fmt"
"gomodules.xyz/resource-quantity"
)

func main() {
q := resource.MustParse("1.1Gi")
if data, err := json.Marshal(q); err != nil {
panic(err)
} else {
fmt.Println(string(data))
}
}
13 changes: 12 additions & 1 deletion quantity.go
Original file line number Diff line number Diff line change
Expand Up @@ -365,6 +365,13 @@ func ParseQuantity(str string) (Quantity, error) {
amount.Neg(amount)
}

copyAmount := new(inf.Dec)
if sign == -1 {
copyAmount.Neg(amount)
} else {
copyAmount.Set(amount)
}

// This rounds non-zero values up to the minimum representable value, under the theory that
// if you want some resources, you should get some resources, even if you asked for way too small
// of an amount. Arguably, this should be inf.RoundHalfUp (normal rounding), but that would have
Expand All @@ -387,7 +394,11 @@ func ParseQuantity(str string) (Quantity, error) {
amount.Neg(amount)
}

return Quantity{d: infDecAmount{amount}, Format: format}, nil
q := Quantity{d: infDecAmount{amount}, Format: format}
if copyAmount.Cmp(amount) == 0 {
q.s = str
}
return q, nil
}

// DeepCopy returns a deep-copy of the Quantity value. Note that the method
Expand Down
9 changes: 5 additions & 4 deletions quantity_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -725,7 +725,7 @@ func TestQuantityString(t *testing.T) {
{decQuantity(0, 0, BinarySI), "0", ""},
{decQuantity(1, 9, DecimalExponent), "1e9", ".001e12"},
{decQuantity(1, -3, DecimalExponent), "1e-3", "0.001e0"},
{decQuantity(1, -9, DecimalExponent), "1e-9", "1000e-12"},
{decQuantity(1, -9, DecimalExponent), "1e-9", ""},
{decQuantity(80, -3, DecimalExponent), "80e-3", ""},
{decQuantity(300, 6, DecimalExponent), "300e6", ""},
{decQuantity(1, 12, DecimalExponent), "1e12", ""},
Expand Down Expand Up @@ -794,11 +794,12 @@ func TestQuantityParseEmit(t *testing.T) {
{"1Ki", "1Ki"},
{"1Mi", "1Mi"},
{"1Gi", "1Gi"},
{"1.1Gi", "1.1Gi"},
{"1024Mi", "1Gi"},
{"1000M", "1G"},
{".001Ki", "1024m"},
{".000001Ki", "1024u"},
{".000000001Ki", "1024n"},
{".001Ki", ".001Ki"},
{".000001Ki", ".000001Ki"},
{".000000001Ki", ".000000001Ki"},
{".000000000001Ki", "2n"},
}

Expand Down