This repository has been archived by the owner on Apr 29, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
key.go
86 lines (69 loc) · 2.01 KB
/
key.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 key
import (
"encoding/json"
"fmt"
ds "github.com/ipfs/go-datastore"
b58 "github.com/jbenet/go-base58"
mh "github.com/multiformats/go-multihash"
base32 "github.com/whyrusleeping/base32"
)
// Key is a string representation of multihash for use with maps.
type Key string
// String is utililty function for printing out keys as strings (Pretty).
func (k Key) String() string {
return k.B58String()
}
func (k Key) ToMultihash() mh.Multihash {
return mh.Multihash(k)
}
// B58String returns Key in a b58 encoded string
func (k Key) B58String() string {
return B58KeyEncode(k)
}
// B58KeyDecode returns Key from a b58 encoded string
func B58KeyDecode(s string) Key {
return Key(string(b58.Decode(s)))
}
// B58KeyEncode returns Key in a b58 encoded string
func B58KeyEncode(k Key) string {
return b58.Encode([]byte(k))
}
// DsKey returns a Datastore key
func (k Key) DsKey() ds.Key {
return ds.NewKey(base32.RawStdEncoding.EncodeToString([]byte(k)))
}
// UnmarshalJSON returns a JSON-encoded Key (string)
func (k *Key) UnmarshalJSON(mk []byte) error {
var s string
err := json.Unmarshal(mk, &s)
if err != nil {
return err
}
*k = Key(string(b58.Decode(s)))
if len(*k) == 0 && len(s) > 2 { // if b58.Decode fails, k == ""
return fmt.Errorf("Key.UnmarshalJSON: invalid b58 string: %v", mk)
}
return nil
}
// MarshalJSON returns a JSON-encoded Key (string)
func (k *Key) MarshalJSON() ([]byte, error) {
return json.Marshal(b58.Encode([]byte(*k)))
}
func (k *Key) Loggable() map[string]interface{} {
return map[string]interface{}{
"key": k.String(),
}
}
// KeyFromDsKey returns a Datastore key
func KeyFromDsKey(dsk ds.Key) (Key, error) {
dec, err := base32.RawStdEncoding.DecodeString(dsk.String()[1:])
if err != nil {
return "", err
}
return Key(dec), nil
}
// KeySlice is used for sorting Keys
type KeySlice []Key
func (es KeySlice) Len() int { return len(es) }
func (es KeySlice) Swap(i, j int) { es[i], es[j] = es[j], es[i] }
func (es KeySlice) Less(i, j int) bool { return es[i] < es[j] }