Skip to content

Commit

Permalink
utils: BigInt implements UnmarshalJSON and MarshalJSON. Unittests inc…
Browse files Browse the repository at this point in the history
…luded for peace of mind, although code does not actually do much.
  • Loading branch information
randomshinichi committed Feb 28, 2019
1 parent 5a4a67b commit b6714c8
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 0 deletions.
19 changes: 19 additions & 0 deletions utils/utils.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package utils

import (
"bufio"
"encoding/json"
"errors"
"fmt"
"math/big"
Expand Down Expand Up @@ -157,3 +158,21 @@ func (b *BigInt) validate() error {
}
return nil
}

// UnmarshalJSON implements encoding/json/RawMessage.UnmarshalJSON
func (b *BigInt) UnmarshalJSON(data []byte) error {
err := json.Unmarshal(data, &b.Int)
if err != nil {
return err
}

return nil
}

// MarshalJSON calls json.Marshal() on the BigInt.Int field.
func (b *BigInt) MarshalJSON() ([]byte, error) {
if b == nil {
return []byte("null"), nil
}
return json.Marshal(b.Int)
}
49 changes: 49 additions & 0 deletions utils/utils_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,29 @@ package utils

import (
"errors"
"fmt"
"math"
"math/big"
"reflect"
"testing"
)

func TestBigInt(t *testing.T) {
realBig := big.Int{}
realBig.SetUint64(math.MaxUint64)
result := big.Int{}
fmt.Println(realBig, result)
fmt.Println(result.Add(&realBig, big.NewInt(10)))

var customBig = BigInt{&big.Int{}}
customBig.SetUint64(math.MaxUint64)
fmt.Println(customBig)

var resultBig = BigInt{&big.Int{}}
resultBig.Add(customBig.Int, big.NewInt(1000))
fmt.Println(resultBig)
}

func TestValidate(t *testing.T) {
var amount = BigInt{&big.Int{}}
var tests = []struct {
Expand All @@ -29,3 +46,35 @@ func TestValidate(t *testing.T) {
}
}
}

func TestUnmarshalJSON(t *testing.T) {
maxuint64AsString := []byte("18446744073709551615")
maxuint64AsBigInt := BigInt{&big.Int{}}
maxuint64AsBigInt.SetString("18446744073709551615", 10)

overuint64AsString := []byte("28446744073709551615")
overuint64AsBigInt := BigInt{&big.Int{}}
overuint64AsBigInt.SetString("28446744073709551615", 10)

negBigIntAsString := []byte("-1")
negBigIntAsBigInt := BigInt{&big.Int{}}
negBigIntAsBigInt.SetString("-1", 10)

var amount = BigInt{&big.Int{}}
var tests = []struct {
input []byte
expected BigInt
}{
{[]byte("0"), BigInt{&big.Int{}}},
{maxuint64AsString, maxuint64AsBigInt},
{overuint64AsString, overuint64AsBigInt},
{negBigIntAsString, negBigIntAsBigInt},
}

for _, test := range tests {
amount.UnmarshalJSON(test.input)
if amount.Cmp(test.expected.Int) != 0 {
t.Errorf("Test Failed: %v inputted, %v expected, %#v received", test.input, test.expected, amount)
}
}
}

0 comments on commit b6714c8

Please sign in to comment.