aboutsummaryrefslogtreecommitdiff
path: root/meta/piece.go
blob: ee39d361798923e6c2af1109c10e20cbe7c50b8f (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
31
32
33
34
35
36
37
package meta

import (
	"crypto/sha1"
	"fmt"

	"dim13.org/btget/bencode"
)

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
}

type Piece [sha1.Size]byte

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

type Percent float64

func (p Percent) String() string {
	return fmt.Sprintf("%6.2f%%", p)
}