aboutsummaryrefslogtreecommitdiff
path: root/meta/piece.go
blob: 3878818ae8fc639b95aa59d2ded02a1e260262c2 (plain)
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
package meta

import (
	"crypto/sha1"

	"dim13.org/btget/bencode"
)

type Piece [sha1.Size]byte

func (p Piece) Check(b []byte) bool {
	return sha1.Sum(b) == p
}

type Pieces []Piece

func (p *Pieces) UnmarshalBencode(b []byte) (int, error) {
	var tmp []byte
	n, err := bencode.Unmarshal(b, &tmp)
	if err != nil {
		return 0, err
	}
	count := len(tmp) / sha1.Size
	*p = make(Pieces, count)
	for i := 0; i < count; i++ {
		off := i * sha1.Size
		copy((*p)[i][:], tmp[off:off+sha1.Size])
	}
	return n, nil
}