-
Notifications
You must be signed in to change notification settings - Fork 0
/
utils.go
executable file
·62 lines (54 loc) · 1.07 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
package kvod
import (
"bytes"
"crypto/rand"
"encoding/gob"
"io/ioutil"
"os"
)
func serialize[T any](data T) ([]byte, error) {
var buffer bytes.Buffer
enc := gob.NewEncoder(&buffer)
err := enc.Encode(data)
return buffer.Bytes(), err
}
func deserialize[T any](data []byte, ret T) error {
var buffer bytes.Buffer
buffer.Write(data)
dec := gob.NewDecoder(&buffer)
return dec.Decode(ret)
}
func write(filename string, data []byte) error {
file, err := os.OpenFile(
filename,
os.O_WRONLY|os.O_TRUNC|os.O_CREATE,
0660,
)
if err != nil {
return err
}
defer file.Close()
_, err = file.Write(data)
if err != nil {
return err
}
return nil
}
func read(filename string) ([]byte, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
data, err := ioutil.ReadAll(file)
if err != nil {
return nil, err
}
return data, nil
}
// GenerateRandom generates a random of size provided
func GenerateRandom(size int) ([]byte, error) {
randomData := make([]byte, size)
_, err := rand.Reader.Read(randomData)
return randomData, err
}