From cdc0264a6b11ce6bad7c9d75309e18514ccd78cb Mon Sep 17 00:00:00 2001 From: John Mulligan Date: Wed, 2 Sep 2020 13:51:13 -0400 Subject: [PATCH] cephfs admin: add quotaSizePlaceholder type for JSON unmarshaling Add a new quotaSizePlaceholder type which is a non-interface type that can unmarshal JSON with a varying type into one of our types that meets the QuotaSize interface. Signed-off-by: John Mulligan --- cephfs/admin/bytecount.go | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/cephfs/admin/bytecount.go b/cephfs/admin/bytecount.go index 25304ff..f490bc3 100644 --- a/cephfs/admin/bytecount.go +++ b/cephfs/admin/bytecount.go @@ -2,6 +2,11 @@ package admin +import ( + "encoding/json" + "fmt" +) + // ByteCount represents the size of a volume in bytes. type ByteCount uint64 @@ -35,3 +40,29 @@ func (s specialSize) resizeValue() string { // Infinite is a special QuotaSize value that can be used to clear size limits // on a subvolume. const Infinite = specialSize("infinite") + +// quotaSizePlaceholder types are helpful to extract QuotaSize typed values +// from JSON responses. +type quotaSizePlaceholder struct { + Value QuotaSize +} + +func (p *quotaSizePlaceholder) UnmarshalJSON(b []byte) error { + var val interface{} + if err := json.Unmarshal(b, &val); err != nil { + return err + } + switch v := val.(type) { + case string: + if v == string(Infinite) { + p.Value = Infinite + } else { + return fmt.Errorf("quota size: invalid string value: %q", v) + } + case float64: + p.Value = ByteCount(v) + default: + return fmt.Errorf("quota size: invalid type, string or number required: %v (%T)", val, val) + } + return nil +}