Commit a68d9310 authored by Brian Tiger Chow's avatar Brian Tiger Chow

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.
parent 6db72127
...@@ -28,12 +28,14 @@ type Exportable interface { ...@@ -28,12 +28,14 @@ type Exportable interface {
// message wraps a proto message for convenience // message wraps a proto message for convenience
type message struct { type message struct {
wantlist []u.Key wantlist map[u.Key]struct{}
blocks []blocks.Block blocks []blocks.Block
} }
func New() *message { func New() BitSwapMessage {
return new(message) return &message{
wantlist: make(map[u.Key]struct{}),
}
} }
func newMessageFromProto(pbm pb.Message) BitSwapMessage { func newMessageFromProto(pbm pb.Message) BitSwapMessage {
...@@ -50,7 +52,11 @@ func newMessageFromProto(pbm pb.Message) BitSwapMessage { ...@@ -50,7 +52,11 @@ func newMessageFromProto(pbm pb.Message) BitSwapMessage {
// TODO(brian): convert these into keys // TODO(brian): convert these into keys
func (m *message) Wantlist() []u.Key { func (m *message) Wantlist() []u.Key {
return m.wantlist wl := make([]u.Key, 0)
for k, _ := range m.wantlist {
wl = append(wl, k)
}
return wl
} }
// TODO(brian): convert these into blocks // TODO(brian): convert these into blocks
...@@ -59,7 +65,7 @@ func (m *message) Blocks() []blocks.Block { ...@@ -59,7 +65,7 @@ func (m *message) Blocks() []blocks.Block {
} }
func (m *message) AddWanted(k u.Key) { func (m *message) AddWanted(k u.Key) {
m.wantlist = append(m.wantlist, k) m.wantlist[k] = struct{}{}
} }
func (m *message) AppendBlock(b blocks.Block) { func (m *message) AppendBlock(b blocks.Block) {
......
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment