Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add xml marshal for Uint type #364

Merged
merged 4 commits into from
Nov 24, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
}
Loading