2016-04-04 03:48:39 +00:00
|
|
|
package metainfo
|
|
|
|
|
2016-05-02 01:21:03 +00:00
|
|
|
import (
|
2016-05-03 11:34:20 +00:00
|
|
|
"crypto/sha1"
|
2016-05-02 01:21:03 +00:00
|
|
|
"encoding/hex"
|
|
|
|
"fmt"
|
|
|
|
)
|
2016-04-04 03:48:39 +00:00
|
|
|
|
|
|
|
// 20-byte SHA1 hash used for info and pieces.
|
|
|
|
type Hash [20]byte
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (h Hash) Bytes() []byte {
|
|
|
|
return h[:]
|
2016-04-04 03:48:39 +00:00
|
|
|
}
|
|
|
|
|
2016-07-29 14:37:52 +00:00
|
|
|
func (h Hash) AsString() string {
|
2016-04-19 04:11:11 +00:00
|
|
|
return string(h[:])
|
2016-04-04 03:48:39 +00:00
|
|
|
}
|
|
|
|
|
2017-02-02 05:53:19 +00:00
|
|
|
func (h Hash) String() string {
|
|
|
|
return h.HexString()
|
|
|
|
}
|
|
|
|
|
2016-04-19 04:11:11 +00:00
|
|
|
func (h Hash) HexString() string {
|
|
|
|
return fmt.Sprintf("%x", h[:])
|
2016-04-04 03:48:39 +00:00
|
|
|
}
|
2016-05-02 01:21:03 +00:00
|
|
|
|
|
|
|
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
|
|
|
|
}
|
2016-05-03 11:34:20 +00:00
|
|
|
|
2016-06-20 16:35:53 +00:00
|
|
|
func NewHashFromHex(s string) (h Hash) {
|
2016-12-31 23:07:05 +00:00
|
|
|
err := h.FromHexString(s)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2016-06-20 16:35:53 +00:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-05-03 11:34:20 +00:00
|
|
|
func HashBytes(b []byte) (ret Hash) {
|
|
|
|
hasher := sha1.New()
|
|
|
|
hasher.Write(b)
|
|
|
|
copy(ret[:], hasher.Sum(nil))
|
|
|
|
return
|
|
|
|
}
|