Skip to content

Commit

Permalink
feat(textx): use fmt.Sscan to parse numeric types from string to supp…
Browse files Browse the repository at this point in the history
…ort multi numerical bases input
  • Loading branch information
saitofun committed May 31, 2024
1 parent 6f3429d commit 0b5e7ec
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 12 deletions.
26 changes: 14 additions & 12 deletions textx/text.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ package textx
import (
"encoding"
"encoding/base64"
"fmt"
"reflect"
"strconv"

Expand Down Expand Up @@ -96,23 +97,25 @@ func UnmarshalText(data []byte, v any) error {
rv.SetString(string(data))
return nil
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
v, err := strconv.ParseInt(string(data), 10, 64)
if err != nil {
i64 := int64(0)
if _, err := fmt.Sscan(string(data), &i64); err != nil {
return &ErrUnmarshalFailed{data, rv.Type(), err.Error()}
}
rv.SetInt(v)
rv.SetInt(i64)
return nil
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
v, err := strconv.ParseUint(string(data), 10, 64)
if err != nil {
return &ErrUnmarshalFailed{data, rt, err.Error()}
ui64 := uint64(0)
if _, err := fmt.Sscan(string(data), &ui64); err != nil {
return &ErrUnmarshalFailed{data, rv.Type(), err.Error()}
}
rv.SetUint(v)
rv.SetUint(ui64)
return nil
case reflect.Float32, reflect.Float64:
v, err := strconv.ParseFloat(string(data), 64)
if err != nil {
return &ErrUnmarshalFailed{data, rt, err.Error()}
f64 := float64(0)
if _, err := fmt.Sscan(string(data), &f64); err != nil {
return &ErrUnmarshalFailed{data, rv.Type(), err.Error()}
}
rv.SetFloat(v)
rv.SetFloat(f64)
return nil
case reflect.Bool:
v, err := strconv.ParseBool(string(data))
Expand All @@ -124,7 +127,6 @@ func UnmarshalText(data []byte, v any) error {
default:
return &ErrUnmarshalUnsupportedType{Type: rt}
}
return nil
}

func ToBase64(raw []byte) []byte {
Expand Down
3 changes: 3 additions & 0 deletions textx/text_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -132,6 +132,9 @@ var unmarshalCases = []*UnmarshalCase{
{"UnmarshalerFailed2", &UnsignedIntegers{0x02}, []byte{1, 0, 0, 0, 0, 0, 0}, errInvalidDataLength},
{"Unsupported1", new([]int), []byte("any"), &ErrUnmarshalUnsupportedType{Type: reflect.TypeOf([]int{})}},
{"Unsupported2", &struct{}{}, []byte("any"), &ErrUnmarshalUnsupportedType{Type: reflect.TypeOf(struct{}{})}},
{"HexInt", new(int), []byte("0xFF"), nil},
{"OctUint", new(uint), []byte("077"), nil},
{"InvalidNumeric", new(float64), []byte("abcdef"), &ErrUnmarshalFailed{Data: []byte("abcdef"), Type: reflect.TypeOf(float64(0))}},
}

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

0 comments on commit 0b5e7ec

Please sign in to comment.