2016-04-04 11:48:39 +08:00
|
|
|
package metainfo
|
|
|
|
|
2016-05-02 09:21:03 +08:00
|
|
|
import (
|
|
|
|
"encoding/hex"
|
|
|
|
"fmt"
|
|
|
|
)
|
2016-04-04 11:48:39 +08:00
|
|
|
|
|
|
|
// 20-byte SHA1 hash used for info and pieces.
|
|
|
|
type Hash [20]byte
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (h Hash) Bytes() []byte {
|
|
|
|
return h[:]
|
2016-04-04 11:48:39 +08:00
|
|
|
}
|
|
|
|
|
2016-04-19 12:11:11 +08:00
|
|
|
func (h *Hash) AsString() string {
|
|
|
|
return string(h[:])
|
2016-04-04 11:48:39 +08:00
|
|
|
}
|
|
|
|
|
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) {
|
|
|
|
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
|
|
|
|
}
|