Skip to content

Commit

Permalink
deal '-' as null on number marshaling
Browse files Browse the repository at this point in the history
  • Loading branch information
Songmu committed Jun 16, 2017
1 parent 15982a6 commit 50c6b57
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 0 deletions.
15 changes: 15 additions & 0 deletions decode.go
Original file line number Diff line number Diff line change
Expand Up @@ -109,6 +109,12 @@ func Unmarshal(data []byte, v interface{}) error {

if fv.Kind() == reflect.Ptr {
if fv.IsNil() {
if s == "-" {
switch fv.Type().Elem().Kind() {
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64, reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64, reflect.Float32, reflect.Float64:
continue
}
}
fv.Set(reflect.New(fv.Type().Elem()))
}
fv = fv.Elem()
Expand All @@ -121,20 +127,29 @@ func Unmarshal(data []byte, v interface{}) error {
case reflect.String:
fv.SetString(s)
case reflect.Int, reflect.Int8, reflect.Int16, reflect.Int32, reflect.Int64:
if s == "-" {
continue
}
i, err := strconv.ParseInt(s, 10, 64)
if err != nil || fv.OverflowInt(i) {
errs[ft.Name] = &UnmarshalTypeError{"number " + s, fv.Type()}
continue
}
fv.SetInt(i)
case reflect.Uint, reflect.Uint8, reflect.Uint16, reflect.Uint32, reflect.Uint64:
if s == "-" {
continue
}
i, err := strconv.ParseUint(s, 10, 64)
if err != nil || fv.OverflowUint(i) {
errs[ft.Name] = &UnmarshalTypeError{"number " + s, fv.Type()}
continue
}
fv.SetUint(i)
case reflect.Float32, reflect.Float64:
if s == "-" {
continue
}
n, err := strconv.ParseFloat(s, fv.Type().Bits())
if err != nil || fv.OverflowFloat(n) {
errs[ft.Name] = &UnmarshalTypeError{"number " + s, fv.Type()}
Expand Down
13 changes: 13 additions & 0 deletions decode_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -64,4 +64,17 @@ func TestUnmarshal(t *testing.T) {
if !reflect.DeepEqual(s2, expect3) {
t.Errorf("result of data2map not expected: %#v", s2)
}

s3 := &ss{}
Unmarshal([]byte("user:songmu\tage:-\theight:-"), s3)
expect4 := &ss{
User: "songmu",
Age: 0,
// Height: nil,
Weight: 0.0,
}
if !reflect.DeepEqual(s3, expect4) {
t.Errorf("result of data2map not expected: %#v", s3)
}

}

0 comments on commit 50c6b57

Please sign in to comment.