-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsha.go
70 lines (59 loc) · 1.1 KB
/
sha.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
package g
import (
"bytes"
"encoding/hex"
"fmt"
)
type (
Sha struct {
set bool
hash [20]byte
}
)
// NewSha creates a Sha from either a binary or hex encoded byte slice
func NewSha(b []byte) (Sha, error) {
if len(b) == 40 {
s := Sha{set: true}
_, _ = hex.Decode(s.hash[:], b)
return s, nil
}
if len(b) == 20 {
s := Sha{set: true}
copy(s.hash[:], b)
return s, nil
}
return Sha{}, fmt.Errorf("invalid sha %s", b)
}
func ShaFromHexString(s string) (Sha, error) {
v, err := hex.DecodeString(s)
if err != nil {
return Sha{}, err
}
return NewSha(v)
}
func (s Sha) Matches(ss Sha) bool {
return bytes.Equal(s.hash[:], ss.hash[:])
}
func (s Sha) String() string {
return s.AsHexString()
}
func (s Sha) IsSet() bool {
return s.set
}
func (s Sha) AsHexString() string {
return hex.EncodeToString(s.hash[:])
}
func (s Sha) AsHexBytes() []byte {
b := make([]byte, 40)
hex.Encode(b, s.hash[:])
return b
}
func (s Sha) AsArray() [20]byte {
var r [20]byte
copy(r[:], s.hash[:])
return r
}
// AsByteSlice returns a Sha as a byte slice
func (s Sha) AsByteSlice() []byte {
return s.hash[:]
}