-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcore.go
89 lines (75 loc) · 2.49 KB
/
core.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
81
82
83
84
85
86
87
88
89
package hydrogen
// #cgo LDFLAGS: -lhydrogen
// #include <stdlib.h>
// #include <hydrogen.h>
import "C"
import (
"fmt"
"unsafe"
)
func init() {
result := int(C.hydro_init())
if result != 0 {
panic(fmt.Sprintf("hydrogen initialization failed, result code %d.", result))
}
// fmt.Println("libhydrogen initialized")
}
func CheckCtx(ctx string, wantlen int) {
if len(ctx) != wantlen {
panic(fmt.Sprintf("Bad context len. Want (%d), got (%d).", wantlen, len(ctx)))
}
}
// CheckSize checks if the length of a byte slice is equal to the expected length,
// and panics when this is not the case.
func CheckSize(buf []byte, expected int, descrip string) {
if len(buf) != expected {
panic(fmt.Sprintf("Invalid \"%s\" size. Want (%d), got (%d).", descrip, expected, len(buf)))
}
}
// CheckIntInRange checks if the size of an integer is between a lower and upper boundaries.
func CheckIntInRange(n int, min int, max int, descrip string) {
if n < min || n > max {
panic(fmt.Sprintf("Invalid \"%s\" size. Want (%d - %d), got (%d).", descrip, min, max, n))
}
}
// CheckIntGt checks if n is > lower
func CheckIntGt(n int, lower int, descrip string) {
if !(n > lower) {
panic(fmt.Sprintf("%s is not > %d", descrip, lower))
}
}
// CheckIntMin checks if n is > lower
func CheckIntGtOrEq(n int, lower int, descrip string) {
if !(n >= lower) {
panic(fmt.Sprintf("%s is not >= %d", descrip, lower))
}
}
// MemZero sets the buffer to zero
func MemZero(buf []byte) {
if len(buf) > 0 {
C.hydro_memzero(unsafe.Pointer(&buf[0]), C.size_t(len(buf)))
}
}
// NOTE: not a lexicographic comparator, not a replacement for memcmp
// bool hydro_equal(const void *b1_, const void *b2_, size_t len);
func MemEqual(buff1, buff2 []byte, length int) bool {
if length != len(buff1) || length != len(buff2) {
panic(fmt.Sprintf("MemEqual: One or more buf lens (%d, %d) != %d",
len(buff1), len(buff2), length))
}
return bool(C.hydro_equal(unsafe.Pointer(&buff1[0]), unsafe.Pointer(&buff2[0]), C.size_t(length)))
}
func Bin2hex(bin []byte) string {
maxlen := len(bin)*2 + 1
binPtr := (*C.uchar)(unsafe.Pointer(&bin[0]))
buf := (*C.char)(C.malloc(C.size_t(maxlen)))
defer C.free(unsafe.Pointer(buf))
C.hydro_bin2hex(buf, C.size_t(maxlen), binPtr, C.size_t(len(bin)))
return C.GoString(buf)
}
// AlignedSlice returns a memory aligned slice
func AlignedSlice(size, alignment int) []byte {
slice := make([]byte, size+alignment)
offset := alignment - int(uintptr(unsafe.Pointer(&slice[0])))%alignment
return slice[offset : offset+size]
}