-
Notifications
You must be signed in to change notification settings - Fork 1
/
fsm_binaryfile.go
121 lines (95 loc) · 2.24 KB
/
fsm_binaryfile.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
110
111
112
113
114
115
116
117
118
119
120
121
// 二进制文件读写实现
package fsm
import (
"bytes"
"encoding/binary"
"fmt"
"io"
"math"
"os"
)
func (f *fileHashmap) readByte(absPos int64, size uint64, file *os.File) []byte {
if file == nil {
panic(fmt.Errorf("file not open"))
}
if size >= DefaultMaxValueSize {
return nil
}
byteString := make([]byte, size)
if _, err := file.ReadAt(byteString, absPos); err != nil {
if err == io.EOF {
return nil
}
panic(err)
}
return byteString
}
func (f *fileHashmap) writeByte(absPos int64, value []byte, file *os.File) {
if file == nil {
panic(fmt.Errorf("file not open"))
}
if value == nil || len(value) == 0 || len(value) >= DefaultMaxValueSize {
return
}
if _, err := file.WriteAt(value, absPos); err != nil {
panic(err)
}
}
func (f *fileHashmap) writeUInt32(absPos int64, val uint32, file *os.File) {
if file == nil {
panic(fmt.Errorf("file not open"))
}
var byteString bytes.Buffer
if err := binary.Write(&byteString, binary.LittleEndian, val); err != nil {
panic(err)
}
if _, err := file.WriteAt(byteString.Bytes(), absPos); err != nil {
panic(err)
}
}
func (f *fileHashmap) readUInt32(absPos int64, file *os.File) uint32 {
if file == nil {
panic(fmt.Errorf("file not open"))
}
var val uint32
byteString := make([]byte, 4)
if _, err := file.ReadAt(byteString, absPos); err != nil {
if err == io.EOF {
return math.MaxUint32
}
panic(err)
}
if err := binary.Read(bytes.NewBuffer(byteString), binary.LittleEndian, &val); err != nil {
panic(err)
}
return val
}
func (f *fileHashmap) writeUInt64(absPos int64, val uint64, file *os.File) {
if file == nil {
panic(fmt.Errorf("file not open"))
}
var buf bytes.Buffer
if err := binary.Write(&buf, binary.LittleEndian, val); err != nil {
panic(err)
}
if _, err := file.WriteAt(buf.Bytes(), absPos); err != nil {
panic(err)
}
}
func (f *fileHashmap) readUInt64(absPos int64, file *os.File) uint64 {
if file == nil {
panic(fmt.Errorf("file not open"))
}
var val uint64
byteString := make([]byte, 8)
if _, err := file.ReadAt(byteString, absPos); err != nil {
if err == io.EOF {
return 0
}
panic(err)
}
if err := binary.Read(bytes.NewBuffer(byteString), binary.LittleEndian, &val); err != nil {
panic(err)
}
return val
}