From 7044161faad877dd8a764b485b856ddb2a450167 Mon Sep 17 00:00:00 2001 From: Matt Joiner Date: Mon, 2 May 2016 11:21:03 +1000 Subject: [PATCH] Add metainfo.Hash.FromHexString --- metainfo/hash.go | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/metainfo/hash.go b/metainfo/hash.go index 46cb3e8d..58c5b7cc 100644 --- a/metainfo/hash.go +++ b/metainfo/hash.go @@ -1,6 +1,9 @@ package metainfo -import "fmt" +import ( + "encoding/hex" + "fmt" +) // 20-byte SHA1 hash used for info and pieces. type Hash [20]byte @@ -16,3 +19,18 @@ func (h *Hash) AsString() string { func (h Hash) HexString() string { return fmt.Sprintf("%x", h[:]) } + +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 +}