-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpiece_storage.go
62 lines (51 loc) · 1.11 KB
/
piece_storage.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package main
import (
"hash"
"log"
"github.com/a-pavlov/ged2k/proto"
)
type ReceivingPiece struct {
hash hash.Hash
blocks []*PendingBlock
hashBlockIndex int
}
func (rp *ReceivingPiece) InsertBlock(pb *PendingBlock) bool {
skipBlocks := 0
for _, x := range rp.blocks {
if x.block.BlockIndex == pb.block.BlockIndex {
return false
}
if x.block.BlockIndex < pb.block.BlockIndex {
skipBlocks++
} else {
break
}
}
log.Println("skip blocks", skipBlocks)
switch skipBlocks {
case 0:
rp.blocks = append([]*PendingBlock{pb}, rp.blocks...)
case len(rp.blocks):
rp.blocks = append(rp.blocks, pb)
default:
rp.blocks = append(rp.blocks[:skipBlocks+1], rp.blocks[skipBlocks:]...)
rp.blocks[skipBlocks] = pb
}
for _, x := range rp.blocks {
// skip blocks with index less than start hashing
if x.block.BlockIndex < rp.hashBlockIndex {
continue
}
if rp.hashBlockIndex != x.block.BlockIndex {
break
}
rp.hash.Write(x.data)
rp.hashBlockIndex++
}
return true
}
func (rp *ReceivingPiece) Hash() proto.ED2KHash {
h := proto.ED2KHash{}
rp.hash.Sum(h[:0])
return h
}