diff --git a/math/int.go b/math/int.go index 6811893f7a..80b0733967 100644 --- a/math/int.go +++ b/math/int.go @@ -3,6 +3,7 @@ package math import ( "encoding" "encoding/json" + "encoding/xml" "fmt" "math/big" "strings" @@ -327,6 +328,20 @@ func (i Int) String() string { return i.i.String() } +// MarshalXML defines custom encoding for xml Marshaler +func (i Int) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + return e.EncodeElement(i.String(), start) +} + +// UnmarshalXML defines custom decoding for xml Marshaler +func (i *Int) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + var s string + if err := d.DecodeElement(&s, &start); err != nil { + return err + } + return i.Unmarshal([]byte(s)) +} + // MarshalJSON defines custom encoding scheme func (i Int) MarshalJSON() ([]byte, error) { if i.i == nil { // Necessary since default Uint initialization has i.i as nil diff --git a/math/int_test.go b/math/int_test.go index 5af450cb6c..3106734db5 100644 --- a/math/int_test.go +++ b/math/int_test.go @@ -2,6 +2,7 @@ package math_test import ( "encoding/json" + "encoding/xml" "fmt" "math/big" "math/rand" @@ -396,6 +397,14 @@ func (s *intTestSuite) TestIntEq() { s.Require().False(resp) } +func (s *intTestSuite) TestIntXmlMarshalRoundTrip() { + u1 := math.NewInt(256) + marshalResult, _ := xml.Marshal(u1) + u2 := math.Int{} + xml.Unmarshal(marshalResult, &u2) + s.Require().Equal(u1, u2) +} + func TestRoundTripMarshalToInt(t *testing.T) { values := []int64{ 0,