github.com/zignig/go-ipfs@v0.0.0-20141111235910-c9e5fdf55a52/net/message/message.go (about)

     1  package message
     2  
     3  import (
     4  	peer "github.com/jbenet/go-ipfs/peer"
     5  
     6  	proto "github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
     7  )
     8  
     9  // NetMessage is the interface for the message
    10  type NetMessage interface {
    11  	Peer() peer.Peer
    12  	Data() []byte
    13  }
    14  
    15  // New is the interface for constructing a new message.
    16  func New(p peer.Peer, data []byte) NetMessage {
    17  	return &message{peer: p, data: data}
    18  }
    19  
    20  // message represents a packet of information sent to or received from a
    21  // particular Peer.
    22  type message struct {
    23  	// To or from, depending on direction.
    24  	peer peer.Peer
    25  
    26  	// Opaque data
    27  	data []byte
    28  }
    29  
    30  func (m *message) Peer() peer.Peer {
    31  	return m.peer
    32  }
    33  
    34  func (m *message) Data() []byte {
    35  	return m.data
    36  }
    37  
    38  // FromObject creates a message from a protobuf-marshallable message.
    39  func FromObject(p peer.Peer, data proto.Message) (NetMessage, error) {
    40  	bytes, err := proto.Marshal(data)
    41  	if err != nil {
    42  		return nil, err
    43  	}
    44  	return New(p, bytes), nil
    45  }
    46  
    47  // Pipe objects represent a bi-directional message channel.
    48  type Pipe struct {
    49  	Incoming chan NetMessage
    50  	Outgoing chan NetMessage
    51  }
    52  
    53  // NewPipe constructs a pipe with channels of a given buffer size.
    54  func NewPipe(bufsize int) *Pipe {
    55  	return &Pipe{
    56  		Incoming: make(chan NetMessage, bufsize),
    57  		Outgoing: make(chan NetMessage, bufsize),
    58  	}
    59  }
    60  
    61  // ConnectTo connects this pipe to another, using a context for termination.
    62  func (p *Pipe) ConnectTo(p2 *Pipe) {
    63  	connectChans(p.Outgoing, p2.Outgoing)
    64  	connectChans(p2.Incoming, p.Incoming)
    65  }
    66  
    67  func connectChans(a, b chan NetMessage) {
    68  	go func() {
    69  		for {
    70  			m, more := <-a
    71  			if !more {
    72  				close(b)
    73  				return
    74  			}
    75  			b <- m
    76  		}
    77  	}()
    78  }