-
Notifications
You must be signed in to change notification settings - Fork 0
/
castx.go
70 lines (59 loc) · 1.6 KB
/
castx.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
// Copyright © 2023 Ory Corp
// SPDX-License-Identifier: Apache-2.0
package castx
import (
"encoding/csv"
"fmt"
"reflect"
"strings"
"github.com/spf13/cast"
)
// ToFloatSlice casts an interface to a []float64 type.
func ToFloatSlice(i interface{}) []float64 {
f, _ := ToFloatSliceE(i)
return f
}
// ToFloatSliceE casts an interface to a []float64 type.
func ToFloatSliceE(i interface{}) ([]float64, error) {
if i == nil {
return []float64{}, fmt.Errorf("unable to cast %#v of type %T to []float64", i, i)
}
switch v := i.(type) {
case []float64:
return v, nil
}
kind := reflect.TypeOf(i).Kind()
switch kind {
case reflect.Slice, reflect.Array:
s := reflect.ValueOf(i)
a := make([]float64, s.Len())
for j := 0; j < s.Len(); j++ {
val, err := cast.ToFloat64E(s.Index(j).Interface())
if err != nil {
return []float64{}, fmt.Errorf("unable to cast %#v of type %T to []float64", i, i)
}
a[j] = val
}
return a, nil
default:
return []float64{}, fmt.Errorf("unable to cast %#v of type %T to []float64", i, i)
}
}
// ToStringSlice casts an interface to a []string type and respects comma-separated values.
func ToStringSlice(i interface{}) []string {
s, _ := ToStringSliceE(i)
return s
}
// ToStringSliceE casts an interface to a []string type and respects comma-separated values.
func ToStringSliceE(i interface{}) ([]string, error) {
switch s := i.(type) {
case string:
return parseCSV(s)
}
return cast.ToStringSliceE(i)
}
func parseCSV(v string) ([]string, error) {
stringReader := strings.NewReader(v)
csvReader := csv.NewReader(stringReader)
return csvReader.Read()
}