-
Notifications
You must be signed in to change notification settings - Fork 0
/
chan.go
62 lines (58 loc) · 1.23 KB
/
chan.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
package attest
import (
"errors"
"reflect"
)
// Ensure that a value is able to be immediately sent on the specified channel.
func ChanSend(c interface{}, v interface{}) error {
cases := []reflect.SelectCase{
{
Dir: reflect.SelectSend,
Chan: reflect.ValueOf(c),
Send: reflect.ValueOf(v),
},
{
Dir: reflect.SelectDefault,
},
}
i, _, _ := reflect.Select(cases)
if i != 0 {
return errors.New("sending on channel failed")
}
return nil
}
// Ensure that a value is able to be immediately received on the specified
// channel. If a value is received, it is returned.
func ChanRecv(c interface{}) (interface{}, error) {
cases := []reflect.SelectCase{
{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(c),
},
{
Dir: reflect.SelectDefault,
},
}
_, v, ok := reflect.Select(cases)
if !ok {
return nil, errors.New("receiving on channel failed")
}
return v.Interface(), nil
}
// Ensure that the channel is closed.
func ChanClosed(c interface{}) error {
cases := []reflect.SelectCase{
{
Dir: reflect.SelectRecv,
Chan: reflect.ValueOf(c),
},
{
Dir: reflect.SelectDefault,
},
}
i, _, ok := reflect.Select(cases)
if i != 0 || ok {
return errors.New("channel is not closed")
}
return nil
}