gitea

Development moved to Codeberg

  1. 1
  2. 2
  3. 3
  4. 4
  5. 5
  6. 6
  7. 7
  8. 8
  9. 9
  10. 10
  11. 11
  12. 12
  13. 13
  14. 14
  15. 15
  16. 16
  17. 17
  18. 18
  19. 19
  20. 20
  21. 21
  22. 22
  23. 23
  24. 24
  25. 25
  26. 26
  27. 27
  28. 28
  29. 29
  30. 30
  31. 31
  32. 32
  33. 33
  34. 34
  35. 35
  36. 36
  37. 37
  38. 38
  39. 39
  40. 40
  41. 41
  42. 42
  43. 43
  44. 44
  45. 45
  46. 46
  47. 47
  48. 48
  49. 49
  50. 50
  51. 51
  52. 52
  53. 53
  54. 54
  55. 55
  56. 56
  57. 57
  58. 58
  59. 59
  60. 60
  61. 61
  62. 62
  63. 63
  64. 64
  65. 65
  66. 66
  67. 67
  68. 68
  69. 69
  70. 70
  71. 71
  72. 72
  73. 73
  74. 74
  75. 75
  76. 76
  77. 77
  78. 78
  79. 79
  80. 80
  81. 81
  82. 82
  83. 83
  84. 84
  85. 85
  86. 86
  87. 87
  88. 88
  89. 89
  90. 90
  91. 91
  92. 92
  93. 93
// Copyright (C) 2019 Yasuhiro Matsumoto <mattn.jp@gmail.com>.
//
// Use of this source code is governed by an MIT-style
// license that can be found in the LICENSE file.

// +build cgo
// +build sqlite_unlock_notify

package sqlite3

/*
#cgo CFLAGS: -DSQLITE_ENABLE_UNLOCK_NOTIFY

#include <stdlib.h>
#include <sqlite3-binding.h>

extern void unlock_notify_callback(void *arg, int argc);
*/
import "C"
import (
	"fmt"
	"math"
	"sync"
	"unsafe"
)

type unlock_notify_table struct {
	sync.Mutex
	seqnum uint
	table  map[uint]chan struct{}
}

var unt unlock_notify_table = unlock_notify_table{table: make(map[uint]chan struct{})}

func (t *unlock_notify_table) add(c chan struct{}) uint {
	t.Lock()
	defer t.Unlock()
	h := t.seqnum
	t.table[h] = c
	t.seqnum++
	return h
}

func (t *unlock_notify_table) remove(h uint) {
	t.Lock()
	defer t.Unlock()
	delete(t.table, h)
}

func (t *unlock_notify_table) get(h uint) chan struct{} {
	t.Lock()
	defer t.Unlock()
	c, ok := t.table[h]
	if !ok {
		panic(fmt.Sprintf("Non-existent key for unlcok-notify channel: %d", h))
	}
	return c
}

//export unlock_notify_callback
func unlock_notify_callback(argv unsafe.Pointer, argc C.int) {
	for i := 0; i < int(argc); i++ {
		parg := ((*(*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.uint)(nil))]*[1]uint)(argv))[i])
		arg := *parg
		h := arg[0]
		c := unt.get(h)
		c <- struct{}{}
	}
}

//export unlock_notify_wait
func unlock_notify_wait(db *C.sqlite3) C.int {
	// It has to be a bufferred channel to not block in sqlite_unlock_notify
	// as sqlite_unlock_notify could invoke the callback before it returns.
	c := make(chan struct{}, 1)
	defer close(c)

	h := unt.add(c)
	defer unt.remove(h)

	pargv := C.malloc(C.sizeof_uint)
	defer C.free(pargv)

	argv := (*[1]uint)(pargv)
	argv[0] = h
	if rv := C.sqlite3_unlock_notify(db, (*[0]byte)(C.unlock_notify_callback), unsafe.Pointer(pargv)); rv != C.SQLITE_OK {
		return rv
	}

	<-c

	return C.SQLITE_OK
}