Message.go 1.41 KB
Newer Older
1 2
package dht

Jeromy's avatar
Jeromy committed
3
import (
4
	"github.com/jbenet/go-ipfs/Godeps/_workspace/src/code.google.com/p/goprotobuf/proto"
Jeromy's avatar
Jeromy committed
5 6 7
	peer "github.com/jbenet/go-ipfs/peer"
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
8 9 10 11 12 13 14 15 16
func newMessage(typ Message_MessageType, key string, level int) *Message {
	m := &Message{
		Type: &typ,
		Key:  &key,
	}
	m.SetClusterLevel(level)
	return m
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
17
func peerToPBPeer(p *peer.Peer) *Message_Peer {
18
	pbp := new(Message_Peer)
Jeromy's avatar
Jeromy committed
19 20 21
	if len(p.Addresses) == 0 || p.Addresses[0] == nil {
		pbp.Addr = proto.String("")
	} else {
22
		addr := p.Addresses[0].String()
Jeromy's avatar
Jeromy committed
23
		pbp.Addr = &addr
Jeromy's avatar
Jeromy committed
24 25 26 27
	}
	pid := string(p.ID)
	pbp.Id = &pid
	return pbp
28 29
}

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
30
func peersToPBPeers(peers []*peer.Peer) []*Message_Peer {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
31
	pbpeers := make([]*Message_Peer, len(peers))
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
32 33 34 35 36 37
	for i, p := range peers {
		pbpeers[i] = peerToPBPeer(p)
	}
	return pbpeers
}

38 39 40
// GetClusterLevel gets and adjusts the cluster level on the message.
// a +/- 1 adjustment is needed to distinguish a valid first level (1) and
// default "no value" protobuf behavior (0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
41
func (m *Message) GetClusterLevel() int {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
42 43
	level := m.GetClusterLevelRaw() - 1
	if level < 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
44
		log.Debug("GetClusterLevel: no routing level specified, assuming 0")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
45 46
		level = 0
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
47
	return int(level)
48
}
49

50 51 52
// SetClusterLevel adjusts and sets the cluster level on the message.
// a +/- 1 adjustment is needed to distinguish a valid first level (1) and
// default "no value" protobuf behavior (0)
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
53 54 55
func (m *Message) SetClusterLevel(level int) {
	lvl := int32(level)
	m.ClusterLevelRaw = &lvl
56
}