summaryrefslogtreecommitdiff
path: root/handles.go
blob: f5d30f0dad1916fa76693bd001a467665ade676b (plain)
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
package git

import (
	"fmt"
	"sync"
	"unsafe"
)

type HandleList struct {
	sync.RWMutex
	// stores the Go pointers
	handles []interface{}
	// Indicates which indices are in use.
	set map[int]bool
}

func NewHandleList() *HandleList {
	return &HandleList{
		handles: make([]interface{}, 5),
		set:     make(map[int]bool),
	}
}

// findUnusedSlot finds the smallest-index empty space in our
// list. You must only run this function while holding a write lock.
func (v *HandleList) findUnusedSlot() int {
	for i := 1; i < len(v.handles); i++ {
		if !v.set[i] {
			return i
		}
	}

	// reaching here means we've run out of entries so append and
	// return the new index, which is equal to the old length.
	slot := len(v.handles)
	v.handles = append(v.handles, nil)

	return slot
}

// 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 {
	v.Lock()

	slot := v.findUnusedSlot()
	v.handles[slot] = pointer
	v.set[slot] = true

	v.Unlock()

	return unsafe.Pointer(uintptr(slot))
}

// Untrack stops tracking the pointer given by the handle
func (v *HandleList) Untrack(handle unsafe.Pointer) {
	slot := int(uintptr(handle))

	v.Lock()

	v.handles[slot] = nil
	delete(v.set, slot)

	v.Unlock()
}

// Get retrieves the pointer from the given handle
func (v *HandleList) Get(handle unsafe.Pointer) interface{} {
	slot := int(uintptr(handle))

	v.RLock()

	if !v.set[slot] {
		panic(fmt.Sprintf("invalid pointer handle: %p", handle))
	}

	ptr := v.handles[slot]

	v.RUnlock()

	return ptr
}