-
Notifications
You must be signed in to change notification settings - Fork 24
/
key.go
48 lines (39 loc) · 1.1 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
package shard
import (
"encoding/json"
"github.com/ipfs/go-cid"
"github.com/mr-tron/base58"
)
// Key represents a shard key. It can be instantiated from a string, a byte
// slice, or a CID.
type Key struct {
// str stores a string or an arbitrary byte slice in base58 form. We cannot
// store the raw byte slice because this struct needs to be comparable.
str string
}
// KeyFromString returns a key representing an arbitrary string.
func KeyFromString(str string) Key {
return Key{str: str}
}
// KeyFromBytes returns a key from a byte slice, encoding it in b58 first.
func KeyFromBytes(b []byte) Key {
return Key{str: base58.Encode(b)}
}
// KeyFromCID returns a key representing a CID.
func KeyFromCID(cid cid.Cid) Key {
return Key{str: cid.String()}
}
// String returns the string representation for this key.
func (k Key) String() string {
return k.str
}
//
// We need a custom JSON marshaller and unmarshaller because str is a
// private field
//
func (k Key) MarshalJSON() ([]byte, error) {
return json.Marshal(k.str)
}
func (k *Key) UnmarshalJSON(bz []byte) error {
return json.Unmarshal(bz, &k.str)
}