-
Notifications
You must be signed in to change notification settings - Fork 303
/
model.go
65 lines (54 loc) · 1.31 KB
/
model.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
package starkit
import (
"context"
"fmt"
"reflect"
"go.starlark.net/starlark"
)
type Model struct {
state map[reflect.Type]interface{}
BuiltinCalls []BuiltinCall
}
func NewModel() Model {
return Model{
state: make(map[reflect.Type]interface{}),
}
}
func (m Model) createInitState(ext StatefulExtension) error {
v := ext.NewState()
t := reflect.TypeOf(v)
_, exists := m.state[t]
if exists {
return fmt.Errorf("Initializing extension %T: model type conflict: %T", ext, v)
}
m.state[t] = v
return nil
}
func (m Model) Load(ptr interface{}) error {
ptrVal := reflect.ValueOf(ptr)
if ptrVal.Kind() != reflect.Ptr {
return fmt.Errorf("Cannot load %T", ptr)
}
val := ptrVal.Elem()
typ := val.Type()
data, ok := m.state[typ]
if !ok {
return fmt.Errorf("Cannot load %T", ptr)
}
val.Set(reflect.ValueOf(data))
return nil
}
func ModelFromThread(t *starlark.Thread) (Model, error) {
model, ok := t.Local(modelKey).(Model)
if !ok {
return Model{}, fmt.Errorf("Internal error: Starlark not initialized correctly: starkit.Model not found")
}
return model, nil
}
func ContextFromThread(t *starlark.Thread) (context.Context, error) {
ctx, ok := t.Local(ctxKey).(context.Context)
if !ok {
return nil, fmt.Errorf("Internal error Starlark not initialized correctly: starkit.Ctx not found")
}
return ctx, nil
}