Skip to content

Commit

Permalink
fix json marshal/unmarshal for FIL type (#4686)
Browse files Browse the repository at this point in the history
  • Loading branch information
hunjixin authored Jan 11, 2022
1 parent 69cd482 commit b115c3e
Show file tree
Hide file tree
Showing 2 changed files with 69 additions and 0 deletions.
22 changes: 22 additions & 0 deletions pkg/types/internal/fil.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package internal

import (
"encoding"
"encoding/json"
"fmt"
fbig "github.com/filecoin-project/go-state-types/big"
"github.com/filecoin-project/venus/pkg/constants"
Expand Down Expand Up @@ -85,6 +86,24 @@ func (f FIL) UnmarshalText(text []byte) error {
return nil
}

func (f FIL) MarshalJSON() ([]byte, error) {
return []byte("\"" + f.String() + "\""), nil
}

func (f *FIL) UnmarshalJSON(by []byte) error {
p, err := ParseFIL(strings.Trim(string(by), "\""))
if err != nil {
return err
}
if f.Int != nil {
f.Int.Set(p.Int)
} else {
f.Int = p.Int
}

return nil
}

func ParseFIL(s string) (FIL, error) {
suffix := strings.TrimLeft(s, "-.1234567890")
s = s[:len(s)-len(suffix)]
Expand Down Expand Up @@ -135,3 +154,6 @@ func MustParseFIL(s string) FIL {

var _ encoding.TextMarshaler = (*FIL)(nil)
var _ encoding.TextUnmarshaler = (*FIL)(nil)

var _ json.Marshaler = (*FIL)(nil)
var _ json.Unmarshaler = (*FIL)(nil)
47 changes: 47 additions & 0 deletions pkg/types/internal/fil_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package internal

import (
"encoding/json"
"fmt"
"math/big"
"testing"

"github.com/stretchr/testify/require"
Expand Down Expand Up @@ -112,3 +115,47 @@ func TestFilShort(t *testing.T) {
})
}
}

func TestMarshal(t *testing.T) {
type A struct {
Fil FIL
}
var a = A{
Fil: FIL{big.NewInt(1000000)},
}

aBytes, err := json.Marshal(a)
require.NoError(t, err)

require.Equal(t, aBytes, []byte("{\"Fil\":\"0.000000000001 FIL\"}"))
fmt.Println(string(aBytes))
}

func TestUnMarshal(t *testing.T) {
type A struct {
Fil FIL
}
bigFIl, _ := big.NewInt(0).SetString("100000000000000000000", 10)
for _, s := range []struct {
fil string
expect FIL
}{
{
fil: "{\"Fil\":\"0.000000000001 FIL\"}",
expect: FIL{big.NewInt(1000000)},
},
{
fil: "{\"Fil\":\"1 FIL\"}",
expect: FIL{big.NewInt(1000000000000000000)},
},
{
fil: "{\"Fil\":\"100 FIL\"}",
expect: FIL{bigFIl},
},
} {
a := A{}
err := json.Unmarshal([]byte(s.fil), &a)
require.NoError(t, err)
require.Equal(t, a.Fil.String(), s.expect.String())
}
}

0 comments on commit b115c3e

Please sign in to comment.