-
Notifications
You must be signed in to change notification settings - Fork 1
/
utils.go
80 lines (71 loc) · 1.98 KB
/
utils.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
69
70
71
72
73
74
75
76
77
78
79
80
package qdb
/*
#include <qdb/client.h>
#include <stdlib.h>
*/
import "C"
import (
"math"
"math/rand"
"time"
"unsafe"
)
func convertToCharStarStar(toConvert []string) unsafe.Pointer {
var v *C.char
ptrSize := unsafe.Sizeof(v)
size := len(toConvert)
data := C.malloc(C.size_t(size) * C.size_t(ptrSize))
for i := 0; i < size; i++ {
element := (**C.char)(unsafe.Pointer(uintptr(data) + uintptr(i)*ptrSize))
*element = (*C.char)(convertToCharStar(toConvert[i]))
}
return data
}
func releaseCharStarStar(data unsafe.Pointer, size int) {
var v *C.char
ptrSize := unsafe.Sizeof(v)
for i := 0; i < size; i++ {
element := (**C.char)(unsafe.Pointer(uintptr(data) + uintptr(i)*ptrSize))
releaseCharStar(*element)
}
C.free(data)
}
func convertToCharStar(toConvert string) *C.char {
if len(toConvert) == 0 {
return nil
}
return C.CString(toConvert)
}
func releaseCharStar(data *C.char) {
if data != nil {
C.free(unsafe.Pointer(data))
}
}
const letterBytes = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
const (
letterIdxBits = 6 // 6 bits to represent a letter index
letterIdxMask = 1<<letterIdxBits - 1 // All 1-bits, as many as letterIdxBits
letterIdxMax = 63 / letterIdxBits // # of letter indices fitting in 63 bits
)
func generateAlias(n int) string {
nanos := int64(time.Now().UnixNano())
b := make([]byte, n)
// A rand.Int63() generates 63 random bits, enough for letterIdxMax letters!
rand.Seed(nanos)
for i, cache, remain := n-1, rand.Int63(), letterIdxMax; i >= 0; {
if remain == 0 {
cache, remain = rand.Int63(), letterIdxMax
}
if idx := int(cache & letterIdxMask); idx < len(letterBytes) {
b[i] = letterBytes[idx]
i--
}
cache >>= letterIdxBits
remain--
}
return string(b)
}
func charStarArrayToSlice(strings **C.char, length int) []*C.char {
// See https://github.com/mattn/go-sqlite3/issues/238 for details.
return (*[(math.MaxInt32 - 1) / unsafe.Sizeof((*C.char)(nil))]*C.char)(unsafe.Pointer(strings))[:length:length]
}