Skip to content

Commit

Permalink
Merge pull request #798 from gobuffalo/empty-slice
Browse files Browse the repository at this point in the history
fixed empty slice bug on slices.Float
  • Loading branch information
sio4 committed Nov 19, 2022
2 parents 339173d + 599fed6 commit 479087d
Show file tree
Hide file tree
Showing 3 changed files with 50 additions and 7 deletions.
25 changes: 18 additions & 7 deletions slices/float.go
Expand Up @@ -27,8 +27,9 @@ func (f *Float) Scan(src interface{}) error {
default:
return fmt.Errorf("scan source was not []byte nor string but %T", src)
}
*f = strToFloat(str)
return nil
v, err := strToFloat(str)
*f = v
return err
}

// Value implements the driver.Valuer interface.
Expand Down Expand Up @@ -56,12 +57,22 @@ func (f *Float) UnmarshalText(text []byte) error {
return nil
}

func strToFloat(s string) []float64 {
func strToFloat(s string) ([]float64, error) {
r := strings.Trim(s, "{}")
a := make([]float64, 0, 10)
for _, t := range strings.Split(r, ",") {
i, _ := strconv.ParseFloat(t, 64)
a = append(a, i)

elems := strings.Split(r, ",")
if len(elems) == 1 && elems[0] == "" {
return a, nil
}
return a

for _, t := range elems {
f, err := strconv.ParseFloat(t, 64)
if err != nil {
return nil, err
}
a = append(a, f)
}

return a, nil
}
30 changes: 30 additions & 0 deletions slices/float_test.go
@@ -0,0 +1,30 @@
package slices

import (
"testing"

"github.com/stretchr/testify/require"
)

func Test_Float_Scan(t *testing.T) {
r := require.New(t)
t.Run("empty slice", func(t *testing.T) {
in := "{}"
v := &Float{}
r.NoError(v.Scan(in))
r.Len(*v, 0)
})

t.Run("non-empty slice", func(t *testing.T) {
in := "{3.14,9.999}"
v := &Float{}
r.NoError(v.Scan(in))
r.Equal([]float64(*v), []float64{3.14, 9.999})
})

t.Run("invalid entry", func(t *testing.T) {
in := "{44,word}"
v := &Float{}
r.Error(v.Scan(in))
})
}
2 changes: 2 additions & 0 deletions slices_test.go
Expand Up @@ -44,6 +44,7 @@ func (s *PostgreSQLSuite) Test_Int() {
err = tx.Reload(c)
r.NoError(err)
r.Equal(slices.Int{1, 2, 3}, c.Int)
r.Equal(slices.Float{}, c.Float)
})
}

Expand All @@ -59,6 +60,7 @@ func (s *PostgreSQLSuite) Test_Float() {

err = tx.Reload(c)
r.NoError(err)
r.Equal(slices.Int{}, c.Int)
r.Equal(slices.Float{1.0, 2.1, 3.2}, c.Float)
})
}

0 comments on commit 479087d

Please sign in to comment.