]> Sergey Matveev's repositories - btrtrc.git/commitdiff
Add metainfo.Hash.FromHexString
authorMatt Joiner <anacrolix@gmail.com>
Mon, 2 May 2016 01:21:03 +0000 (11:21 +1000)
committerMatt Joiner <anacrolix@gmail.com>
Mon, 2 May 2016 01:21:03 +0000 (11:21 +1000)
metainfo/hash.go

index 46cb3e8d09df3e198cc0a4c9e41a05d2d1ad87c8..58c5b7cc185b950193cf1407b9ff8d9785e124e3 100644 (file)
@@ -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
+}