-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsandbox.go
60 lines (49 loc) · 1.18 KB
/
sandbox.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
package gopcp
import (
"errors"
"fmt"
)
// (params, attachment, pcpServer) -> (result, error)
type GeneralFun = func([]interface{}, interface{}, *PcpServer) (interface{}, error)
// SandBoxType
const (
SandboxTypeNormal = 1
SandboxTypeLazy = 2
)
// BoxFun
type BoxFunc struct {
FunType int // SandBoxType
Fun GeneralFun
}
// Sandbox
type Sandbox struct {
funcMap map[string]*BoxFunc // name -> boxFunc
}
func GetSandbox(box map[string]*BoxFunc) *Sandbox {
return (&Sandbox{box}).Extend(DefBox)
}
// Get get sandbox method
func (s *Sandbox) Get(name string) (*BoxFunc, error) {
if val, ok := s.funcMap[name]; ok {
return val, nil
}
return nil, errors.New(fmt.Sprintf("function [%s] doesn't exist in sandBox", name))
}
// Set set sandbox method
func (s *Sandbox) Set(name string, val *BoxFunc) {
s.funcMap[name] = val
return
}
// Extend merge newSandBox's value to origin sandBox
func (s *Sandbox) Extend(newSandBox *Sandbox) *Sandbox {
for k, v := range newSandBox.funcMap {
s.Set(k, v)
}
return s
}
func ToSandboxFun(fun GeneralFun) *BoxFunc {
return &BoxFunc{SandboxTypeNormal, fun}
}
func ToLazySandboxFun(fun GeneralFun) *BoxFunc {
return &BoxFunc{SandboxTypeLazy, fun}
}