]> Cypherpunks repositories - gostls13.git/commitdiff
math/big: produce valid JSON in Int.MarshalJSON when nil
authorcuiweixie <cuiweixie@gmail.com>
Sat, 12 Feb 2022 15:19:18 +0000 (15:19 +0000)
committerDaniel Martí <mvdan@mvdan.cc>
Wed, 2 Mar 2022 11:27:34 +0000 (11:27 +0000)
Fixes #50940.

Change-Id: Ie2a0c4505ca9d7e448017d9d00a020a6b3996be3
GitHub-Last-Rev: afd8c6b5598f43de25831c700b8d76cd97571426
GitHub-Pull-Request: golang/go#50941
Reviewed-on: https://go-review.googlesource.com/c/go/+/381963
Trust: Cherry Mui <cherryyz@google.com>
Reviewed-by: Emmanuel Odeke <emmanuel@orijtech.com>
Trust: Emmanuel Odeke <emmanuel@orijtech.com>
Run-TryBot: Emmanuel Odeke <emmanuel@orijtech.com>
TryBot-Result: Gopher Robot <gobot@golang.org>
Reviewed-by: Daniel Martí <mvdan@mvdan.cc>
Trust: Daniel Martí <mvdan@mvdan.cc>

src/math/big/intmarsh.go
src/math/big/intmarsh_test.go

index c1422e271072063f88254258673e50db92707e11..ce429ffc11e71d226609492009204c0f4eb29f15 100644 (file)
@@ -67,7 +67,10 @@ func (z *Int) UnmarshalText(text []byte) error {
 
 // MarshalJSON implements the json.Marshaler interface.
 func (x *Int) MarshalJSON() ([]byte, error) {
-       return x.MarshalText()
+       if x == nil {
+               return []byte("null"), nil
+       }
+       return x.abs.itoa(x.neg, 10), nil
 }
 
 // UnmarshalJSON implements the json.Unmarshaler interface.
index f82956ceaf22ea08b24c23c086a1365730bf9d2b..936669b380b470d67ad50b2e0af20a7137bb6634 100644 (file)
@@ -97,6 +97,20 @@ func TestIntJSONEncoding(t *testing.T) {
        }
 }
 
+
+func TestIntJSONEncodingNil(t *testing.T) {
+       var x *Int
+       b, err := x.MarshalJSON()
+       if err != nil {
+               t.Fatalf("marshaling of nil failed: %s", err)
+       }
+       got := string(b)
+       want := "null"
+       if got != want {
+               t.Fatalf("marshaling of nil failed: got %s want %s", got, want)
+       }
+}
+
 func TestIntXMLEncoding(t *testing.T) {
        for _, test := range encodingTests {
                for _, sign := range []string{"", "+", "-"} {