-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
123 lines (112 loc) · 2.02 KB
/
utils.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
package zmq3
import (
"fmt"
)
/*
Send multi-part message on socket.
Any `[]string' or `[][]byte' is split into separate `string's or `[]byte's
Any other part that isn't a `string' or `[]byte' is converted
to `string' with `fmt.Sprintf("%v", part)'.
Returns total bytes sent.
*/
func (soc *Socket) SendMessage(parts ...interface{}) (total int, err error) {
// TODO: make this faster
// flatten first, just in case the last part may be an empty []string or [][]byte
pp := make([]interface{}, 0)
for _, p := range parts {
switch t := p.(type) {
case []string:
for _, s := range t {
pp = append(pp, s)
}
case [][]byte:
for _, b := range t {
pp = append(pp, b)
}
default:
pp = append(pp, t)
}
}
n := len(pp)
if n == 0 {
return
}
opt := SNDMORE
for i, p := range pp {
if i == n-1 {
opt = 0
}
switch t := p.(type) {
case string:
j, e := soc.Send(t, opt)
if e == nil {
total += j
} else {
return -1, e
}
case []byte:
j, e := soc.SendBytes(t, opt)
if e == nil {
total += j
} else {
return -1, e
}
default:
j, e := soc.Send(fmt.Sprintf("%v", t), opt)
if e == nil {
total += j
} else {
return -1, e
}
}
}
return
}
/*
Receive parts as message from socket.
Returns last non-nil error code.
*/
func (soc *Socket) RecvMessage(flags Flag) (msg []string, err error) {
msg = make([]string, 0)
for {
s, e := soc.Recv(flags)
if e == nil {
msg = append(msg, s)
} else {
return msg[0:0], e
}
more, e := soc.GetRcvmore()
if e == nil {
if !more {
break
}
} else {
return msg[0:0], e
}
}
return
}
/*
Receive parts as message from socket.
Returns last non-nil error code.
*/
func (soc *Socket) RecvMessageBytes(flags Flag) (msg [][]byte, err error) {
msg = make([][]byte, 0)
for {
b, e := soc.RecvBytes(flags)
if e == nil {
msg = append(msg, b)
} else {
return msg[0:0], e
}
more, e := soc.GetRcvmore()
if e == nil {
if !more {
break
}
} else {
return msg[0:0], e
}
}
return
}