-
Notifications
You must be signed in to change notification settings - Fork 105
/
key.go
59 lines (48 loc) · 1.23 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
package key
import (
"bytes"
"strings"
"golang.org/x/exp/constraints"
"github.com/axelarnetwork/utils/convert"
)
// DefaultDelimiter represents the default delimiter used for the KV store keys when concatenating them together
const DefaultDelimiter = "_"
// Key provides a type safe way to interact with the store
type Key interface {
Append(Key) Key
Bytes(delimiter ...string) []byte
}
type basicKey struct {
particles [][]byte
}
func (k basicKey) Append(suffix Key) Key {
var bz [][]byte
switch suffix := suffix.(type) {
case basicKey:
bz = suffix.particles
default:
bz = [][]byte{suffix.Bytes()}
}
return basicKey{
particles: append(k.particles, bz...),
}
}
func (k basicKey) Bytes(delimiter ...string) []byte {
del := DefaultDelimiter
if len(delimiter) == 1 {
del = delimiter[0]
}
return bytes.Join(k.particles, []byte(del))
}
// FromBz creates a new Key from bytes
func FromBz(key []byte) Key {
return &basicKey{particles: [][]byte{key}}
}
// FromStr creates a new Key from a string
func FromStr(key string) Key {
return FromBz([]byte(strings.ToLower(key)))
}
// FromUInt creates a new Key from any unsigned integer type
func FromUInt[T constraints.Unsigned](key T) Key {
return FromBz(convert.IntToBytes[T](key))
}