12 // 20-byte SHA1 hash used for info and pieces.
13 type Hash [HashSize]byte
15 var _ fmt.Formatter = (*Hash)(nil)
17 func (h Hash) Format(f fmt.State, c rune) {
18 // TODO: I can't figure out a nice way to just override the 'x' rune, since it's meaningless
19 // with the "default" 'v', or .String() already returning the hex.
20 f.Write([]byte(h.HexString()))
23 func (h Hash) Bytes() []byte {
27 func (h Hash) AsString() string {
31 func (h Hash) String() string {
35 func (h Hash) HexString() string {
36 return fmt.Sprintf("%x", h[:])
39 func (h *Hash) FromHexString(s string) (err error) {
40 if len(s) != 2*HashSize {
41 err = fmt.Errorf("hash hex string has bad length: %d", len(s))
44 n, err := hex.Decode(h[:], []byte(s))
55 _ encoding.TextUnmarshaler = (*Hash)(nil)
56 _ encoding.TextMarshaler = Hash{}
59 func (h *Hash) UnmarshalText(b []byte) error {
60 return h.FromHexString(string(b))
63 func (h Hash) MarshalText() (text []byte, err error) {
64 return []byte(h.HexString()), nil
67 func NewHashFromHex(s string) (h Hash) {
68 err := h.FromHexString(s)
75 func HashBytes(b []byte) (ret Hash) {
78 copy(ret[:], hasher.Sum(nil))