Skip to content

Commit

Permalink
fix: utils.BigInt.MarshalJSON() should, surprisingly, NOT have a poin…
Browse files Browse the repository at this point in the history
…ter receiver. This allows json.Marshal() to work on it.
  • Loading branch information
randomshinichi committed Aug 15, 2019
1 parent e29afb3 commit ebd8af4
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 10 deletions.
4 changes: 2 additions & 2 deletions utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -60,9 +60,9 @@ func (b *BigInt) UnmarshalJSON(text []byte) error {
}

// MarshalJSON implements the json.Marshaler interface.
func (b *BigInt) MarshalJSON() ([]byte, error) {
func (b BigInt) MarshalJSON() ([]byte, error) {
bc := new(big.Int)
bOrig := big.Int(*b)
bOrig := big.Int(b)
bc.Set(&bOrig)
return bc.MarshalJSON()
}
Expand Down
25 changes: 17 additions & 8 deletions utils/utils_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
package utils

import (
"encoding/json"
"fmt"
"math"
"math/big"
"reflect"
Expand Down Expand Up @@ -72,29 +74,36 @@ func TestBigIntLargerThanZero(t *testing.T) {
}

func TestBigInt_UnmarshalJSON(t *testing.T) {
type args struct {
text []byte
}
tests := []struct {
name string
b BigInt
args args
rawInt []byte
wantErr bool
}{{
name: "Deserialize this",
args: args{[]byte("1600000000000000000129127208515966861305")},
name: "utils.BigInt 1600000000000000000129127208515966861305",
rawInt: []byte("1600000000000000000129127208515966861305"),
b: BigInt(*RequireIntFromString("1600000000000000000129127208515966861305")),
wantErr: false,
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Run(fmt.Sprintf("UnmarshalJSON %v", tt.name), func(t *testing.T) {
b := &BigInt{}
if err := b.UnmarshalJSON(tt.args.text); (err != nil) != tt.wantErr {
if err := b.UnmarshalJSON(tt.rawInt); (err != nil) != tt.wantErr {
t.Errorf("BigInt.UnmarshalJSON() error = %v, wantErr %v", err, tt.wantErr)
}
if b.Cmp(&tt.b) != 0 {
t.Errorf("The values are not the same: b: %s, want: %s", b.String(), tt.b.String())
}
})
t.Run(fmt.Sprintf("MarshalJSON %v", tt.name), func(t *testing.T) {
jm, err := json.Marshal(tt.b)
if err != nil {
t.Errorf("BigInt.MarshalJSON() error = %v", err)
}

if !reflect.DeepEqual(jm, tt.rawInt) {
t.Errorf("BigInt.MarshalJSON() should have marshaled into %s, got %s", tt.rawInt, jm)
}
})
}
}

0 comments on commit ebd8af4

Please sign in to comment.