-
Notifications
You must be signed in to change notification settings - Fork 1
/
memory.go
108 lines (91 loc) · 1.79 KB
/
memory.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
package memory
import "fmt"
const (
sizeInt8 = 1
sizeInt16 = sizeInt8 << 1
sizeInt32 = sizeInt16 << 1
sizeInt64 = sizeInt32 << 1
)
type Memory struct {
g grid
h heap
}
type Opt func(*Memory)
func PreallocGrid(size uint32) Opt {
return func(m *Memory) {
m.g.grow(size)
}
}
func PreallocHeap(size uint32) Opt {
return func(m *Memory) {
m.h.grow(size)
}
}
func New(opts ...Opt) Memory {
m := Memory{}
for _, opt := range opts {
opt(&m)
}
return m
}
func (b *Memory) Reset() {
b.g.reset()
b.h.reset()
}
func (b *Memory) alloc(t Type, size uint32) Addr {
buf := b.h.alloc(size)
return NewAddr(t, buf...)
}
func (b *Memory) Alloc(in interface{}) (Addr, error) {
switch v := in.(type) {
case []byte:
return b.AllocBytesAddr(v), nil
case string:
return b.AllocBytesAddr([]byte(v)), nil
case int:
return b.AllocInt64(int64(v)), nil
case int64:
return b.AllocInt64(v), nil
case bool:
if v {
return True, nil
}
return False, nil
case []interface{}:
vec := b.AllocVector(uint32(len(v)))
for i, e := range v {
addr, err := b.Alloc(e)
if err != nil {
return Nil, err
}
vec.SetVectorAt(i, addr)
}
return vec, nil
default:
return Nil, fmt.Errorf("memory: unsupported type %T", v)
}
}
func (b *Memory) AllocBytesAddr(dat []byte) Addr {
return NewAddr(TypeBytes, dat...)
}
func (b *Memory) AllocBytes(size uint32) Addr {
if size == 0 {
return NoBytes
}
return b.alloc(TypeBytes, size)
}
func (b *Memory) AllocInt64(v int64) Addr {
addr := b.alloc(TypeInt64, sizeInt64)
addr.SetInt64(v)
return addr
}
func (b *Memory) AllocVector(size uint32) Addr {
addr := NewAddr(TypeVector)
addr.vec = b.g.alloc(size)
return addr
}
func (b *Memory) CopyVector(elems ...Addr) Addr {
addr := b.AllocVector(uint32(len(elems)))
addr.CopyVector(elems)
return addr
}