github.com/pjdufour-truss/pop@v4.11.2-0.20190705085848-4c90b0ff4d5a+incompatible/slices/float.go (about)

     1  package slices
     2  
     3  import (
     4  	"database/sql/driver"
     5  	"fmt"
     6  	"strconv"
     7  	"strings"
     8  
     9  	"errors"
    10  )
    11  
    12  // Float is a slice of float64.
    13  type Float []float64
    14  
    15  // Interface implements the nulls.nullable interface.
    16  func (f Float) Interface() interface{} {
    17  	return []float64(f)
    18  }
    19  
    20  // Scan implements the sql.Scanner interface.
    21  // It allows to read the float slice from the database value.
    22  func (f *Float) Scan(src interface{}) error {
    23  	b, ok := src.([]byte)
    24  	if !ok {
    25  		return errors.New("scan source was not []byte")
    26  	}
    27  	str := string(b)
    28  	*f = strToFloat(str)
    29  	return nil
    30  }
    31  
    32  // Value implements the driver.Valuer interface.
    33  // It allows to convert the float slice to a driver.value.
    34  func (f Float) Value() (driver.Value, error) {
    35  	sa := make([]string, len(f))
    36  	for x, i := range f {
    37  		sa[x] = strconv.FormatFloat(i, 'f', -1, 64)
    38  	}
    39  	return fmt.Sprintf("{%s}", strings.Join(sa, ",")), nil
    40  }
    41  
    42  // UnmarshalText will unmarshall text value into
    43  // the float slice representation of this value.
    44  func (f *Float) UnmarshalText(text []byte) error {
    45  	var ss []float64
    46  	for _, x := range strings.Split(string(text), ",") {
    47  		f, err := strconv.ParseFloat(x, 64)
    48  		if err != nil {
    49  			return err
    50  		}
    51  		ss = append(ss, f)
    52  	}
    53  	*f = ss
    54  	return nil
    55  }
    56  
    57  func strToFloat(s string) []float64 {
    58  	r := strings.Trim(s, "{}")
    59  	a := make([]float64, 0, 10)
    60  	for _, t := range strings.Split(r, ",") {
    61  		i, _ := strconv.ParseFloat(t, 64)
    62  		a = append(a, i)
    63  	}
    64  	return a
    65  }