diff --git a/pkg/util/fixed8.go b/pkg/util/fixed8.go index 617d0f48d..1282da8b8 100644 --- a/pkg/util/fixed8.go +++ b/pkg/util/fixed8.go @@ -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()) diff --git a/pkg/util/fixed8_test.go b/pkg/util/fixed8_test.go index 30753a7f2..7b2c76463 100644 --- a/pkg/util/fixed8_test.go +++ b/pkg/util/fixed8_test.go @@ -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)