-
Notifications
You must be signed in to change notification settings - Fork 4
/
pos.go
100 lines (80 loc) · 1.79 KB
/
pos.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the MIT License.
// This product includes software developed at Guance Cloud (https://www.guance.com/).
// Copyright 2021-present Guance, Inc.
package diskcache
import (
"bytes"
"encoding/binary"
"encoding/json"
"fmt"
"os"
"path/filepath"
)
type pos struct {
Seek int64 `json:"seek"`
Name []byte `json:"name"`
fname string // where to dump the binary data
buf *bytes.Buffer // reused buffer to build the binary data
}
func (p *pos) String() string {
return fmt.Sprintf("%s:%d", string(p.Name), p.Seek)
}
func posFromFile(fname string) (*pos, error) {
bin, err := os.ReadFile(filepath.Clean(fname))
if err != nil {
return nil, err
}
if len(bin) <= 8 {
return nil, nil
}
var p pos
if err := p.UnmarshalBinary(bin); err != nil {
return nil, err
}
return &p, nil
}
func (p *pos) MarshalBinary() ([]byte, error) {
if p.buf == nil {
p.buf = new(bytes.Buffer)
}
p.buf.Reset()
if err := binary.Write(p.buf, binary.LittleEndian, p.Seek); err != nil {
return nil, err
}
if _, err := p.buf.Write(p.Name); err != nil {
return nil, err
}
return p.buf.Bytes(), nil
}
func (p *pos) UnmarshalBinary(bin []byte) error {
p.buf = bytes.NewBuffer(bin)
if err := binary.Read(p.buf, binary.LittleEndian, &p.Seek); err != nil {
return err
}
p.Name = p.buf.Bytes()
return nil
}
func (p *pos) reset() error {
p.Seek = -1
p.Name = nil
if p.buf != nil {
p.buf.Reset()
}
return p.dumpFile()
}
func (p *pos) dumpFile() error {
if data, err := p.MarshalBinary(); err != nil {
return err
} else {
return os.WriteFile(p.fname, data, 0o600)
}
}
// for benchmark.
func (p *pos) dumpJSON() ([]byte, error) {
j, err := json.Marshal(p)
if err != nil {
return nil, err
}
return j, nil
}