-
Notifications
You must be signed in to change notification settings - Fork 100
/
ptr_gen.py
66 lines (51 loc) · 1.01 KB
/
ptr_gen.py
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
#!/usr/bin/env python
from string import Template
import sys
HEADER = Template('''\
package goquic
import (
"sync"
"math"
)
// Generated by `ptr_gen.py ${args}`
// Do not edit manually!
''')
TMPL = Template('''\
var ${inst}Ptr = &${cls}Ptr{pool: make(map[int64]*${cls})}
type ${cls}Ptr struct {
sync.RWMutex
pool map[int64]*${cls}
index int64
}
func (p *${cls}Ptr) Get(key int64) *${cls} {
p.RLock()
defer p.RUnlock()
return p.pool[key]
}
func (p *${cls}Ptr) Set(pt *${cls}) int64 {
p.Lock()
defer p.Unlock()
for {
if _, ok := p.pool[p.index]; !ok {
break
}
p.index += 1
if p.index == math.MaxInt64 {
p.index = 0
}
}
p.pool[p.index] = pt
p.index += 1
return p.index - 1
}
func (p *${cls}Ptr) Del(key int64) {
p.Lock()
defer p.Unlock()
delete(p.pool, key)
}
''')
if __name__ == "__main__":
with open("ptr.go", "w") as f:
f.write(HEADER.substitute(args=" ".join(sys.argv[1:])))
for t in sys.argv[1:]:
f.write(TMPL.substitute(cls=t, inst=t[0].lower()+t[1:]))