This repository has been archived by the owner on May 13, 2024. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 30
/
map.go
214 lines (185 loc) · 4.72 KB
/
map.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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
package bind
import (
"crypto/sha256"
"fmt"
"io"
"math/big"
"time"
"blockwatch.cc/tzgo/micheline"
"blockwatch.cc/tzgo/tezos"
"github.com/pkg/errors"
)
// Map is a map type used to interact with Tezos smart contracts.
//
// Go's map type cannot be used in this context, because the "comparable"
// types are different in Go and in Tezos specification.
type Map[K, V any] struct {
m map[hashType]MapEntry[K, V]
hashFunc func(any) hashType
}
type MapEntry[K, V any] struct {
Key K
Value V
}
func MakeMap[K, V any](size ...int) Map[K, V] {
h := hashFunc(zero[K]())
if len(size) > 0 {
return Map[K, V]{
m: make(map[hashType]MapEntry[K, V], size[0]),
hashFunc: h,
}
}
return Map[K, V]{
m: make(map[hashType]MapEntry[K, V]),
hashFunc: h,
}
}
func (m *Map[K, V]) Get(key K) (V, bool) {
value, ok := m.m[m.hashFunc(key)]
return value.Value, ok
}
func (m *Map[K, V]) Set(key K, value V) {
m.m[m.hashFunc(key)] = MapEntry[K, V]{Key: key, Value: value}
}
func (m *Map[K, V]) Entries() []MapEntry[K, V] {
entries := make([]MapEntry[K, V], 0, len(m.m))
for _, e := range m.m {
entries = append(entries, e)
}
return entries
}
func (m Map[K, V]) MarshalPrim(optimized bool) (micheline.Prim, error) {
entries := make([]micheline.Prim, 0, len(m.m))
for _, e := range m.m {
keyPrim, err := MarshalPrim(e.Key, optimized)
if err != nil {
return micheline.Prim{}, errors.Wrap(err, "failed to marshal key")
}
valuePrim, err := MarshalPrim(e.Value, optimized)
if err != nil {
return micheline.Prim{}, errors.Wrap(err, "failed to marshal value")
}
entries = append(entries, micheline.NewCode(micheline.D_ELT, keyPrim, valuePrim))
}
return micheline.NewSeq(entries...), nil
}
func (m *Map[K, V]) UnmarshalPrim(prim micheline.Prim) error {
if prim.Type != micheline.PrimSequence {
return errors.Errorf("invalid micheline type for Map: %s", prim.Type)
}
*m = MakeMap[K, V](len(prim.Args))
for _, entry := range prim.Args {
if entry.OpCode != micheline.D_ELT {
return errors.Errorf("map entries should be ELT, got %s", prim.OpCode)
}
if len(entry.Args) != 2 {
return errors.New("prim ELT should have 2 args")
}
var key K
var value V
if err := UnmarshalPrim(entry.Args[0], &key); err != nil {
return errors.Wrap(err, "failed to unmarshal key")
}
if err := UnmarshalPrim(entry.Args[1], &value); err != nil {
return errors.Wrap(err, "failed to unmarshal value")
}
m.Set(key, value)
}
return nil
}
func (m Map[K, V]) Format(f fmt.State, verb rune) {
vSharp := verb == 'v' && f.Flag('#')
if vSharp {
// Write the entire Map type with %#v
_, _ = fmt.Fprintf(f, "bind.Map[%T]%T", zero[K](), zero[V]())
// Special case if m is nil: we print (nil) instead of {nil}
if m.m == nil {
_, _ = io.WriteString(f, "(nil)")
return // we can return here
} else {
_, _ = f.Write([]byte{'{'})
}
} else {
_, _ = io.WriteString(f, "bind.Map[")
}
// Begin of content
first := true
for _, e := range m.m {
if first {
first = false
} else {
_, _ = f.Write([]byte{' '})
}
_, _ = fmt.Fprintf(f, "%v:%v", e.Key, e.Value)
}
// End of content
if vSharp {
_, _ = f.Write([]byte{'}'})
} else {
_, _ = f.Write([]byte{']'})
}
}
type hashType [sha256.Size]byte
// hashFunc
//
// Allowed types:
// - string
// - []byte
// - bool
// - *big.Int
// - time.Time
// - tezos.Address
// - tezos.Key
// - tezos.Signature
// - tezos.ChainIdHash
// - bind.Or
// - bind.Option
// - pair
func hashFunc(keyType any) func(any) hashType {
switch keyType.(type) {
case string:
return func(k any) hashType { return hashBytes([]byte(k.(string))) }
case []byte:
return func(k any) hashType { return hashBytes(k.([]byte)) }
case bool:
return func(k any) hashType {
if k.(bool) {
return hashType{1}
}
return hashType{0}
}
case *big.Int:
return func(k any) hashType { return hashBytes(k.(*big.Int).Bytes()) }
case time.Time:
return func(k any) hashType { return hashBytes(must(k.(time.Time).MarshalBinary())) }
case tezos.Address:
return func(k any) hashType { return hashBytes(k.(tezos.Address).Hash()) }
case tezos.Key:
return func(k any) hashType { return hashBytes(k.(tezos.Key).Bytes()) }
case tezos.ChainIdHash:
return func(k any) hashType { return hashBytes(k.(tezos.ChainIdHash).Bytes()) }
case keyHasher:
return func(k any) hashType { return k.(keyHasher).keyHash() }
}
panic(fmt.Sprintf("%T keys is not supported", keyType))
}
type keyHasher interface {
keyHash() hashType
}
func hashBytes(b []byte) hashType {
h := sha256.New()
h.Write(b)
var hash hashType
copy(hash[:], h.Sum(nil))
return hash
}
func must[T any](t T, err error) T {
if err != nil {
panic(err)
}
return t
}
func zero[T any]() T {
var t T
return t
}