-
Notifications
You must be signed in to change notification settings - Fork 3
/
utils.go
68 lines (59 loc) · 1.48 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
package gonut
import (
"bytes"
crand "crypto/rand"
"encoding/binary"
"io"
"math/rand"
"reflect"
"time"
"unsafe"
)
func makeRandomStr(table string, length int) string {
bs := []byte(table)
var result []byte
r := rand.New(rand.NewSource(time.Now().UnixNano()))
for i := 0; i < length; i++ {
result = append(result, bs[r.Intn(len(bs))])
}
return string(result)
}
// GenRandomString Generates a pseudo-random string
// donut/donut.c
// static int gen_random_string(void *output, uint64_t len) { ... }
func GenRandomString(length int) string {
return makeRandomStr("HMN34P67R9TWCXYF", length) // https://stackoverflow.com/a/27459196
}
// GenRandomBytes Generates pseudo-random bytes.
// donut/donut.c
// static int gen_random(void *buf, uint64_t len) { ... }
func GenRandomBytes(n int) []byte {
b := make([]byte, n)
if _, err := io.ReadFull(crand.Reader, b); err != nil {
panic(err)
}
return b
}
func BytesToStruct(buf []byte, v any) error {
return binary.Read(bytes.NewReader(buf), binary.LittleEndian, v)
}
func StructToBytes(v any) []byte {
buffer := bytes.NewBuffer(nil)
if err := binary.Write(buffer, binary.LittleEndian, v); err != nil {
panic(err)
}
return buffer.Bytes()
}
func UnsafeStructToBytes(ptr any) []byte {
v := reflect.ValueOf(ptr)
if v.Kind() != reflect.Pointer {
panic("need a pointer")
}
return *(*[]byte)(unsafe.Pointer(
&reflect.SliceHeader{
Data: v.Pointer(),
Len: int(v.Elem().Type().Size()),
Cap: int(v.Elem().Type().Size()),
},
))
}