@cryptotaxi247 / kubo / commits / f94d6a37b

refactor(bitswap/message) use map to prevent duplicate entries

A nice invariant for bitswap sessions: Senders and receivers can trust that messages do not contain duplicate blocks or duplicate keys. Backing the message with a map enforces this invariant. This comes at the cost of O(n) getters.

Brian Tiger Chow committed Oct 27, 2014 at 06:04 UTC f94d6a37b657d7923c7e54453b6b685827bdc19c
1 file changed +11 -5
exchange/bitswap/message/message.go
+11 -5
@@ -28,12 +28,14 @@ type Exportable interface {
28
29 // message wraps a proto message for convenience
30 type message struct {
31 - wantlist []u.Key
31 + wantlist map[u.Key]struct{}
32 blocks []blocks.Block
33 }
34
35 -func New() *message {
36 - return new(message)
35 +func New() BitSwapMessage {
36 + return &message{
37 + wantlist: make(map[u.Key]struct{}),
38 + }
39 }
40
41 func newMessageFromProto(pbm pb.Message) BitSwapMessage {
@@ -50,7 +52,11 @@ func newMessageFromProto(pbm pb.Message) BitSwapMessage {
52
53 // TODO(brian): convert these into keys
54 func (m *message) Wantlist() []u.Key {
53 - return m.wantlist
55 + wl := make([]u.Key, 0)
56 + for k, _ := range m.wantlist {
57 + wl = append(wl, k)
58 + }
59 + return wl
60 }
61
62 // TODO(brian): convert these into blocks
@@ -59,7 +65,7 @@ func (m *message) Blocks() []blocks.Block {
65 }
66
67 func (m *message) AddWanted(k u.Key) {
62 - m.wantlist = append(m.wantlist, k)
68 + m.wantlist[k] = struct{}{}
69 }
70
71 func (m *message) AppendBlock(b blocks.Block) {