fix(bitswap) preserve ordering in bitswap message
Brian Tiger Chow committed
Oct 27, 2014 at 22:39 UTC
edf99f5e2025cd92ce95a2ba73eee28c2ddf3c77
1 file changed
+13
-12
exchange/bitswap/message/message.go
+13
-12
@@ -27,14 +27,16 @@ type Exportable interface {
27
}
28
29
type impl struct {
30
- wantlist map[u.Key]struct{}
31
- blocks map[u.Key]blocks.Block
30
+ existsInWantlist map[u.Key]struct{} // map to detect duplicates
31
+ wantlist []u.Key // slice to preserve ordering
32
+ blocks map[u.Key]blocks.Block // map to detect duplicates
33
}
34
35
func New() BitSwapMessage {
36
return &impl{
36
- wantlist: make(map[u.Key]struct{}),
37
- blocks: make(map[u.Key]blocks.Block),
37
+ blocks: make(map[u.Key]blocks.Block),
38
+ existsInWantlist: make(map[u.Key]struct{}),
39
+ wantlist: make([]u.Key, 0),
40
}
41
}
42
@@ -50,16 +52,10 @@ func newMessageFromProto(pbm pb.Message) BitSwapMessage {
52
return m
53
}
54
53
-// TODO(brian): convert these into keys
55
func (m *impl) Wantlist() []u.Key {
55
- wl := make([]u.Key, 0)
56
- for k, _ := range m.wantlist {
57
- wl = append(wl, k)
58
- }
59
- return wl
56
+ return m.wantlist
57
}
58
62
-// TODO(brian): convert these into blocks
59
func (m *impl) Blocks() []blocks.Block {
60
bs := make([]blocks.Block, 0)
61
for _, block := range m.blocks {
@@ -69,7 +65,12 @@ func (m *impl) Blocks() []blocks.Block {
65
}
66
67
func (m *impl) AddWanted(k u.Key) {
72
- m.wantlist[k] = struct{}{}
68
+ _, exists := m.existsInWantlist[k]
69
+ if exists {
70
+ return
71
+ }
72
+ m.existsInWantlist[k] = struct{}{}
73
+ m.wantlist = append(m.wantlist, k)
74
}
75
76
func (m *impl) AddBlock(b blocks.Block) {