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:
@ -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 {
|
|||||||
|
|
||||||
// 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 {
|
|||||||
}
|
}
|
||||||
|
|
||||||
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) {
|
||||||
|
Reference in New Issue
Block a user