forked from goby-lang/goby
/
concurrent_hash.go
385 lines (321 loc) · 10.5 KB
/
concurrent_hash.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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
package vm
import (
"bytes"
"fmt"
"strings"
"sync"
"github.com/goby-lang/goby/vm/classes"
"github.com/goby-lang/goby/vm/errors"
)
// ConcurrentHashObject is an implementation of thread-safe associative arrays (Hash).
//
// The implementation internally uses Go's `sync.Map` type, with some advantages and disadvantages:
//
// - it is highly performant and predictable for a certain pattern of usage (`concurrent loops with keys that are stable over time, and either few steady-state stores, or stores localized to one goroutine per key.`); performance and predictability in other conditions are unspecified;
// - iterations are non-deterministic; during iterations, keys may not be included;
// - size can't be retrieved;
// - for the reasons above, the Hash APIs implemented are minimal.
//
// For details, see https://golang.org/pkg/sync/#Map.
//
// ```ruby
// require 'concurrent/hash'
// hash = Concurrent::Hash.new({ "a": 1, "b": 2 })
// hash["a"] # => 1
// ```
//
type ConcurrentHashObject struct {
*baseObj
internalMap sync.Map
}
// Class methods --------------------------------------------------------
func builtinConcurrentHashClassMethods() []*BuiltinMethodObject {
return []*BuiltinMethodObject{
{
Name: "new",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) > 1 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, "Expect 0 or 1 arguments, got %d", len(args))
}
if len(args) == 0 {
return t.vm.initConcurrentHashObject(make(map[string]Object))
}
arg := args[0]
hashArg, ok := arg.(*HashObject)
if !ok {
return t.vm.initErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.HashClass, arg.Class().Name)
}
return t.vm.initConcurrentHashObject(hashArg.Pairs)
}
},
},
}
}
// Instance methods -----------------------------------------------------
func builtinConcurrentHashInstanceMethods() []*BuiltinMethodObject {
return []*BuiltinMethodObject{
{
// Retrieves the value (object) that corresponds to the key specified.
// When a key doesn't exist, `nil` is returned, or the default, if set.
//
// ```Ruby
// h = Concurrent::Hash.new({ a: 1, b: "2" })
// h['a'] #=> 1
// h['b'] #=> "2"
// h['c'] #=> nil
// ```
//
// @return [Object]
Name: "[]",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, "Expect 1 argument. got: %d", len(args))
}
i := args[0]
key, ok := i.(*StringObject)
if !ok {
return t.vm.initErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, i.Class().Name)
}
h := receiver.(*ConcurrentHashObject)
value, ok := h.internalMap.Load(key.value)
if !ok {
return NULL
}
return value.(Object)
}
},
},
{
// Associates the value given by `value` with the key given by `key`.
// Returns the `value`.
//
// ```Ruby
// h = Concurrent::Hash.new{ a: 1, b: "2" })
// h['a'] = 2 #=> 2
// h #=> { a: 2, b: "2" }
// ```
//
// @return [Object] The value
Name: "[]=",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
// First arg is index
// Second arg is assigned value
if len(args) != 2 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, "Expect 2 arguments. got: %d", len(args))
}
k := args[0]
key, ok := k.(*StringObject)
if !ok {
return t.vm.initErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, k.Class().Name)
}
h := receiver.(*ConcurrentHashObject)
h.internalMap.Store(key.value, args[1])
return args[1]
}
},
},
{
// Remove the key from the hash if key exist.
//
// ```Ruby
// h = Concurrent::Hash.new({ a: 1, b: 2, c: 3 })
// h.delete("b") # => NULL
// h # => { a: 1, c: 3 }
// ```
//
// @return [NULL]
Name: "delete",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, "Expect 1 argument. got: %d", len(args))
}
h := receiver.(*ConcurrentHashObject)
d := args[0]
deleteKeyObject, ok := d.(*StringObject)
if !ok {
return t.vm.initErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, d.Class().Name)
}
h.internalMap.Delete(deleteKeyObject.value)
return NULL
}
},
},
{
// Calls block once for each key in the hash (in sorted key order), passing the
// key-value pair as parameters.
// Note that iteration is not deterministic under all circumstances; see
// https://golang.org/pkg/sync/#Map.
//
// ```Ruby
// h = Concurrent::Hash.new({ b: "2", a: 1 })
// h.each do |k, v|
// puts k.to_s + "->" + v.to_s
// end
// # => a->1
// # => b->2
// ```
//
// @return [Hash] self
Name: "each",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
if blockFrame == nil {
return t.vm.initErrorObject(errors.InternalError, sourceLine, errors.CantYieldWithoutBlockFormat)
}
if len(args) != 0 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, "Expect 0 arguments. got: %d", len(args))
}
hash := receiver.(*ConcurrentHashObject)
framePopped := false
iterator := func(key, value interface{}) bool {
keyObject := t.vm.initStringObject(key.(string))
t.builtinMethodYield(blockFrame, keyObject, value.(Object))
framePopped = true
return true
}
hash.internalMap.Range(iterator)
if !framePopped {
t.callFrameStack.pop()
}
return hash
}
},
},
{
// Returns true if the key exist in the hash.
//
// ```Ruby
// h = Concurrent::Hash.new({ a: 1, b: "2" })
// h.has_key?("a") # => true
// h.has_key?("e") # => false
// ```
//
// @return [Boolean]
Name: "has_key?",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 1 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, "Expect 1 argument. got: %d", len(args))
}
h := receiver.(*ConcurrentHashObject)
i := args[0]
input, ok := i.(*StringObject)
if !ok {
return t.vm.initErrorObject(errors.TypeError, sourceLine, errors.WrongArgumentTypeFormat, classes.StringClass, i.Class().Name)
}
if _, ok := h.internalMap.Load(input.value); ok {
return TRUE
}
return FALSE
}
},
},
{
// Returns json that is corresponding to the hash.
// Basically just like Hash#to_json in Rails but currently doesn't support options.
//
// ```Ruby
// h = Concurrent::Hash.new({ a: 1, b: 2 })
// h.to_json #=> {"a":1,"b":2}
// ```
//
// @return [String]
Name: "to_json",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, "Expect 0 argument. got: %d", len(args))
}
r := receiver.(*ConcurrentHashObject)
return t.vm.initStringObject(r.toJSON(t))
}
},
},
{
// Returns json that is corresponding to the hash.
// Basically just like Hash#to_json in Rails but currently doesn't support options.
//
// ```Ruby
// h = Concurrent::Hash.new({ a: 1, b: "2"})
// h.to_s #=> "{ a: 1, b: \"2\" }"
// ```
//
// @return [String]
Name: "to_s",
Fn: func(receiver Object, sourceLine int) builtinMethodBody {
return func(t *thread, args []Object, blockFrame *normalCallFrame) Object {
if len(args) != 0 {
return t.vm.initErrorObject(errors.ArgumentError, sourceLine, "Expect 0 argument. got: %d", len(args))
}
h := receiver.(*ConcurrentHashObject)
return t.vm.initStringObject(h.toString())
}
},
},
}
}
// Internal functions ===================================================
// Functions for initialization -----------------------------------------
func (vm *VM) initConcurrentHashObject(pairs map[string]Object) *ConcurrentHashObject {
var internalMap sync.Map
for key, value := range pairs {
internalMap.Store(key, value)
}
concurrent := vm.loadConstant("Concurrent", true)
hash := concurrent.getClassConstant("Hash")
return &ConcurrentHashObject{
baseObj: &baseObj{class: hash},
internalMap: internalMap,
}
}
func initConcurrentHashClass(vm *VM) {
concurrent := vm.loadConstant("Concurrent", true)
hash := vm.initializeClass("Hash", false)
hash.setBuiltinMethods(builtinConcurrentHashInstanceMethods(), false)
hash.setBuiltinMethods(builtinConcurrentHashClassMethods(), true)
concurrent.setClassConstant(hash)
}
// Polymorphic helper functions -----------------------------------------
// Value returns the object
func (h *ConcurrentHashObject) Value() interface{} {
return h.internalMap
}
// toString returns the object's name as the string format
func (h *ConcurrentHashObject) toString() string {
var out bytes.Buffer
var pairs []string
iterator := func(key, value interface{}) bool {
var template string
switch value.(type) {
case *StringObject:
template = "%s: \"%s\""
default:
template = "%s: %s"
}
pairs = append(pairs, fmt.Sprintf(template, key, value.(Object).toString()))
return true
}
h.internalMap.Range(iterator)
out.WriteString("{ ")
out.WriteString(strings.Join(pairs, ", "))
out.WriteString(" }")
return out.String()
}
// toJSON returns the object's name as the JSON string format
func (h *ConcurrentHashObject) toJSON(t *thread) string {
var out bytes.Buffer
var values []string
out.WriteString("{")
iterator := func(key, value interface{}) bool {
values = append(values, generateJSONFromPair(key.(string), value.(Object), t))
return true
}
h.internalMap.Range(iterator)
out.WriteString(strings.Join(values, ","))
out.WriteString("}")
return out.String()
}