Debian Codegraph @

lmdb/msgfunc.go

raw symbols SCIP
1 package lmdb
2
3 /*
4 #include "lmdbgo.h"
5 */
6 import "C"
7 import (
8 "sync"
9 "sync/atomic"
10 )
11
12 // lmdbgoMDBMsgFuncBridge provides a static C function for handling MDB_msgfunc
13 // callbacks. It performs string conversion and dynamic dispatch to a msgfunc
14 // provided to Env.ReaderList. Any error returned by the msgfunc is cached and
15 // -1 is returned to terminate the iteration.
16
17 //export lmdbgoMDBMsgFuncBridge
18 func lmdbgoMDBMsgFuncBridge(cmsg C.lmdbgo_ConstCString, _ctx C.size_t) C.int {
19 ctx := msgctx(_ctx).get()
20 msg := C.GoString(cmsg.p)
21 err := ctx.fn(msg)
22 if err != nil {
23 ctx.err = err
24 return -1
25 }
26 return 0
27 }
28
29 type msgfunc func(string) error
30
31 // msgctx is the type used for context pointers passed to mdb_reader_list. A
32 // msgctx stores its corresponding msgfunc, and any error encountered in an
33 // external map. The corresponding function is called once for each
34 // mdb_reader_list entry using the msgctx.
35 //
36 // An External map is used because struct pointers passed to C functions must
37 // not contain pointers in their struct fields. See the following language
38 // proposal which discusses the restrictions on passing pointers to C.
39 //
40 // https://github.com/golang/proposal/blob/master/design/12416-cgo-pointers.md
41 type msgctx uintptr
42 type _msgctx struct {
43 fn msgfunc
44 err error
45 }
46
47 var msgctxn uint32
48 var msgctxm = map[msgctx]*_msgctx{}
49 var msgctxmlock sync.RWMutex
50
51 func nextctx() msgctx {
52 return msgctx(atomic.AddUint32(&msgctxn, 1))
53 }
54
55 func newMsgFunc(fn msgfunc) (ctx msgctx, done func()) {
56 ctx = nextctx()
57 ctx.register(fn)
58 return ctx, ctx.deregister
59 }
60
61 func (ctx msgctx) register(fn msgfunc) {
62 msgctxmlock.Lock()
63 if _, ok := msgctxm[ctx]; ok {
64 msgctxmlock.Unlock()
65 panic("msgfunc conflict")
66 }
67 msgctxm[ctx] = &_msgctx{fn: fn}
68 msgctxmlock.Unlock()
69 }
70
71 func (ctx msgctx) deregister() {
72 msgctxmlock.Lock()
73 delete(msgctxm, ctx)
74 msgctxmlock.Unlock()
75 }
76
77 func (ctx msgctx) get() *_msgctx {
78 msgctxmlock.RLock()
79 _ctx := msgctxm[ctx]
80 msgctxmlock.RUnlock()
81 return _ctx
82 }