FedP2P/metainfo/hash.go

75 lines
1.3 KiB
Go
Raw Normal View History

package metainfo
2016-05-02 09:21:03 +08:00
import (
2016-05-03 19:34:20 +08:00
"crypto/sha1"
"encoding"
2016-05-02 09:21:03 +08:00
"encoding/hex"
"fmt"
)
const HashSize = 20
// 20-byte SHA1 hash used for info and pieces.
type Hash [HashSize]byte
var (
_ fmt.Formatter = (*Hash)(nil)
_ encoding.TextUnmarshaler = (*Hash)(nil)
)
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()))
}
func (h Hash) Bytes() []byte {
return h[:]
}
func (h Hash) AsString() string {
return string(h[:])
}
func (h Hash) String() string {
return h.HexString()
}
func (h Hash) HexString() string {
return fmt.Sprintf("%x", h[:])
}
2016-05-02 09:21:03 +08:00
func (h *Hash) FromHexString(s string) (err error) {
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
}
if n != HashSize {
2016-05-02 09:21:03 +08:00
panic(n)
}
return
}
2016-05-03 19:34:20 +08:00
func (h *Hash) UnmarshalText(b []byte) error {
return h.FromHexString(string(b))
}
2016-06-21 00:35:53 +08:00
func NewHashFromHex(s string) (h Hash) {
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
}