-
Notifications
You must be signed in to change notification settings - Fork 0
/
mempool.go
120 lines (96 loc) · 2.14 KB
/
mempool.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
package lsystem
type Buffer struct {
BytePairs []TokenStateId
Len int
Cap int
}
func (m *Buffer) Append(bp TokenStateId) {
if m.Len >= m.Cap {
m.Grow(m.Len)
}
m.BytePairs[m.Len] = bp
m.Len++
}
func (m *Buffer) AppendSlice(bps []TokenStateId) {
if m.Len+len(bps) > m.Cap {
m.Grow(m.Len + len(bps))
}
copy(m.BytePairs[m.Len:], bps)
m.Len += len(bps)
}
func (m *Buffer) Grow(atLeast int) {
newCap := int(float32(atLeast) * 1.5)
m.Cap = newCap
newSlice := make([]TokenStateId, newCap)
copy(newSlice, m.BytePairs)
m.BytePairs = newSlice
}
const threadCount = 4
type MemPool struct {
readBuffers [threadCount]*Buffer
writeBuffers [threadCount]*Buffer
swap [threadCount]bool
}
func NewMemPool(capacity int) *MemPool {
readBuffers := [threadCount]*Buffer{}
writeBuffers := [threadCount]*Buffer{}
swapValues := [threadCount]bool{}
for i := 0; i < threadCount; i++ {
readBuffers[i] = &Buffer{
BytePairs: make([]TokenStateId, capacity),
Len: 0,
Cap: capacity,
}
writeBuffers[i] = &Buffer{
BytePairs: make([]TokenStateId, capacity),
Len: 0,
Cap: capacity,
}
}
return &MemPool{
readBuffers: readBuffers,
writeBuffers: writeBuffers,
swap: swapValues,
}
}
func (m *MemPool) GetReadBuffer(idx int) *Buffer {
if m.swap[idx] {
return m.writeBuffers[idx]
}
return m.readBuffers[idx]
}
func (m *MemPool) GetWriteBuffer(idx int) *Buffer {
if m.swap[idx] {
return m.readBuffers[idx]
}
return m.writeBuffers[idx]
}
func (m *MemPool) SwapAll() {
for i := 0; i < threadCount; i++ {
m.swap[i] = !m.swap[i]
writeBuf := m.GetWriteBuffer(i)
writeBuf.Len = 0
}
}
func (m *MemPool) Swap(idx int) {
m.swap[idx] = !m.swap[idx]
writeBuf := m.GetWriteBuffer(idx)
writeBuf.Len = 0
}
func (m *MemPool) Reset() {
for i := 0; i < threadCount; i++ {
readBuf := m.GetReadBuffer(i)
readBuf.Len = 0
writeBuf := m.GetWriteBuffer(i)
writeBuf.Len = 0
m.swap[i] = false
}
}
func (m *MemPool) ReadAll() []TokenStateId {
tokens := []TokenStateId{}
for i := 0; i < threadCount; i++ {
buf := m.GetReadBuffer(i)
tokens = append(tokens, buf.BytePairs[:buf.Len]...)
}
return tokens
}