-
Notifications
You must be signed in to change notification settings - Fork 338
/
item.go
97 lines (86 loc) · 2.14 KB
/
item.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
package rxgo
import (
"context"
"reflect"
)
type (
// Item is a wrapper having either a value or an error.
Item struct {
V interface{}
E error
}
// CloseChannelStrategy indicates a strategy on whether to close a channel.
CloseChannelStrategy uint32
)
const (
// LeaveChannelOpen indicates to leave the channel open after completion.
LeaveChannelOpen CloseChannelStrategy = iota
// CloseChannel indicates to close the channel open after completion.
CloseChannel
)
// Of creates an item from a value.
func Of(i interface{}) Item {
return Item{V: i}
}
// Error creates an item from an error.
func Error(err error) Item {
return Item{E: err}
}
// SendItems is an utility function that send a list of interface{} and indicate a strategy on whether to close
// the channel once the function completes.
func SendItems(ch chan<- Item, strategy CloseChannelStrategy, items ...interface{}) {
if strategy == CloseChannel {
defer close(ch)
}
for _, currentItem := range items {
switch item := currentItem.(type) {
default:
rt := reflect.TypeOf(item)
switch rt.Kind() {
default:
ch <- Of(item)
case reflect.Slice:
s := reflect.ValueOf(currentItem)
for i := 0; i < s.Len(); i++ {
currentItem := s.Index(i).Interface()
switch item := currentItem.(type) {
default:
ch <- Of(item)
case error:
ch <- Error(item)
}
}
}
case error:
ch <- Error(item)
}
}
}
// Error checks if an item is an error.
func (i Item) Error() bool {
return i.E != nil
}
// SendBlocking sends an item and blocks until it is sent.
func (i Item) SendBlocking(ch chan<- Item) {
ch <- i
}
// SendWithContext sends an item and blocks until it is sent or a context canceled.
// It returns a boolean to indicate whether the item was sent.
func (i Item) SendWithContext(ctx context.Context, ch chan<- Item) bool {
select {
case <-ctx.Done():
return false
case ch <- i:
return true
}
}
// SendNonBlocking sends an item without blocking.
// It returns a boolean to indicate whether the item was sent.
func (i Item) SendNonBlocking(ch chan<- Item) bool {
select {
default:
return false
case ch <- i:
return true
}
}