Skip to content

Commit

Permalink
fix(textx): scan MarshalText implements from both interface and addr.…
Browse files Browse the repository at this point in the history
…interface
  • Loading branch information
saitofun committed Jun 1, 2024
1 parent 0b5e7ec commit 9c166ec
Show file tree
Hide file tree
Showing 2 changed files with 10 additions and 1 deletion.
5 changes: 5 additions & 0 deletions textx/text.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,11 @@ func MarshalText(v any) ([]byte, error) {
return marshaller.MarshalText()
}
}
if rv.CanAddr() {
if marshaller, ok := rv.Addr().Interface().(encoding.TextMarshaler); ok {
return marshaller.MarshalText()
}
}

switch kind := rv.Kind(); kind {
case reflect.String:
Expand Down
6 changes: 5 additions & 1 deletion textx/text_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,13 +4,15 @@ import (
"bytes"
"encoding/binary"
"errors"
"math/big"
"reflect"
"strconv"
"testing"
"time"

. "github.com/onsi/gomega"

"github.com/xoctopus/x/misc/must"
"github.com/xoctopus/x/ptrx"
. "github.com/xoctopus/x/textx"
)
Expand Down Expand Up @@ -82,7 +84,9 @@ var marshalCases = map[string]*MarshalCase{
"Float64": {1.1, []byte("1.1"), nil},
"Bytes": {[]byte("any"), ToBase64([]byte("any")), nil},
"Marshaller": {Duration(time.Second), []byte("1s"), nil},
"Unsupported": {struct{}{}, nil, &ErrMarshalUnsupportedType{Type: reflect.TypeOf(struct{}{})}},
// type big.Int impl MarshalText with pointer reference: (*big.Int)MarshalText
"AddrMarshaller": {must.BeTrueV(new(big.Int).SetString("100110011001", 10)), []byte("100110011001"), nil},
"Unsupported": {struct{}{}, nil, &ErrMarshalUnsupportedType{Type: reflect.TypeOf(struct{}{})}},
}

func TestMarshalText(t *testing.T) {
Expand Down

0 comments on commit 9c166ec

Please sign in to comment.