diff --git a/math/uint.go b/math/uint.go index 10cf749a99..597fe8e2e8 100644 --- a/math/uint.go +++ b/math/uint.go @@ -1,6 +1,7 @@ package math import ( + "encoding/xml" "errors" "fmt" "math/big" @@ -137,6 +138,21 @@ func MaxUint(u1, u2 Uint) Uint { return NewUintFromBigInt(max(u1.i, u2.i)) } // Human readable string func (u Uint) String() string { return u.i.String() } +// MarshalXML defines custom encoding for xml Marshaler +func (u Uint) MarshalXML(e *xml.Encoder, start xml.StartElement) error { + return e.EncodeElement(u.String(), start) +} + +// UnmarshalXML defines custom decoding for xml Marshaler +func (u *Uint) UnmarshalXML(d *xml.Decoder, start xml.StartElement) error { + var s string + if err := d.DecodeElement(&s, &start); err != nil { + return err + } + *u = NewUintFromString(s) + return nil +} + // MarshalJSON defines custom encoding scheme func (u Uint) MarshalJSON() ([]byte, error) { if u.i == nil { // Necessary since default Uint initialization has i.i as nil diff --git a/math/uint_test.go b/math/uint_test.go index ceb3e87d72..dcb6e9ab86 100644 --- a/math/uint_test.go +++ b/math/uint_test.go @@ -1,6 +1,7 @@ package math_test import ( + "encoding/xml" "fmt" "math" "math/big" @@ -377,3 +378,11 @@ func (s *uintTestSuite) TestUintBigEndian() { s.Require().Equal(u1, u2) } + +func (s *uintTestSuite) TestUintXmlMarshalRoundTrip() { + u1 := sdkmath.NewUint(256) + marshalResult, _ := xml.Marshal(u1) + u2 := sdkmath.Uint{} + xml.Unmarshal(marshalResult, &u2) + s.Require().Equal(u1, u2) +}