mirror of
https://github.com/GopeedLab/gopeed.git
synced 2026-11-15 04:43:41 +00:00
refactor: message entity
This commit is contained in:
1 parent
1d2f38d7ae
commit
d6d411f48c
12 files changed
+167
-151
No files matched your search
@@ -4,38 +4,39 @@ import "encoding/binary"
|
||||
|
||||
// piece: <len=0009+X><id=7><index><begin><block>
|
||||
type Piece struct {
|
||||
*Message
|
||||
*base
|
||||
Index uint32
|
||||
Begin uint32
|
||||
Block []byte
|
||||
}
|
||||
|
||||
func NewPiece(index uint32, begin uint32, block []byte) *Piece {
|
||||
func NewPiece() *Piece {
|
||||
return &Piece{
|
||||
Message: &Message{
|
||||
Length: 9 + uint32(len(block)),
|
||||
ID: IdPiece,
|
||||
base: &base{
|
||||
id: IdPiece,
|
||||
},
|
||||
Index: index,
|
||||
Begin: begin,
|
||||
// Block: io.LimitReader(reader, int64(length)),
|
||||
Block: block,
|
||||
}
|
||||
}
|
||||
|
||||
func (p *Piece) Encode() []byte {
|
||||
buf := make([]byte, 8)
|
||||
binary.BigEndian.PutUint32(buf[:4], p.Index)
|
||||
binary.BigEndian.PutUint32(buf[4:8], p.Begin)
|
||||
buf = append(buf, p.Block...)
|
||||
return append(p.Message.Encode(), buf...)
|
||||
func BuildPiece(index uint32, begin uint32, block []byte) *Piece {
|
||||
piece := NewPiece()
|
||||
piece.Index = index
|
||||
piece.Begin = begin
|
||||
piece.Block = block
|
||||
return piece
|
||||
|
||||
}
|
||||
|
||||
func (p *Piece) Decode(buf []byte) Serialize {
|
||||
p.Message = &Message{}
|
||||
p.Message.Decode(buf)
|
||||
p.Index = binary.BigEndian.Uint32(buf[5:9])
|
||||
p.Begin = binary.BigEndian.Uint32(buf[9:13])
|
||||
p.Block = buf[13:]
|
||||
return p
|
||||
func (p *Piece) Encode() []byte {
|
||||
buf := make([]byte, 8+len(p.Block))
|
||||
binary.BigEndian.PutUint32(buf[0:4], p.Index)
|
||||
binary.BigEndian.PutUint32(buf[4:8], p.Begin)
|
||||
copy(buf[8:], p.Block)
|
||||
return encode(p.base, buf)
|
||||
}
|
||||
|
||||
func (p *Piece) Decode(buf []byte) {
|
||||
p.Index = binary.BigEndian.Uint32(buf[0:4])
|
||||
p.Begin = binary.BigEndian.Uint32(buf[4:8])
|
||||
p.Block = buf[8:]
|
||||
}
|
||||
Reference in new issue
Block a user