-
Notifications
You must be signed in to change notification settings - Fork 37
/
key.go
102 lines (82 loc) · 1.88 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package abi
import (
"bytes"
"encoding/binary"
"errors"
"github.com/filecoin-project/go-address"
"github.com/ipfs/go-cid"
)
// Keyer defines an interface required to put values in mapping.
type Keyer interface {
Key() string
}
// Adapts an address as a mapping key.
type AddrKey address.Address
func (k AddrKey) Key() string {
return string(address.Address(k).Bytes())
}
type IdAddrKey address.Address
func (k IdAddrKey) Key() string {
return string(address.Address(k).Payload())
}
// Adapts an address tuple as a mapping key.
type AddrPairKey struct {
First address.Address
Second address.Address
}
func (k *AddrPairKey) Key() string {
buf := new(bytes.Buffer)
_ = k.MarshalCBOR(buf)
return buf.String()
}
func NewAddrPairKey(first address.Address, second address.Address) *AddrPairKey {
return &AddrPairKey{
First: first,
Second: second,
}
}
type CidKey cid.Cid
func (k CidKey) Key() string {
return cid.Cid(k).KeyString()
}
// Adapts an int64 as a mapping key.
type intKey struct {
int64
}
//noinspection GoExportedFuncWithUnexportedType
func IntKey(k int64) intKey {
return intKey{k}
}
func (k intKey) Key() string {
buf := make([]byte, 10)
n := binary.PutVarint(buf, k.int64)
return string(buf[:n])
}
//noinspection GoUnusedExportedFunction
func ParseIntKey(k string) (int64, error) {
i, n := binary.Varint([]byte(k))
if n != len(k) {
return 0, errors.New("failed to decode varint key")
}
return i, nil
}
// Adapts a uint64 as a mapping key.
type uintKey struct {
uint64
}
//noinspection GoExportedFuncWithUnexportedType
func UIntKey(k uint64) uintKey {
return uintKey{k}
}
func (k uintKey) Key() string {
buf := make([]byte, 10)
n := binary.PutUvarint(buf, k.uint64)
return string(buf[:n])
}
func ParseUIntKey(k string) (uint64, error) {
i, n := binary.Uvarint([]byte(k))
if n != len(k) {
return 0, errors.New("failed to decode varint key")
}
return i, nil
}