callbacks: use uintptr instead of int as index

Since the index of the registered callbacks is basically only used as
void*/unsafe.Pointer, it makes more sense and code simpler, if
the index type is uintptr instead of a simple int.

Signed-off-by: Sven Anderson <sven@redhat.com>
This commit is contained in:
Sven Anderson 2020-08-26 00:01:14 +02:00 committed by John Mulligan
parent 9cd28289b5
commit 176a163c3c
3 changed files with 9 additions and 9 deletions

View File

@ -19,17 +19,17 @@ import (
// to control and validate what "callbacks" get used.
type Callbacks struct {
mutex sync.RWMutex
cmap map[int]interface{}
cmap map[uintptr]interface{}
}
// New returns a new callbacks tracker.
func New() *Callbacks {
return &Callbacks{cmap: make(map[int]interface{})}
return &Callbacks{cmap: make(map[uintptr]interface{})}
}
// Add a callback/object to the tracker and return a new index
// for the object.
func (cb *Callbacks) Add(v interface{}) int {
func (cb *Callbacks) Add(v interface{}) uintptr {
cb.mutex.Lock()
defer cb.mutex.Unlock()
// this approach assumes that there are typically very few callbacks
@ -38,7 +38,7 @@ func (cb *Callbacks) Add(v interface{}) int {
// until we find a free key like in the cgo wiki page.
// If this code ever becomes a hot path there's surely plenty of room
// for optimization in the future :-)
index := len(cb.cmap) + 1
index := uintptr(len(cb.cmap) + 1)
for {
if _, found := cb.cmap[index]; !found {
break
@ -50,14 +50,14 @@ func (cb *Callbacks) Add(v interface{}) int {
}
// Remove a callback/object given it's index.
func (cb *Callbacks) Remove(index int) {
func (cb *Callbacks) Remove(index uintptr) {
cb.mutex.Lock()
defer cb.mutex.Unlock()
delete(cb.cmap, index)
}
// Lookup returns a mapped callback/object given an index.
func (cb *Callbacks) Lookup(index int) interface{} {
func (cb *Callbacks) Lookup(index uintptr) interface{} {
cb.mutex.RLock()
defer cb.mutex.RUnlock()
return cb.cmap[index]

View File

@ -126,7 +126,7 @@ func (image *Image) DiffIterate(config DiffIterateConfig) error {
func diffIterateCallback(
offset C.uint64_t, length C.size_t, exists C.int, index unsafe.Pointer) C.int {
v := diffIterateCallbacks.Lookup(int(uintptr(index)))
v := diffIterateCallbacks.Lookup(uintptr(index))
config := v.(DiffIterateConfig)
return C.int(config.Callback(
uint64(offset), uint64(length), int(exists), config.Data))

View File

@ -95,7 +95,7 @@ type Watch struct {
image *Image
wcc watchCallbackCtx
handle C.uint64_t
cbIndex int
cbIndex uintptr
}
// UpdateWatch updates the image object to watch metadata changes to the
@ -146,7 +146,7 @@ func (w *Watch) Unwatch() error {
//export imageWatchCallback
func imageWatchCallback(index unsafe.Pointer) {
v := watchCallbacks.Lookup(int(uintptr(index)))
v := watchCallbacks.Lookup(uintptr(index))
wcc := v.(watchCallbackCtx)
wcc.callback(wcc.data)
}