kubo/net/message/message.go
Brian Tiger Chow 4c95eb15b2 refactor(net:message) add NetMessage interface
* Design Goal: reduce coupling
* NB: Slices hold references to an underlying array, and if you assign
  one slice to another, both refer to the same array. If a function
  takes a slice argument, changes it makes to the elements of the slice
  will be visible to the caller, analogous to passing a pointer to the
  underlying array.
2014-09-12 17:58:12 -07:00

61 lines
1.2 KiB
Go

package message
import (
peer "github.com/jbenet/go-ipfs/peer"
proto "code.google.com/p/goprotobuf/proto"
)
type NetMessage interface {
Peer() *peer.Peer
Data() []byte
}
func New(p *peer.Peer, data []byte) NetMessage {
return &message{peer: p, data: data}
}
// message represents a packet of information sent to or received from a
// particular Peer.
type message struct {
// To or from, depending on direction.
peer *peer.Peer
// Opaque data
data []byte
}
func (m *message) Peer() *peer.Peer {
return m.peer
}
func (m *message) Data() []byte {
return m.data
}
// FromObject creates a message from a protobuf-marshallable message.
func FromObject(p *peer.Peer, data proto.Message) (*message, error) {
bytes, err := proto.Marshal(data)
if err != nil {
return nil, err
}
return &message{
peer: p,
data: bytes,
}, nil
}
// Pipe objects represent a bi-directional message channel.
type Pipe struct {
Incoming chan NetMessage
Outgoing chan NetMessage
}
// NewPipe constructs a pipe with channels of a given buffer size.
func NewPipe(bufsize int) *Pipe {
return &Pipe{
Incoming: make(chan NetMessage, bufsize),
Outgoing: make(chan NetMessage, bufsize),
}
}