-
-
Notifications
You must be signed in to change notification settings - Fork 221
/
value.go
600 lines (503 loc) · 16.5 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
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
// Copyright 2019 Roger Chapman and the v8go contributors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
package v8go
// #include <stdlib.h>
// #include "v8go.h"
import "C"
import (
"errors"
"fmt"
"io"
"math/big"
"unsafe"
)
// Value represents all Javascript values and objects
type Value struct {
ptr C.ValuePtr
ctx *Context
}
// Valuer is an interface that reperesents anything that extends from a Value
// eg. Object, Array, Date etc
type Valuer interface {
value() *Value
}
func (v *Value) value() *Value {
return v
}
func newValueNull(iso *Isolate) *Value {
return &Value{
ptr: C.NewValueNull(iso.ptr),
}
}
func newValueUndefined(iso *Isolate) *Value {
return &Value{
ptr: C.NewValueUndefined(iso.ptr),
}
}
// Undefined returns the `undefined` JS value
func Undefined(iso *Isolate) *Value {
return iso.undefined
}
// Null returns the `null` JS value
func Null(iso *Isolate) *Value {
return iso.null
}
// NewValue will create a primitive value. Supported values types to create are:
//
// string -> V8::String
// int32 -> V8::Integer
// uint32 -> V8::Integer
// int64 -> V8::BigInt
// uint64 -> V8::BigInt
// bool -> V8::Boolean
// *big.Int -> V8::BigInt
func NewValue(iso *Isolate, val interface{}) (*Value, error) {
if iso == nil {
return nil, errors.New("v8go: failed to create new Value: Isolate cannot be <nil>")
}
var rtnVal *Value
switch v := val.(type) {
case string:
cstr := C.CString(v)
defer C.free(unsafe.Pointer(cstr))
rtn := C.NewValueString(iso.ptr, cstr, C.int(len(v)))
return valueResult(nil, rtn)
case int32:
rtnVal = &Value{
ptr: C.NewValueInteger(iso.ptr, C.int(v)),
}
case uint32:
rtnVal = &Value{
ptr: C.NewValueIntegerFromUnsigned(iso.ptr, C.uint(v)),
}
case int64:
rtnVal = &Value{
ptr: C.NewValueBigInt(iso.ptr, C.int64_t(v)),
}
case uint64:
rtnVal = &Value{
ptr: C.NewValueBigIntFromUnsigned(iso.ptr, C.uint64_t(v)),
}
case bool:
var b int
if v {
b = 1
}
rtnVal = &Value{
ptr: C.NewValueBoolean(iso.ptr, C.int(b)),
}
case float64:
rtnVal = &Value{
ptr: C.NewValueNumber(iso.ptr, C.double(v)),
}
case *big.Int:
if v.IsInt64() {
rtnVal = &Value{
ptr: C.NewValueBigInt(iso.ptr, C.int64_t(v.Int64())),
}
break
}
if v.IsUint64() {
rtnVal = &Value{
ptr: C.NewValueBigIntFromUnsigned(iso.ptr, C.uint64_t(v.Uint64())),
}
break
}
var sign, count int
if v.Sign() == -1 {
sign = 1
}
bits := v.Bits()
count = len(bits)
words := make([]C.uint64_t, count, count)
for idx, word := range bits {
words[idx] = C.uint64_t(word)
}
rtn := C.NewValueBigIntFromWords(iso.ptr, C.int(sign), C.int(count), &words[0])
return valueResult(nil, rtn)
default:
return nil, fmt.Errorf("v8go: unsupported value type `%T`", v)
}
return rtnVal, nil
}
// Format implements the fmt.Formatter interface to provide a custom formatter
// primarily to output the detail string (for debugging) with `%+v` verb.
func (v *Value) Format(s fmt.State, verb rune) {
switch verb {
case 'v':
if s.Flag('+') {
io.WriteString(s, v.DetailString())
return
}
fallthrough
case 's':
io.WriteString(s, v.String())
case 'q':
fmt.Fprintf(s, "%q", v.String())
}
}
// ArrayIndex attempts to converts a string to an array index. Returns ok false if conversion fails.
func (v *Value) ArrayIndex() (idx uint32, ok bool) {
arrayIdx := C.ValueToArrayIndex(v.ptr)
defer C.free(unsafe.Pointer(arrayIdx))
if arrayIdx == nil {
return 0, false
}
return uint32(*arrayIdx), true
}
// BigInt perform the equivalent of `BigInt(value)` in JS.
func (v *Value) BigInt() *big.Int {
if v == nil {
return nil
}
bint := C.ValueToBigInt(v.ptr)
defer C.free(unsafe.Pointer(bint.word_array))
if bint.word_array == nil {
return nil
}
words := (*[1 << 30]big.Word)(unsafe.Pointer(bint.word_array))[:bint.word_count:bint.word_count]
abs := make([]big.Word, len(words))
copy(abs, words)
b := &big.Int{}
b.SetBits(abs)
if bint.sign_bit == 1 {
b.Neg(b)
}
return b
}
// Boolean perform the equivalent of `Boolean(value)` in JS. This can never fail.
func (v *Value) Boolean() bool {
return C.ValueToBoolean(v.ptr) != 0
}
// DetailString provide a string representation of this value usable for debugging.
func (v *Value) DetailString() string {
rtn := C.ValueToDetailString(v.ptr)
if rtn.data == nil {
err := newJSError(rtn.error)
panic(err) // TODO: Return a fallback value
}
defer C.free(unsafe.Pointer(rtn.data))
return C.GoStringN(rtn.data, rtn.length)
}
// Int32 perform the equivalent of `Number(value)` in JS and convert the result to a
// signed 32-bit integer by performing the steps in https://tc39.es/ecma262/#sec-toint32.
func (v *Value) Int32() int32 {
return int32(C.ValueToInt32(v.ptr))
}
// Integer perform the equivalent of `Number(value)` in JS and convert the result to an integer.
// Negative values are rounded up, positive values are rounded down. NaN is converted to 0.
// Infinite values yield undefined results.
func (v *Value) Integer() int64 {
return int64(C.ValueToInteger(v.ptr))
}
// Number perform the equivalent of `Number(value)` in JS.
func (v *Value) Number() float64 {
return float64(C.ValueToNumber(v.ptr))
}
// Object perform the equivalent of Object(value) in JS.
// To just cast this value as an Object use AsObject() instead.
func (v *Value) Object() *Object {
rtn := C.ValueToObject(v.ptr)
obj, err := objectResult(v.ctx, rtn)
if err != nil {
panic(err) // TODO: Return error
}
return obj
}
// String perform the equivalent of `String(value)` in JS. Primitive values
// are returned as-is, objects will return `[object Object]` and functions will
// print their definition.
func (v *Value) String() string {
s := C.ValueToString(v.ptr)
defer C.free(unsafe.Pointer(s.data))
return C.GoStringN(s.data, C.int(s.length))
}
// Uint32 perform the equivalent of `Number(value)` in JS and convert the result to an
// unsigned 32-bit integer by performing the steps in https://tc39.es/ecma262/#sec-touint32.
func (v *Value) Uint32() uint32 {
return uint32(C.ValueToUint32(v.ptr))
}
// SameValue returns true if the other value is the same value.
// This is equivalent to `Object.is(v, other)` in JS.
func (v *Value) SameValue(other *Value) bool {
return C.ValueSameValue(v.ptr, other.ptr) != 0
}
// IsUndefined returns true if this value is the undefined value. See ECMA-262 4.3.10.
func (v *Value) IsUndefined() bool {
return C.ValueIsUndefined(v.ptr) != 0
}
// IsNull returns true if this value is the null value. See ECMA-262 4.3.11.
func (v *Value) IsNull() bool {
return C.ValueIsNull(v.ptr) != 0
}
// IsNullOrUndefined returns true if this value is either the null or the undefined value.
// See ECMA-262 4.3.11. and 4.3.12
// This is equivalent to `value == null` in JS.
func (v *Value) IsNullOrUndefined() bool {
return C.ValueIsNullOrUndefined(v.ptr) != 0
}
// IsTrue returns true if this value is true.
// This is not the same as `BooleanValue()`. The latter performs a conversion to boolean,
// i.e. the result of `Boolean(value)` in JS, whereas this checks `value === true`.
func (v *Value) IsTrue() bool {
return C.ValueIsTrue(v.ptr) != 0
}
// IsFalse returns true if this value is false.
// This is not the same as `!BooleanValue()`. The latter performs a conversion to boolean,
// i.e. the result of `!Boolean(value)` in JS, whereas this checks `value === false`.
func (v *Value) IsFalse() bool {
return C.ValueIsFalse(v.ptr) != 0
}
// IsName returns true if this value is a symbol or a string.
// This is equivalent to `typeof value === 'string' || typeof value === 'symbol'` in JS.
func (v *Value) IsName() bool {
return C.ValueIsName(v.ptr) != 0
}
// IsString returns true if this value is an instance of the String type. See ECMA-262 8.4.
// This is equivalent to `typeof value === 'string'` in JS.
func (v *Value) IsString() bool {
return C.ValueIsString(v.ptr) != 0
}
// IsSymbol returns true if this value is a symbol.
// This is equivalent to `typeof value === 'symbol'` in JS.
func (v *Value) IsSymbol() bool {
return C.ValueIsSymbol(v.ptr) != 0
}
// IsFunction returns true if this value is a function.
// This is equivalent to `typeof value === 'function'` in JS.
func (v *Value) IsFunction() bool {
return C.ValueIsFunction(v.ptr) != 0
}
// IsObject returns true if this value is an object.
func (v *Value) IsObject() bool {
return v.ctx != nil && C.ValueIsObject(v.ptr) != 0
}
// IsBigInt returns true if this value is a bigint.
// This is equivalent to `typeof value === 'bigint'` in JS.
func (v *Value) IsBigInt() bool {
return C.ValueIsBigInt(v.ptr) != 0
}
// IsBoolean returns true if this value is boolean.
// This is equivalent to `typeof value === 'boolean'` in JS.
func (v *Value) IsBoolean() bool {
return C.ValueIsBoolean(v.ptr) != 0
}
// IsNumber returns true if this value is a number.
// This is equivalent to `typeof value === 'number'` in JS.
func (v *Value) IsNumber() bool {
return C.ValueIsNumber(v.ptr) != 0
}
// IsExternal returns true if this value is an `External` object.
func (v *Value) IsExternal() bool {
// TODO(rogchap): requires test case
return v.ctx != nil && C.ValueIsExternal(v.ptr) != 0
}
// IsInt32 returns true if this value is a 32-bit signed integer.
func (v *Value) IsInt32() bool {
return C.ValueIsInt32(v.ptr) != 0
}
// IsUint32 returns true if this value is a 32-bit unsigned integer.
func (v *Value) IsUint32() bool {
return C.ValueIsUint32(v.ptr) != 0
}
// IsDate returns true if this value is a `Date`.
func (v *Value) IsDate() bool {
return C.ValueIsDate(v.ptr) != 0
}
// IsArgumentsObject returns true if this value is an Arguments object.
func (v *Value) IsArgumentsObject() bool {
return C.ValueIsArgumentsObject(v.ptr) != 0
}
// IsBigIntObject returns true if this value is a BigInt object.
func (v *Value) IsBigIntObject() bool {
return C.ValueIsBigIntObject(v.ptr) != 0
}
// IsNumberObject returns true if this value is a `Number` object.
func (v *Value) IsNumberObject() bool {
return C.ValueIsNumberObject(v.ptr) != 0
}
// IsStringObject returns true if this value is a `String` object.
func (v *Value) IsStringObject() bool {
return C.ValueIsStringObject(v.ptr) != 0
}
// IsSymbolObject returns true if this value is a `Symbol` object.
func (v *Value) IsSymbolObject() bool {
return C.ValueIsSymbolObject(v.ptr) != 0
}
// IsNativeError returns true if this value is a NativeError.
func (v *Value) IsNativeError() bool {
return C.ValueIsNativeError(v.ptr) != 0
}
// IsRegExp returns true if this value is a `RegExp`.
func (v *Value) IsRegExp() bool {
return C.ValueIsRegExp(v.ptr) != 0
}
// IsAsyncFunc returns true if this value is an async function.
func (v *Value) IsAsyncFunction() bool {
return C.ValueIsAsyncFunction(v.ptr) != 0
}
// Is IsGeneratorFunc returns true if this value is a Generator function.
func (v *Value) IsGeneratorFunction() bool {
return C.ValueIsGeneratorFunction(v.ptr) != 0
}
// IsGeneratorObject returns true if this value is a Generator object (iterator).
func (v *Value) IsGeneratorObject() bool {
return C.ValueIsGeneratorObject(v.ptr) != 0
}
// IsPromise returns true if this value is a `Promise`.
func (v *Value) IsPromise() bool {
return C.ValueIsPromise(v.ptr) != 0
}
// IsMap returns true if this value is a `Map`.
func (v *Value) IsMap() bool {
return C.ValueIsMap(v.ptr) != 0
}
// IsSet returns true if this value is a `Set`.
func (v *Value) IsSet() bool {
return C.ValueIsSet(v.ptr) != 0
}
// IsMapIterator returns true if this value is a `Map` Iterator.
func (v *Value) IsMapIterator() bool {
return C.ValueIsMapIterator(v.ptr) != 0
}
// IsSetIterator returns true if this value is a `Set` Iterator.
func (v *Value) IsSetIterator() bool {
return C.ValueIsSetIterator(v.ptr) != 0
}
// IsWeakMap returns true if this value is a `WeakMap`.
func (v *Value) IsWeakMap() bool {
return C.ValueIsWeakMap(v.ptr) != 0
}
// IsWeakSet returns true if this value is a `WeakSet`.
func (v *Value) IsWeakSet() bool {
return C.ValueIsWeakSet(v.ptr) != 0
}
// IsArray returns true if this value is an array.
// Note that it will return false for a `Proxy` of an array.
func (v *Value) IsArray() bool {
return C.ValueIsArray(v.ptr) != 0
}
// IsArrayBuffer returns true if this value is an `ArrayBuffer`.
func (v *Value) IsArrayBuffer() bool {
return C.ValueIsArrayBuffer(v.ptr) != 0
}
// IsArrayBufferView returns true if this value is an `ArrayBufferView`.
func (v *Value) IsArrayBufferView() bool {
return C.ValueIsArrayBufferView(v.ptr) != 0
}
// IsTypedArray returns true if this value is one of TypedArrays.
func (v *Value) IsTypedArray() bool {
return C.ValueIsTypedArray(v.ptr) != 0
}
// IsUint8Array returns true if this value is an `Uint8Array`.
func (v *Value) IsUint8Array() bool {
return C.ValueIsUint8Array(v.ptr) != 0
}
// IsUint8ClampedArray returns true if this value is an `Uint8ClampedArray`.
func (v *Value) IsUint8ClampedArray() bool {
return C.ValueIsUint8ClampedArray(v.ptr) != 0
}
// IsInt8Array returns true if this value is an `Int8Array`.
func (v *Value) IsInt8Array() bool {
return C.ValueIsInt8Array(v.ptr) != 0
}
// IsUint16Array returns true if this value is an `Uint16Array`.
func (v *Value) IsUint16Array() bool {
return C.ValueIsUint16Array(v.ptr) != 0
}
// IsInt16Array returns true if this value is an `Int16Array`.
func (v *Value) IsInt16Array() bool {
return C.ValueIsInt16Array(v.ptr) != 0
}
// IsUint32Array returns true if this value is an `Uint32Array`.
func (v *Value) IsUint32Array() bool {
return C.ValueIsUint32Array(v.ptr) != 0
}
// IsInt32Array returns true if this value is an `Int32Array`.
func (v *Value) IsInt32Array() bool {
return C.ValueIsInt32Array(v.ptr) != 0
}
// IsFloat32Array returns true if this value is a `Float32Array`.
func (v *Value) IsFloat32Array() bool {
return C.ValueIsFloat32Array(v.ptr) != 0
}
// IsFloat64Array returns true if this value is a `Float64Array`.
func (v *Value) IsFloat64Array() bool {
return C.ValueIsFloat64Array(v.ptr) != 0
}
// IsBigInt64Array returns true if this value is a `BigInt64Array`.
func (v *Value) IsBigInt64Array() bool {
return C.ValueIsBigInt64Array(v.ptr) != 0
}
// IsBigUint64Array returns true if this value is a BigUint64Array`.
func (v *Value) IsBigUint64Array() bool {
return C.ValueIsBigUint64Array(v.ptr) != 0
}
// IsDataView returns true if this value is a `DataView`.
func (v *Value) IsDataView() bool {
return C.ValueIsDataView(v.ptr) != 0
}
// IsSharedArrayBuffer returns true if this value is a `SharedArrayBuffer`.
func (v *Value) IsSharedArrayBuffer() bool {
return C.ValueIsSharedArrayBuffer(v.ptr) != 0
}
// IsProxy returns true if this value is a JavaScript `Proxy`.
func (v *Value) IsProxy() bool {
return C.ValueIsProxy(v.ptr) != 0
}
// Release this value. Using the value after calling this function will result in undefined behavior.
func (v *Value) Release() {
C.ValueRelease(v.ptr)
}
// IsWasmModuleObject returns true if this value is a `WasmModuleObject`.
func (v *Value) IsWasmModuleObject() bool {
// TODO(rogchap): requires test case
return C.ValueIsWasmModuleObject(v.ptr) != 0
}
// IsModuleNamespaceObject returns true if the value is a `Module` Namespace `Object`.
func (v *Value) IsModuleNamespaceObject() bool {
// TODO(rogchap): requires test case
return C.ValueIsModuleNamespaceObject(v.ptr) != 0
}
// AsObject will cast the value to the Object type. If the value is not an Object
// then an error is returned. Use `value.Object()` to do the JS equivalent of `Object(value)`.
func (v *Value) AsObject() (*Object, error) {
if !v.IsObject() {
return nil, errors.New("v8go: value is not an Object")
}
return &Object{v}, nil
}
func (v *Value) AsPromise() (*Promise, error) {
if !v.IsPromise() {
return nil, errors.New("v8go: value is not a Promise")
}
return &Promise{&Object{v}}, nil
}
func (v *Value) AsFunction() (*Function, error) {
if !v.IsFunction() {
return nil, errors.New("v8go: value is not a Function")
}
return &Function{v}, nil
}
// MarshalJSON implements the json.Marshaler interface.
func (v *Value) MarshalJSON() ([]byte, error) {
jsonStr, err := JSONStringify(nil, v)
if err != nil {
return nil, err
}
return []byte(jsonStr), nil
}
func (v *Value) SharedArrayBufferGetContents() ([]byte, func(), error) {
if !v.IsSharedArrayBuffer() {
return nil, nil, errors.New("v8go: value is not a SharedArrayBuffer")
}
backingStore := C.SharedArrayBufferGetBackingStore(v.ptr)
release := func() {
C.BackingStoreRelease(backingStore)
}
byte_ptr := (*byte)(unsafe.Pointer(C.BackingStoreData(backingStore)))
byte_size := C.BackingStoreByteLength(backingStore)
byte_slice := unsafe.Slice(byte_ptr, byte_size)
return byte_slice, release, nil
}