It wasn't possible to move Client.WriteStatus to an external package to verify it doesn't depend on same-package access to data because then it can't be used in the tests, and it's extremely useful there. So I've settled for not locking the Client, and trying to use all the public methods. It's a work in progress.
50 lines
756 B
Go
50 lines
756 B
Go
package metainfo
|
|
|
|
import (
|
|
"crypto/sha1"
|
|
"encoding/hex"
|
|
"fmt"
|
|
)
|
|
|
|
// 20-byte SHA1 hash used for info and pieces.
|
|
type Hash [20]byte
|
|
|
|
func (h Hash) Bytes() []byte {
|
|
return h[:]
|
|
}
|
|
|
|
func (h Hash) AsString() string {
|
|
return string(h[:])
|
|
}
|
|
|
|
func (h Hash) HexString() string {
|
|
return fmt.Sprintf("%x", h[:])
|
|
}
|
|
|
|
func (h *Hash) FromHexString(s string) (err error) {
|
|
if len(s) != 40 {
|
|
err = fmt.Errorf("hash hex string has bad length: %d", len(s))
|
|
return
|
|
}
|
|
n, err := hex.Decode(h[:], []byte(s))
|
|
if err != nil {
|
|
return
|
|
}
|
|
if n != 20 {
|
|
panic(n)
|
|
}
|
|
return
|
|
}
|
|
|
|
func NewHashFromHex(s string) (h Hash) {
|
|
h.FromHexString(s)
|
|
return
|
|
}
|
|
|
|
func HashBytes(b []byte) (ret Hash) {
|
|
hasher := sha1.New()
|
|
hasher.Write(b)
|
|
copy(ret[:], hasher.Sum(nil))
|
|
return
|
|
}
|