forked from lekatariba2006/ppcap
-
Notifications
You must be signed in to change notification settings - Fork 0
/
bufferedwriter.go
62 lines (53 loc) · 1.24 KB
/
bufferedwriter.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 ppcap
import (
"errors"
"os"
)
type BufferedWriter struct {
bufferOffset int64
bufferUsed int
bufferAvail int
buf []byte
fd *os.File
}
func NewBufferedWriter(fd *os.File, bufferByteCount int) (*BufferedWriter, error) {
off, err := fd.Seek(0, os.SEEK_END)
if err != nil {
return nil, err
}
return &BufferedWriter{
off,
0,
bufferByteCount,
make([]byte, bufferByteCount),
fd}, nil
}
func (io *BufferedWriter) Flush() error {
if 0 == io.bufferUsed {
return nil
}
if _, err := io.fd.WriteAt(io.buf[:io.bufferUsed], io.bufferOffset); err != nil {
return err
}
if err := io.fd.Sync(); err != nil {
return err
}
io.bufferOffset += int64(io.bufferUsed)
io.bufferAvail = len(io.buf)
io.bufferUsed = 0
return nil
}
func (io *BufferedWriter) GetBuffer(byteCount int) ([]byte, error) {
if byteCount > len(io.buf) {
return nil, errors.New("ppcap.BufferedWriter.GetBuffer: requested size exceeds maximum")
}
if byteCount > io.bufferAvail {
if err := io.Flush(); err != nil {
return nil, err
}
}
buf := io.buf[io.bufferUsed : io.bufferUsed+byteCount]
io.bufferAvail -= byteCount
io.bufferUsed += byteCount
return buf, nil
}