Skip to content

Commit

Permalink
feat: add xml marshal for Uint type (#364)
Browse files Browse the repository at this point in the history
* feat: add xml marshal for Uint type

* feat: add ut for xml marshal for Uint type

* fix: refine comments

---------

Co-authored-by: dylanhuang <j75689@gmail.com>
Co-authored-by: Clyde <clyde.m@nodereal.io>
  • Loading branch information
3 people authored Nov 24, 2023
1 parent 45af819 commit 3a54123
Show file tree
Hide file tree
Showing 2 changed files with 25 additions and 0 deletions.
16 changes: 16 additions & 0 deletions math/uint.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package math

import (
"encoding/xml"
"errors"
"fmt"
"math/big"
Expand Down Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions math/uint_test.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package math_test

import (
"encoding/xml"
"fmt"
"math"
"math/big"
Expand Down Expand Up @@ -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)
}

0 comments on commit 3a54123

Please sign in to comment.