2016-04-04 11:48:39 +08:00
|
|
|
package metainfo
|
|
|
|
|
2016-05-02 09:21:03 +08:00
|
|
|
import (
|
2016-05-03 19:34:20 +08:00
|
|
|
"crypto/sha1"
|
2021-01-04 10:37:44 +08:00
|
|
|
"encoding"
|
2016-05-02 09:21:03 +08:00
|
|
|
"encoding/hex"
|
|
|
|
"fmt"
|
|
|
|
)
|
2016-04-04 11:48:39 +08:00
|
|
|
|
2017-12-29 09:17:58 +08:00
|
|
|
const HashSize = 20
|
|
|
|
|
2016-04-04 11:48:39 +08:00
|
|
|
// 20-byte SHA1 hash used for info and pieces.
|
2017-12-29 09:17:58 +08:00
|
|
|
type Hash [HashSize]byte
|
2016-04-04 11:48:39 +08:00
|
|
|
|
2021-01-22 06:49:51 +08:00
|
|
|
var _ fmt.Formatter = (*Hash)(nil)
|
2020-11-11 12:31:55 +08:00
|
|
|
|
|
|
|
func (h Hash) Format(f fmt.State, c rune) {
|
|
|
|
// TODO: I can't figure out a nice way to just override the 'x' rune, since it's meaningless
|
|
|
|
// with the "default" 'v', or .String() already returning the hex.
|
|
|
|
f.Write([]byte(h.HexString()))
|
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (h Hash) Bytes() []byte {
|
|
|
|
return h[:]
|
2016-04-04 11:48:39 +08:00
|
|
|
}
|
|
|
|
|
2016-07-29 22:37:52 +08:00
|
|
|
func (h Hash) AsString() string {
|
2016-04-19 12:11:11 +08:00
|
|
|
return string(h[:])
|
2016-04-04 11:48:39 +08:00
|
|
|
}
|
|
|
|
|
2017-02-02 13:53:19 +08:00
|
|
|
func (h Hash) String() string {
|
|
|
|
return h.HexString()
|
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (h Hash) HexString() string {
|
|
|
|
return fmt.Sprintf("%x", h[:])
|
2016-04-04 11:48:39 +08:00
|
|
|
}
|
2016-05-02 09:21:03 +08:00
|
|
|
|
|
|
|
func (h *Hash) FromHexString(s string) (err error) {
|
2017-12-29 09:17:58 +08:00
|
|
|
if len(s) != 2*HashSize {
|
2016-05-02 09:21:03 +08:00
|
|
|
err = fmt.Errorf("hash hex string has bad length: %d", len(s))
|
|
|
|
return
|
|
|
|
}
|
|
|
|
n, err := hex.Decode(h[:], []byte(s))
|
|
|
|
if err != nil {
|
|
|
|
return
|
|
|
|
}
|
2017-12-29 09:17:58 +08:00
|
|
|
if n != HashSize {
|
2016-05-02 09:21:03 +08:00
|
|
|
panic(n)
|
|
|
|
}
|
|
|
|
return
|
|
|
|
}
|
2016-05-03 19:34:20 +08:00
|
|
|
|
2021-01-22 06:49:51 +08:00
|
|
|
var (
|
|
|
|
_ encoding.TextUnmarshaler = (*Hash)(nil)
|
|
|
|
_ encoding.TextMarshaler = Hash{}
|
|
|
|
)
|
|
|
|
|
2021-01-04 10:37:44 +08:00
|
|
|
func (h *Hash) UnmarshalText(b []byte) error {
|
|
|
|
return h.FromHexString(string(b))
|
|
|
|
}
|
2021-01-22 06:49:51 +08:00
|
|
|
func (h Hash) MarshalText() (text []byte, err error) {
|
|
|
|
return []byte(h.HexString()), nil
|
|
|
|
}
|
2021-01-04 10:37:44 +08:00
|
|
|
|
2016-06-21 00:35:53 +08:00
|
|
|
func NewHashFromHex(s string) (h Hash) {
|
2017-01-01 07:07:05 +08:00
|
|
|
err := h.FromHexString(s)
|
|
|
|
if err != nil {
|
|
|
|
panic(err)
|
|
|
|
}
|
2016-06-21 00:35:53 +08:00
|
|
|
return
|
|
|
|
}
|
|
|
|
|
2016-05-03 19:34:20 +08:00
|
|
|
func HashBytes(b []byte) (ret Hash) {
|
|
|
|
hasher := sha1.New()
|
|
|
|
hasher.Write(b)
|
|
|
|
copy(ret[:], hasher.Sum(nil))
|
|
|
|
return
|
|
|
|
}
|