-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathtable.go
70 lines (53 loc) · 1.02 KB
/
table.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
package snail
import (
"errors"
"os"
)
var (
errorTableFull = errors.New("table is full")
errorTableFlushed = errors.New("table is already flushed")
)
type Table struct {
ptr int
cap int
isFlushed bool
buf []byte
}
func newTable(cap int) Table {
return Table{
ptr: 0,
cap: cap,
isFlushed: false,
buf: make([]byte, cap),
}
}
func (t *Table) flush(filePath string) error {
if t.isFlushed {
return errorTableFlushed
}
f, err := os.OpenFile(filePath, os.O_APPEND|os.O_WRONLY|os.O_CREATE, 0600)
if err != nil {
return err
}
defer f.Close()
if _, err = f.Write(t.buf[:t.ptr]); err != nil {
return err
}
t.isFlushed = true
return nil
}
func (t *Table) space(cfg *Config) int {
return cfg.TableSize - t.ptr
}
func (t *Table) write(cfg *Config, src *[]byte) (int, error) {
if t.isFlushed {
return 0, errorTableFlushed
}
l := len(*src)
if int(l) > cfg.TableSize-t.ptr {
return 0, errorTableFull
}
n := copy(t.buf[t.ptr:], *src)
t.ptr += n
return int(n), nil
}