-
Notifications
You must be signed in to change notification settings - Fork 0
/
digest.go
86 lines (74 loc) · 1.65 KB
/
digest.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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package mint
import (
"encoding/json"
"fmt"
)
// DigestSize is digest length in bytes
const DigestSize = 32
// Digest bytes
type Digest [DigestSize]byte
// Bytes of the instance
func (d Digest) Bytes() []byte {
b := make([]byte, len(d[:]))
copy(b, d[:])
return b
}
// String packs the instance into a Base58 string
func (d Digest) String() string {
return Pack58(d[:])
}
// StringMask packs the instance into 6+4 a masked Base58 string
func (d Digest) StringMask() string {
return MaskString6P4(d.String())
}
// MarshalJSON impl
func (d Digest) MarshalJSON() ([]byte, error) {
return json.Marshal(d.String())
}
// UnmarshalJSON impl
func (d *Digest) UnmarshalJSON(b []byte) error {
var s string
if err := json.Unmarshal(b, &s); err != nil {
return err
}
x, err := ParseDigest(s)
if err != nil {
return err
}
copy(d[:], x[:])
return nil
}
// ParseDigest parses an instance from Base58 string
func ParseDigest(s string) (Digest, error) {
var v Digest
b, err := Unpack58(s)
if err != nil {
return v, err
}
return BytesToDigest(b)
}
// MustParseDigest parses an instance from Base58 string or panics
func MustParseDigest(s string) Digest {
v, err := ParseDigest(s)
if err != nil {
panic(err)
}
return v
}
// BytesToDigest creates an instance from a bytes slice
func BytesToDigest(b []byte) (Digest, error) {
var v Digest
if len(b) != DigestSize {
return v, fmt.Errorf("invalid length, got %v expected %v", len(b), DigestSize)
}
copy(v[:], b)
return v, nil
}
// MustBytesToDigest creates an instance from bytes slice or panics
func MustBytesToDigest(b []byte) Digest {
v, err := BytesToDigest(b)
if err != nil {
panic(err)
}
return v
}