From aff8a206c06e39a010ab90d88f41ae78d7a127f3 Mon Sep 17 00:00:00 2001 From: Shulhan Date: Fri, 23 Apr 2021 11:51:31 +0700 Subject: math/big: extend Int to support marshal/unmarshal JSON --- lib/math/big/int.go | 34 ++++++++++++++++++++++++++++++++++ 1 file changed, 34 insertions(+) diff --git a/lib/math/big/int.go b/lib/math/big/int.go index f3f2b45f..66d5588b 100644 --- a/lib/math/big/int.go +++ b/lib/math/big/int.go @@ -7,6 +7,7 @@ package big import ( "bytes" "database/sql/driver" + "fmt" "math/big" "strings" ) @@ -32,6 +33,39 @@ func NewInt(v interface{}) (i *Int) { return i } +// +// MarshalJSON implement the json.Marshaler interface and return the output of +// String method. +// +// If the global variable MarshalJSONAsString is true, the Int value will +// be encoded as string. +// +func (r *Int) MarshalJSON() ([]byte, error) { + var s string + if r == nil { + s = "0" + } else { + s = r.String() + } + if MarshalJSONAsString { + s = `"` + s + `"` + } + return []byte(s), nil +} + +// +// UnmarshalJSON convert the JSON byte value into Int. +// +func (r *Int) UnmarshalJSON(in []byte) (err error) { + in = bytes.Trim(in, `"`) + r.SetInt64(0) + _, ok := r.Int.SetString(string(in), 10) + if !ok { + return fmt.Errorf("Int.UnmarshalJSON: cannot convert %T(%v) to Int", in, in) + } + return nil +} + // // Value implement the sql/driver.Valuer. // -- cgit v1.3