-
Notifications
You must be signed in to change notification settings - Fork 2
/
handles.go
115 lines (98 loc) · 2.27 KB
/
handles.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
package lang
import (
"context"
"fmt"
"sync"
"github.com/freeconf/lang/pb"
)
// ObjectPool keeps track of golang objects and the destructor that is association with
// the C counterpart that was passed to caller.
type HandlePool struct {
objects map[uint64]any
handles map[any]uint64
counter uint64
lock sync.RWMutex
}
type RemoteObject interface {
GetRemoteHandle() uint64
}
type HandleService struct {
pb.UnimplementedHandlesServer
d *Driver
}
func (s *HandleService) Release(ctx context.Context, in *pb.ReleaseRequest) (*pb.ReleaseResponse, error) {
s.d.handles.Release(in.Hnd)
return &pb.ReleaseResponse{}, nil
}
func newHandlePool() *HandlePool {
return &HandlePool{
objects: make(map[uint64]any),
handles: make(map[any]uint64),
counter: 100,
}
}
func (p *HandlePool) Reserve() uint64 {
p.lock.Lock()
defer p.lock.Unlock()
id := p.NextHnd()
return id
}
func (p *HandlePool) Require(handle uint64) any {
p.lock.Lock()
defer p.lock.Unlock()
x, found := p.objects[handle]
if !found {
panic(fmt.Sprintf("attempting to reference handle %d that was not found", handle))
}
return x
}
func (p *HandlePool) Get(handle uint64) any {
p.lock.Lock()
defer p.lock.Unlock()
return p.objects[handle]
}
// Hnd returns current handle if there is one, otherwise adds this object to the pool
// and returns the new handle
func (p *HandlePool) Hnd(obj any) uint64 {
p.lock.Lock()
defer p.lock.Unlock()
// The go object is really just a handle to an object in x lang then return
// that handle
if rhnd, isRemote := obj.(RemoteObject); isRemote {
return rhnd.GetRemoteHandle()
}
hnd, found := p.handles[obj]
if !found {
hnd = p.NextHnd()
p.handles[obj] = hnd
p.objects[hnd] = obj
}
return hnd
}
func (p *HandlePool) Put(x any) uint64 {
p.lock.Lock()
defer p.lock.Unlock()
hnd := p.NextHnd()
p.objects[hnd] = x
p.handles[x] = hnd
return hnd
}
func (p *HandlePool) NextHnd() uint64 {
next := p.counter
p.counter = p.counter + 1
return next
}
func (p *HandlePool) Record(x any, hnd uint64) {
p.lock.Lock()
defer p.lock.Unlock()
p.objects[hnd] = x
p.handles[x] = hnd
}
func (p *HandlePool) Release(handle uint64) {
p.lock.Lock()
defer p.lock.Unlock()
if obj, found := p.objects[handle]; found {
delete(p.objects, handle)
delete(p.handles, obj)
}
}