1
0
mirror of https://github.com/ipfs/kubo.git synced 2025-07-01 02:30:39 +08:00

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.
This commit is contained in:
Brian Tiger Chow
2014-10-27 06:04:09 -07:00
parent 842b910853
commit f94d6a37b6

View File

@ -28,12 +28,14 @@ type Exportable interface {
// message wraps a proto message for convenience
type message struct {
wantlist []u.Key
wantlist map[u.Key]struct{}
blocks []blocks.Block
}
func New() *message {
return new(message)
func New() BitSwapMessage {
return &message{
wantlist: make(map[u.Key]struct{}),
}
}
func newMessageFromProto(pbm pb.Message) BitSwapMessage {
@ -50,7 +52,11 @@ func newMessageFromProto(pbm pb.Message) BitSwapMessage {
// TODO(brian): convert these into keys
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
@ -59,7 +65,7 @@ func (m *message) Blocks() []blocks.Block {
}
func (m *message) AddWanted(k u.Key) {
m.wantlist = append(m.wantlist, k)
m.wantlist[k] = struct{}{}
}
func (m *message) AppendBlock(b blocks.Block) {