forked from rogchap/v8go
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathyao.go
96 lines (83 loc) · 2.23 KB
/
yao.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
package v8go
import (
"fmt"
"unsafe"
)
// #include "v8go.h"
// #include <stdlib.h>
import "C"
// YaoNewIsolate creates a new V8 isolate. Only one thread may access
// a given isolate at a time, but different threads may access
// different isolates simultaneously.
// When an isolate is no longer used its resources should be freed
// by calling iso.Dispose().
// An *Isolate can be used as a v8go.ContextOption to create a new
// Context, rather than creating a new default Isolate.
func YaoNewIsolate() *Isolate {
iso := &Isolate{
ptr: C.YaoNewIsolate(),
cbs: make(map[int]FunctionCallback),
}
iso.null = newValueNull(iso)
iso.undefined = newValueUndefined(iso)
return iso
}
// YaoNewIsolateFromGlobal creates a new V8 isolate from global.
func YaoNewIsolateFromGlobal() (*Isolate, error) {
ptr := C.YaoNewIsolateFromGlobal()
if ptr == nil {
return nil, fmt.Errorf("YaoNewIsolateFromGlobal failed")
}
iso := &Isolate{
ptr: ptr,
cbs: make(map[int]FunctionCallback),
}
return iso, nil
}
// YaoDispose will dispose the Isolate VM; subsequent calls will panic.
func YaoDispose() {
C.YaoDispose()
}
// Copy copies the current isolate.
func (iso *Isolate) Copy() (*Isolate, error) {
if iso.ptr == nil {
return nil, fmt.Errorf("invalid isolate")
}
new := &Isolate{
ptr: C.YaoCopyIsolate(iso.ptr),
cbs: make(map[int]FunctionCallback),
}
return new, nil
}
// Context returns the current context for this isolate.
// DO NOT CALL CLOSE, IT WILL CAUSE PANIC
// THE CONTEXT WILL BE DISPOSED AUTOMATICALLY
func (iso *Isolate) Context() (*Context, error) {
ptr := C.YaoIsolateContext(iso.ptr)
if ptr == nil {
return nil, fmt.Errorf("no current context")
}
ctxSeq++
ref := ctxSeq
return &Context{
ref: ref,
ptr: ptr,
iso: iso,
}, nil
}
// AsGlobal makes the isolate into a global object.
func (iso *Isolate) AsGlobal() {
C.YaoIsolateAsGlobal(iso.ptr)
}
// YaoInit initializes V8 with the given heap size limit.
func YaoInit(heapSizeLimitMB uint) {
v8once.Do(func() {
cflags := C.CString("--no-freeze_flags_after_init")
if heapSizeLimitMB > 0 {
cflags = C.CString(fmt.Sprintf("--no-freeze_flags_after_init --max_old_space_size=%d", heapSizeLimitMB))
}
defer C.free(unsafe.Pointer(cflags))
C.SetFlags(cflags)
C.Init()
})
}