-
Notifications
You must be signed in to change notification settings - Fork 3
/
gollection.go
124 lines (107 loc) · 2.34 KB
/
gollection.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
/*
Package gollection provides collection util to any type slices.
*/
package gollection
import (
"fmt"
"reflect"
"sync"
)
type gollection struct {
slice interface{}
val interface{}
ch chan interface{}
err error
}
// New returns a gollection instance which can method chain *sequentially* specified by some type of slice.
func New(slice interface{}) *gollection {
return &gollection{
slice: slice,
}
}
// Result return a collection processed value and error.
func (g *gollection) Result() (interface{}, error) {
if g.ch != nil {
return g.resultStream()
}
return g.result()
}
func (g *gollection) result() (interface{}, error) {
if g.val != nil {
return g.val, g.err
}
return g.slice, g.err
}
func (g *gollection) ResultAs(out interface{}) error {
if g.err != nil {
return g.err
}
iv := reflect.ValueOf(g.slice)
if g.val != nil {
iv = reflect.ValueOf(g.val)
}
ov := reflect.ValueOf(out)
if ov.Kind() != reflect.Ptr || iv.Type() != ov.Elem().Type() {
return fmt.Errorf("gollection.ResultAs called with unexpected type %T, expected %s", g.slice, ov.Elem().Type())
}
ov.Elem().Set(iv)
return nil
}
func (g *gollection) resultStream() (interface{}, error) {
var ret reflect.Value
var initialized bool
var err error
wg := sync.WaitGroup{}
wg.Add(1)
go func(err *error) {
for {
select {
case v, ok := <-g.ch:
if ok {
if e, ok := v.(error); ok {
*err = e
wg.Done()
return
}
if !initialized {
ret = reflect.MakeSlice(v.(reflect.Type), 0, 0)
initialized = true
continue
}
ret = reflect.Append(ret, reflect.ValueOf(v))
} else {
wg.Done()
return
}
default:
continue
}
}
}(&err)
wg.Wait()
if err != nil {
return nil, err
}
return ret.Interface(), nil
}
// NewStream returns a gollection instance which can method chain *parallel* specified by some type of slice.
func NewStream(slice interface{}) *gollection {
next := &gollection{
ch: make(chan interface{}),
}
sv := reflect.ValueOf(slice)
if sv.Kind() != reflect.Slice {
return &gollection{
err: fmt.Errorf("gollection.NewStream called with non-slice value of type %T", slice),
}
}
go func() {
// initialze next stream type
next.ch <- sv.Type()
for i := 0; i < sv.Len(); i++ {
next.ch <- sv.Index(i).Interface()
}
close(next.ch)
}()
return next
}