forked from libgit2/git2go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
handles.go
68 lines (57 loc) · 1.22 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
package git
/*
#include <stdlib.h>
*/
import "C"
import (
"fmt"
"sync"
"unsafe"
)
type HandleList struct {
doNotCompare
sync.RWMutex
// stores the Go pointers
handles map[unsafe.Pointer]interface{}
}
func NewHandleList() *HandleList {
return &HandleList{
handles: make(map[unsafe.Pointer]interface{}),
}
}
// Track adds the given pointer to the list of pointers to track and
// returns a pointer value which can be passed to C as an opaque
// pointer.
func (v *HandleList) Track(pointer interface{}) unsafe.Pointer {
handle := C.malloc(1)
v.Lock()
v.handles[handle] = pointer
v.Unlock()
return handle
}
// Untrack stops tracking the pointer given by the handle
func (v *HandleList) Untrack(handle unsafe.Pointer) {
v.Lock()
delete(v.handles, handle)
C.free(handle)
v.Unlock()
}
// Clear stops tracking all the managed pointers.
func (v *HandleList) Clear() {
v.Lock()
for handle := range v.handles {
delete(v.handles, handle)
C.free(handle)
}
v.Unlock()
}
// Get retrieves the pointer from the given handle
func (v *HandleList) Get(handle unsafe.Pointer) interface{} {
v.RLock()
defer v.RUnlock()
ptr, ok := v.handles[handle]
if !ok {
panic(fmt.Sprintf("invalid pointer handle: %p", handle))
}
return ptr
}