github.com/Odesyuk/pop@v4.13.1+incompatible/slices/int.go (about) 1 package slices 2 3 import ( 4 "database/sql/driver" 5 "fmt" 6 "strconv" 7 "strings" 8 9 "errors" 10 ) 11 12 // Int is a slice of int. 13 type Int []int 14 15 // Interface implements the nulls.nullable interface. 16 func (i Int) Interface() interface{} { 17 return []int(i) 18 } 19 20 // Scan implements the sql.Scanner interface. 21 // It allows to read the int slice from the database value. 22 func (i *Int) 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 *i = strToInt(str) 29 return nil 30 } 31 32 // Value implements the driver.Valuer interface. 33 // It allows to convert the int slice to a driver.value. 34 func (i Int) Value() (driver.Value, error) { 35 sa := make([]string, len(i)) 36 for x, v := range i { 37 sa[x] = strconv.Itoa(v) 38 } 39 return fmt.Sprintf("{%s}", strings.Join(sa, ",")), nil 40 } 41 42 // UnmarshalText will unmarshall text value into 43 // the int slice representation of this value. 44 func (i *Int) UnmarshalText(text []byte) error { 45 var ss []int 46 for _, x := range strings.Split(string(text), ",") { 47 f, err := strconv.Atoi(x) 48 if err != nil { 49 return err 50 } 51 ss = append(ss, f) 52 } 53 *i = ss 54 return nil 55 } 56 57 func strToInt(s string) []int { 58 r := strings.Trim(s, "{}") 59 a := make([]int, 0, 10) 60 for _, t := range strings.Split(r, ",") { 61 i, _ := strconv.Atoi(t) 62 a = append(a, i) 63 } 64 return a 65 }