/
save.go
109 lines (93 loc) · 2.14 KB
/
save.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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package save
import (
"bufio"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"os"
"strings"
)
func ToBytes(slice []float64) []byte {
byteSlice := make([]byte, 8*len(slice))
for i, f := range slice {
binary.LittleEndian.PutUint64(byteSlice[i*8:(i+1)*8], math.Float64bits(f))
}
return byteSlice
}
func FromBytes(byteSlice []byte) []float64 {
floatSlice := make([]float64, len(byteSlice)/8)
for i := range floatSlice {
bits := binary.LittleEndian.Uint64(byteSlice[i*8 : (i+1)*8])
floatSlice[i] = math.Float64frombits(bits)
}
return floatSlice
}
func ConstantsToBytes(constants ...int) []byte {
bytes := make([]byte, 4*len(constants))
for i, c := range constants {
binary.LittleEndian.PutUint32(bytes[i*4:(i+1)*4], uint32(c))
}
return bytes
}
func ConstantsFromBytes(bytes []byte) []int {
ints := make([]int, len(bytes)/4)
for i := range ints {
ints[i] = int(binary.LittleEndian.Uint32(bytes[i*4 : (i+1)*4]))
}
return ints
}
func recursivelyCreateFolders(path []string) {
cwd := path[0]
for i := range path {
if _, err := os.Stat(cwd); errors.Is(err, os.ErrNotExist) {
os.Mkdir(cwd, os.ModePerm)
}
if i < len(path)-1 {
cwd += "/" + path[i+1]
}
}
}
func WriteBytesToFile(path string, bytes []byte) {
pathSteps := strings.Split(path, "/")
if len(pathSteps) > 1 {
recursivelyCreateFolders(pathSteps[:len(pathSteps)-1])
}
f, e := os.Create(path)
if e != nil {
fmt.Println("\n\nError saving your network to a file!")
panic(e)
}
defer f.Close()
_, err := f.Write(bytes)
if err != nil {
fmt.Println("\n\nError saving your network to a file!")
panic(err)
}
}
func WriteToFile(path string, value string) {
WriteBytesToFile(path, []byte(value))
}
func ReadBytesFromFile(path string) []byte {
file, err := os.Open(path)
if err != nil {
panic(err)
}
defer file.Close()
// Get the file size
stat, err := file.Stat()
if err != nil {
panic(err)
}
// Read the file into a byte slice
bytes := make([]byte, stat.Size())
_, err = bufio.NewReader(file).Read(bytes)
if err != nil && err != io.EOF {
panic(err)
}
return bytes
}
func ReadFromFile(path string) string {
return string(ReadBytesFromFile(path))
}