-
Notifications
You must be signed in to change notification settings - Fork 10
/
value.go
388 lines (332 loc) · 10.7 KB
/
value.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
386
387
388
package quickjs
/*
#include "bridge.h"
*/
import "C"
import (
"errors"
"math/big"
"unsafe"
)
type Error struct {
Cause string
Stack string
}
func (err Error) Error() string { return err.Cause }
// Object property names and some strings are stored as Atoms (unique strings) to save memory and allow fast comparison. Atoms are represented as a 32 bit integer. Half of the atom range is reserved for immediate integer literals from 0 to 2^{31}-1.
type Atom struct {
ctx *Context
ref C.JSAtom
}
// Free the value.
func (a Atom) Free() {
C.JS_FreeAtom(a.ctx.ref, a.ref)
}
// String returns the string representation of the value.
func (a Atom) String() string {
ptr := C.JS_AtomToCString(a.ctx.ref, a.ref)
defer C.JS_FreeCString(a.ctx.ref, ptr)
return C.GoString(ptr)
}
// Value returns the value of the Atom object.
func (a Atom) Value() Value {
return Value{ctx: a.ctx, ref: C.JS_AtomToValue(a.ctx.ref, a.ref)}
}
// propertyEnum is a wrapper around JSAtom.
type propertyEnum struct {
IsEnumerable bool
atom Atom
}
// String returns the atom string representation of the value.
func (p propertyEnum) String() string { return p.atom.String() }
// JSValue represents a Javascript value which can be a primitive type or an object. Reference counting is used, so it is important to explicitly duplicate (JS_DupValue(), increment the reference count) or free (JS_FreeValue(), decrement the reference count) JSValues.
type Value struct {
ctx *Context
ref C.JSValue
}
// Free the value.
func (v Value) Free() {
C.JS_FreeValue(v.ctx.ref, v.ref)
}
// Context represents a Javascript context.
func (v Value) Context() *Context {
return v.ctx
}
// Bool returns the boolean value of the value.
func (v Value) Bool() bool {
return C.JS_ToBool(v.ctx.ref, v.ref) == 1
}
// String returns the string representation of the value.
func (v Value) String() string {
ptr := C.JS_ToCString(v.ctx.ref, v.ref)
defer C.JS_FreeCString(v.ctx.ref, ptr)
return C.GoString(ptr)
}
// JSONString returns the JSON string representation of the value.
func (v Value) JSONStringify() string {
ref := C.JS_JSONStringify(v.ctx.ref, v.ref, C.JS_NewNull(), C.JS_NewNull())
ptr := C.JS_ToCString(v.ctx.ref, ref)
defer C.JS_FreeCString(v.ctx.ref, ptr)
return C.GoString(ptr)
}
func (v Value) ToByteArray(size uint) ([]byte, error) {
if v.ByteLen() < int64(size) {
return nil, errors.New("exceeds the maximum length of the current binary array")
}
cSize := C.size_t(size)
outBuf := C.JS_GetArrayBuffer(v.ctx.ref, &cSize, v.ref)
return C.GoBytes(unsafe.Pointer(outBuf), C.int(size)), nil
}
// IsByteArray return true if the value is array buffer
func (v Value) IsByteArray() bool {
return v.IsObject() && v.globalInstanceof("ArrayBuffer") || v.String() == "[object ArrayBuffer]"
}
// Int64 returns the int64 value of the value.
func (v Value) Int64() int64 {
val := C.int64_t(0)
C.JS_ToInt64(v.ctx.ref, &val, v.ref)
return int64(val)
}
// Int32 returns the int32 value of the value.
func (v Value) Int32() int32 {
val := C.int32_t(0)
C.JS_ToInt32(v.ctx.ref, &val, v.ref)
return int32(val)
}
// Uint32 returns the uint32 value of the value.
func (v Value) Uint32() uint32 {
val := C.uint32_t(0)
C.JS_ToUint32(v.ctx.ref, &val, v.ref)
return uint32(val)
}
// Float64 returns the float64 value of the value.
func (v Value) Float64() float64 {
val := C.double(0)
C.JS_ToFloat64(v.ctx.ref, &val, v.ref)
return float64(val)
}
// BigInt returns the big.Int value of the value.
func (v Value) BigInt() *big.Int {
if !v.IsBigInt() {
return nil
}
val, ok := new(big.Int).SetString(v.String(), 10)
if !ok {
return nil
}
return val
}
// BigFloat returns the big.Float value of the value.
func (v Value) BigFloat() *big.Float {
if !v.IsBigDecimal() && !v.IsBigFloat() {
return nil
}
val, ok := new(big.Float).SetString(v.String())
if !ok {
return nil
}
return val
}
// ToArray
//
// @Description: return array object
// @receiver v :
// @return *Array
func (v Value) ToArray() *Array {
if !v.IsArray() {
return nil
}
return NewQjsArray(v, v.ctx)
}
// ToMap
//
// @Description: return map object
// @receiver v :
// @return *Map
func (v Value) ToMap() *Map {
if !v.IsMap() {
return nil
}
return NewQjsMap(v, v.ctx)
}
// ToSet
//
// @Description: return set object
// @receiver v :
// @return *Set
func (v Value) ToSet() *Set {
if v.IsSet() {
return nil
}
return NewQjsSet(v, v.ctx)
}
// IsMap return true if the value is a map
func (v Value) IsMap() bool {
return v.IsObject() && v.globalInstanceof("Map") || v.String() == "[object Map]"
}
// IsSet return true if the value is a set
func (v Value) IsSet() bool {
return v.IsObject() && v.globalInstanceof("Set") || v.String() == "[object Set]"
}
// Len returns the length of the array.
func (v Value) Len() int64 {
return v.Get("length").Int64()
}
// ByteLen returns the length of the ArrayBuffer.
func (v Value) ByteLen() int64 {
return v.Get("byteLength").Int64()
}
// Set sets the value of the property with the given name.
func (v Value) Set(name string, val Value) {
namePtr := C.CString(name)
defer C.free(unsafe.Pointer(namePtr))
C.JS_SetPropertyStr(v.ctx.ref, v.ref, namePtr, val.ref)
}
// SetIdx sets the value of the property with the given index.
func (v Value) SetIdx(idx int64, val Value) {
C.JS_SetPropertyUint32(v.ctx.ref, v.ref, C.uint32_t(idx), val.ref)
}
// Get returns the value of the property with the given name.
func (v Value) Get(name string) Value {
namePtr := C.CString(name)
defer C.free(unsafe.Pointer(namePtr))
return Value{ctx: v.ctx, ref: C.JS_GetPropertyStr(v.ctx.ref, v.ref, namePtr)}
}
// GetIdx returns the value of the property with the given index.
func (v Value) GetIdx(idx int64) Value {
return Value{ctx: v.ctx, ref: C.JS_GetPropertyUint32(v.ctx.ref, v.ref, C.uint32_t(idx))}
}
// Call calls the function with the given arguments.
func (v Value) Call(fname string, args ...Value) Value {
if !v.IsObject() {
return v.ctx.Error(errors.New("Object not a object"))
}
fn := v.Get(fname) // get the function by name
defer fn.Free()
if !fn.IsFunction() {
return v.ctx.Error(errors.New("Object not a function"))
}
cargs := []C.JSValue{}
for _, x := range args {
cargs = append(cargs, x.ref)
}
if len(cargs) == 0 {
return Value{ctx: v.ctx, ref: C.JS_Call(v.ctx.ref, fn.ref, v.ref, C.int(0), nil)}
}
return Value{ctx: v.ctx, ref: C.JS_Call(v.ctx.ref, fn.ref, v.ref, C.int(len(cargs)), &cargs[0])}
}
// Call Class Constructor
func (v Value) New(args ...Value) Value {
return v.CallConstructor(args...)
}
// Call calls the constructor with the given arguments.
func (v Value) CallConstructor(args ...Value) Value {
if !v.IsConstructor() {
return v.ctx.Error(errors.New("Object not a constructor"))
}
cargs := []C.JSValue{}
for _, x := range args {
cargs = append(cargs, x.ref)
}
if len(cargs) == 0 {
return Value{ctx: v.ctx, ref: C.JS_CallConstructor(v.ctx.ref, v.ref, C.int(0), nil)}
}
return Value{ctx: v.ctx, ref: C.JS_CallConstructor(v.ctx.ref, v.ref, C.int(len(cargs)), &cargs[0])}
}
// Error returns the error value of the value.
func (v Value) Error() error {
if !v.IsError() {
return nil
}
cause := v.String()
stack := v.Get("stack")
defer stack.Free()
if stack.IsUndefined() {
return &Error{Cause: cause}
}
return &Error{Cause: cause, Stack: stack.String()}
}
// propertyEnum is a wrapper around JSValue.
func (v Value) propertyEnum() ([]propertyEnum, error) {
var ptr *C.JSPropertyEnum
var size C.uint32_t
result := int(C.JS_GetOwnPropertyNames(v.ctx.ref, &ptr, &size, v.ref, C.int(1<<0|1<<1|1<<2)))
if result < 0 {
return nil, errors.New("value does not contain properties")
}
defer C.js_free(v.ctx.ref, unsafe.Pointer(ptr))
entries := unsafe.Slice(ptr, size) // Go 1.17 and later
names := make([]propertyEnum, len(entries))
for i := 0; i < len(names); i++ {
names[i].IsEnumerable = entries[i].is_enumerable == 1
names[i].atom = Atom{ctx: v.ctx, ref: entries[i].atom}
names[i].atom.Free()
}
return names, nil
}
// PropertyNames returns the names of the properties of the value.
func (v Value) PropertyNames() ([]string, error) {
pList, err := v.propertyEnum()
if err != nil {
return nil, err
}
names := make([]string, len(pList))
for i := 0; i < len(names); i++ {
names[i] = pList[i].String()
}
return names, nil
}
// Has returns true if the value has the property with the given name.
func (v Value) Has(name string) bool {
prop := v.ctx.Atom(name)
defer prop.Free()
return C.JS_HasProperty(v.ctx.ref, v.ref, prop.ref) == 1
}
// HasIdx returns true if the value has the property with the given index.
func (v Value) HasIdx(idx int64) bool {
prop := v.ctx.AtomIdx(idx)
defer prop.Free()
return C.JS_HasProperty(v.ctx.ref, v.ref, prop.ref) == 1
}
// Delete deletes the property with the given name.
func (v Value) Delete(name string) bool {
prop := v.ctx.Atom(name)
defer prop.Free()
return C.JS_DeleteProperty(v.ctx.ref, v.ref, prop.ref, C.int(1)) == 1
}
// DeleteIdx deletes the property with the given index.
func (v Value) DeleteIdx(idx int64) bool {
return C.JS_DeletePropertyInt64(v.ctx.ref, v.ref, C.int64_t(idx), C.int(1)) == 1
}
// globalInstanceof checks if the value is an instance of the given global constructor
func (v Value) globalInstanceof(name string) bool {
ctor := v.ctx.Globals().Get(name)
defer ctor.Free()
if ctor.IsUndefined() {
return false
}
return C.JS_IsInstanceOf(v.ctx.ref, v.ref, ctor.ref) == 1
}
func (v Value) IsNumber() bool { return C.JS_IsNumber(v.ref) == 1 }
func (v Value) IsBigInt() bool { return C.JS_IsBigInt(v.ctx.ref, v.ref) == 1 }
func (v Value) IsBigFloat() bool { return C.JS_IsBigFloat(v.ref) == 1 }
func (v Value) IsBigDecimal() bool { return C.JS_IsBigDecimal(v.ref) == 1 }
func (v Value) IsBool() bool { return C.JS_IsBool(v.ref) == 1 }
func (v Value) IsNull() bool { return C.JS_IsNull(v.ref) == 1 }
func (v Value) IsUndefined() bool { return C.JS_IsUndefined(v.ref) == 1 }
func (v Value) IsException() bool { return C.JS_IsException(v.ref) == 1 }
func (v Value) IsUninitialized() bool { return C.JS_IsUninitialized(v.ref) == 1 }
func (v Value) IsString() bool { return C.JS_IsString(v.ref) == 1 }
func (v Value) IsSymbol() bool { return C.JS_IsSymbol(v.ref) == 1 }
func (v Value) IsObject() bool { return C.JS_IsObject(v.ref) == 1 }
func (v Value) IsArray() bool { return C.JS_IsArray(v.ctx.ref, v.ref) == 1 }
func (v Value) IsError() bool { return C.JS_IsError(v.ctx.ref, v.ref) == 1 }
func (v Value) IsFunction() bool { return C.JS_IsFunction(v.ctx.ref, v.ref) == 1 }
func (v Value) IsPromise() bool {
state := C.JS_PromiseState(v.ctx.ref, v.ref)
if state == C.JS_PROMISE_PENDING || state == C.JS_PROMISE_FULFILLED || state == C.JS_PROMISE_REJECTED {
return true
}
return false
}
func (v Value) IsConstructor() bool { return C.JS_IsConstructor(v.ctx.ref, v.ref) == 1 }