Skip to content

Commit

Permalink
feat: add xml marshal for Int type (#365)
Browse files Browse the repository at this point in the history
Co-authored-by: Clyde <clyde.m@nodereal.io>
  • Loading branch information
ruojunm and clydemeng committed Nov 29, 2023
1 parent 3a54123 commit 1e407f2
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 0 deletions.
15 changes: 15 additions & 0 deletions math/int.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package math
import (
"encoding"
"encoding/json"
"encoding/xml"
"fmt"
"math/big"
"strings"
Expand Down Expand Up @@ -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
Expand Down
9 changes: 9 additions & 0 deletions math/int_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ package math_test

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

0 comments on commit 1e407f2

Please sign in to comment.