Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
kardolus
GitHub Repository: kardolus/chatgpt-cli
Path: blob/main/vendor/github.com/spf13/cast/slice.go
2875 views
1
// Copyright © 2014 Steve Francia <[email protected]>.
2
//
3
// Use of this source code is governed by an MIT-style
4
// license that can be found in the LICENSE file.
5
6
package cast
7
8
import (
9
"fmt"
10
"reflect"
11
"strings"
12
)
13
14
// ToSliceE casts any value to a []any type.
15
func ToSliceE(i any) ([]any, error) {
16
i, _ = indirect(i)
17
18
var s []any
19
20
switch v := i.(type) {
21
case []any:
22
// TODO: use slices.Clone
23
return append(s, v...), nil
24
case []map[string]any:
25
for _, u := range v {
26
s = append(s, u)
27
}
28
29
return s, nil
30
default:
31
return s, fmt.Errorf(errorMsg, i, i, s)
32
}
33
}
34
35
func toSliceE[T Basic](i any) ([]T, error) {
36
v, ok, err := toSliceEOk[T](i)
37
if err != nil {
38
return nil, err
39
}
40
41
if !ok {
42
return nil, fmt.Errorf(errorMsg, i, i, []T{})
43
}
44
45
return v, nil
46
}
47
48
func toSliceEOk[T Basic](i any) ([]T, bool, error) {
49
i, _ = indirect(i)
50
if i == nil {
51
return nil, true, fmt.Errorf(errorMsg, i, i, []T{})
52
}
53
54
switch v := i.(type) {
55
case []T:
56
// TODO: clone slice
57
return v, true, nil
58
}
59
60
kind := reflect.TypeOf(i).Kind()
61
switch kind {
62
case reflect.Slice, reflect.Array:
63
s := reflect.ValueOf(i)
64
a := make([]T, s.Len())
65
66
for j := 0; j < s.Len(); j++ {
67
val, err := ToE[T](s.Index(j).Interface())
68
if err != nil {
69
return nil, true, fmt.Errorf(errorMsg, i, i, []T{})
70
}
71
72
a[j] = val
73
}
74
75
return a, true, nil
76
default:
77
return nil, false, nil
78
}
79
}
80
81
// ToStringSliceE casts any value to a []string type.
82
func ToStringSliceE(i any) ([]string, error) {
83
if a, ok, err := toSliceEOk[string](i); ok {
84
if err != nil {
85
return nil, err
86
}
87
88
return a, nil
89
}
90
91
var a []string
92
93
switch v := i.(type) {
94
case string:
95
return strings.Fields(v), nil
96
case any:
97
str, err := ToStringE(v)
98
if err != nil {
99
return nil, fmt.Errorf(errorMsg, i, i, a)
100
}
101
102
return []string{str}, nil
103
default:
104
return nil, fmt.Errorf(errorMsg, i, i, a)
105
}
106
}
107
108