-
Notifications
You must be signed in to change notification settings - Fork 0
/
hash.go
63 lines (50 loc) · 1.07 KB
/
hash.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
// Copyright 2021 The June Authors. All rights reserved.
// Use of this source code is governed by Apache License
// that can be found in the LICENSE file.
package key
import (
"crypto/sha256"
"encoding/hex"
"fmt"
"hash"
"github.com/reusee/e5"
"github.com/reusee/sb"
)
const HashSize = 32
type Hash [HashSize]byte
func (h Hash) String() string {
return hex.EncodeToString(h[:])
}
var emptyHash = Hash{}
func (h Hash) Valid() bool {
return h != emptyHash
}
func HashFromString(str string) (hash Hash, err error) {
defer he(&err)
var bs []byte
bs, err = hex.DecodeString(str)
ce(err)
if len(bs) > len(hash) {
ce(ErrTooLong, e5.With(fmt.Errorf("string: %s", str)))
}
copy(hash[:], bs)
return
}
type NewHashState func() hash.Hash
func (_ Def) NewHashState() NewHashState {
return newHashState
}
func newHashState() hash.Hash {
return sha256.New()
}
func HashValue(value any) (ret Hash, err error) {
hash := make([]byte, HashSize)
if err = sb.Copy(
sb.Marshal(value),
sb.Hash(newHashState, &hash, nil),
); err != nil {
return
}
copy(ret[:], hash)
return
}