util: add YAML marshaler to Fixed8
This commit is contained in:
parent
7a6d6f43ce
commit
2f865480d3
2 changed files with 33 additions and 2 deletions
|
@ -87,8 +87,20 @@ func Fixed8FromString(s string) (Fixed8, error) {
|
|||
|
||||
// UnmarshalJSON implements the json unmarshaller interface.
|
||||
func (f *Fixed8) UnmarshalJSON(data []byte) error {
|
||||
return f.unmarshalHelper(func(v interface{}) error {
|
||||
return json.Unmarshal(data, v)
|
||||
})
|
||||
}
|
||||
|
||||
// UnmarshalYAML implements the yaml unmarshaler interface.
|
||||
func (f *Fixed8) UnmarshalYAML(unmarshal func(interface{}) error) error {
|
||||
return f.unmarshalHelper(unmarshal)
|
||||
}
|
||||
|
||||
// unmarshalHelper is an underlying unmarshaller func for JSON and YAML.
|
||||
func (f *Fixed8) unmarshalHelper(unmarshal func(interface{}) error) error {
|
||||
var s string
|
||||
if err := json.Unmarshal(data, &s); err == nil {
|
||||
if err := unmarshal(&s); err == nil {
|
||||
p, err := Fixed8FromString(s)
|
||||
if err != nil {
|
||||
return err
|
||||
|
@ -98,7 +110,7 @@ func (f *Fixed8) UnmarshalJSON(data []byte) error {
|
|||
}
|
||||
|
||||
var fl float64
|
||||
if err := json.Unmarshal(data, &fl); err != nil {
|
||||
if err := unmarshal(&fl); err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
|
@ -111,6 +123,11 @@ func (f Fixed8) MarshalJSON() ([]byte, error) {
|
|||
return []byte(`"` + f.String() + `"`), nil
|
||||
}
|
||||
|
||||
// MarshalYAML implements the yaml marshaller interface.
|
||||
func (f Fixed8) MarshalYAML() (interface{}, error) {
|
||||
return f.String(), nil
|
||||
}
|
||||
|
||||
// DecodeBinary implements the io.Serializable interface.
|
||||
func (f *Fixed8) DecodeBinary(r *io.BinReader) {
|
||||
*f = Fixed8(r.ReadU64LE())
|
||||
|
|
|
@ -6,6 +6,7 @@ import (
|
|||
"testing"
|
||||
|
||||
"github.com/CityOfZion/neo-go/pkg/io"
|
||||
"github.com/go-yaml/yaml"
|
||||
"github.com/stretchr/testify/assert"
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
@ -125,6 +126,19 @@ func TestFixed8_MarshalJSON(t *testing.T) {
|
|||
assert.Equal(t, []byte(`"123.4"`), s)
|
||||
}
|
||||
|
||||
func TestFixed8_UnmarshalYAML(t *testing.T) {
|
||||
u, err := Fixed8FromString("123.4")
|
||||
assert.NoError(t, err)
|
||||
|
||||
s, err := yaml.Marshal(u)
|
||||
assert.NoError(t, err)
|
||||
assert.Equal(t, []byte("\"123.4\"\n"), s) // yaml marshaler inserts LF at the end
|
||||
|
||||
var f Fixed8
|
||||
assert.NoError(t, yaml.Unmarshal([]byte(`"123.4"`), &f))
|
||||
assert.Equal(t, u, f)
|
||||
}
|
||||
|
||||
func TestFixed8_Arith(t *testing.T) {
|
||||
u1 := Fixed8FromInt64(3)
|
||||
u2 := Fixed8FromInt64(8)
|
||||
|
|
Loading…
Reference in a new issue