@@ -3,9 +3,11 @@ package p2p
33import (
44 "bytes"
55 "encoding/binary"
6+ "errors"
67 "io"
78 "io/ioutil"
89 "math/big"
10+ "sync/atomic"
911
1012 "github.com/ethereum/go-ethereum/ethutil"
1113 "github.com/ethereum/go-ethereum/rlp"
@@ -153,3 +155,78 @@ func (r *postrack) ReadByte() (byte, error) {
153155 }
154156 return b , err
155157}
158+
159+ // MsgPipe creates a message pipe. Reads on one end are matched
160+ // with writes on the other. The pipe is full-duplex, both ends
161+ // implement MsgReadWriter.
162+ func MsgPipe () (* MsgPipeRW , * MsgPipeRW ) {
163+ var (
164+ c1 , c2 = make (chan Msg ), make (chan Msg )
165+ closing = make (chan struct {})
166+ closed = new (int32 )
167+ rw1 = & MsgPipeRW {c1 , c2 , closing , closed }
168+ rw2 = & MsgPipeRW {c2 , c1 , closing , closed }
169+ )
170+ return rw1 , rw2
171+ }
172+
173+ // ErrPipeClosed is returned from pipe operations after the
174+ // pipe has been closed.
175+ var ErrPipeClosed = errors .New ("p2p: read or write on closed message pipe" )
176+
177+ // MsgPipeRW is an endpoint of a MsgReadWriter pipe.
178+ type MsgPipeRW struct {
179+ w chan <- Msg
180+ r <- chan Msg
181+ closing chan struct {}
182+ closed * int32
183+ }
184+
185+ // WriteMsg sends a messsage on the pipe.
186+ // It blocks until the receiver has consumed the message payload.
187+ func (p * MsgPipeRW ) WriteMsg (msg Msg ) error {
188+ if atomic .LoadInt32 (p .closed ) == 0 {
189+ consumed := make (chan struct {}, 1 )
190+ msg .Payload = & eofSignal {msg .Payload , int64 (msg .Size ), consumed }
191+ select {
192+ case p .w <- msg :
193+ if msg .Size > 0 {
194+ // wait for payload read or discard
195+ <- consumed
196+ }
197+ return nil
198+ case <- p .closing :
199+ }
200+ }
201+ return ErrPipeClosed
202+ }
203+
204+ // EncodeMsg is a convenient shorthand for sending an RLP-encoded message.
205+ func (p * MsgPipeRW ) EncodeMsg (code uint64 , data ... interface {}) error {
206+ return p .WriteMsg (NewMsg (code , data ... ))
207+ }
208+
209+ // ReadMsg returns a message sent on the other end of the pipe.
210+ func (p * MsgPipeRW ) ReadMsg () (Msg , error ) {
211+ if atomic .LoadInt32 (p .closed ) == 0 {
212+ select {
213+ case msg := <- p .r :
214+ return msg , nil
215+ case <- p .closing :
216+ }
217+ }
218+ return Msg {}, ErrPipeClosed
219+ }
220+
221+ // Close unblocks any pending ReadMsg and WriteMsg calls on both ends
222+ // of the pipe. They will return ErrPipeClosed. Note that Close does
223+ // not interrupt any reads from a message payload.
224+ func (p * MsgPipeRW ) Close () error {
225+ if atomic .AddInt32 (p .closed , 1 ) != 1 {
226+ // someone else is already closing
227+ atomic .StoreInt32 (p .closed , 1 ) // avoid overflow
228+ return nil
229+ }
230+ close (p .closing )
231+ return nil
232+ }
0 commit comments