Message.go 1.45 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
	peer "github.com/jbenet/go-ipfs/peer"
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
6
	u "github.com/jbenet/go-ipfs/util"
Jeromy's avatar
Jeromy committed
7 8
)

Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
9 10 11 12 13 14 15 16 17
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
18
func peerToPBPeer(p *peer.Peer) *Message_Peer {
19
	pbp := new(Message_Peer)
Jeromy's avatar
Jeromy committed
20 21 22
	if len(p.Addresses) == 0 || p.Addresses[0] == nil {
		pbp.Addr = proto.String("")
	} else {
23
		addr := p.Addresses[0].String()
Jeromy's avatar
Jeromy committed
24
		pbp.Addr = &addr
Jeromy's avatar
Jeromy committed
25 26 27 28
	}
	pid := string(p.ID)
	pbp.Id = &pid
	return pbp
29 30
}

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

39 40 41
// 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
42
func (m *Message) GetClusterLevel() int {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
43 44
	level := m.GetClusterLevelRaw() - 1
	if level < 0 {
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
45
		u.DErr("GetClusterLevel: no routing level specified, assuming 0\n")
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
46 47
		level = 0
	}
Juan Batiz-Benet's avatar
Juan Batiz-Benet committed
48
	return int(level)
49
}
50

51 52 53
// 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
54 55 56
func (m *Message) SetClusterLevel(level int) {
	lvl := int32(level)
	m.ClusterLevelRaw = &lvl
57
}