-
Notifications
You must be signed in to change notification settings - Fork 1
/
buffer.go
69 lines (61 loc) · 1.2 KB
/
buffer.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
package ubuffer
import (
"bytes"
"io/ioutil"
"os"
)
const MEMSIZE = 50 * (1 << 20)
type Buffer struct {
mem *bytes.Buffer
swap *os.File
}
func NewBuffer(cap int64) *Buffer {
var (
mem = new(bytes.Buffer)
swap *os.File = nil
err error
)
if cap > MEMSIZE {
swap, err = ioutil.TempFile("", "ubuffer-*")
if err != nil || swap == nil || swap.Close() != nil{
return nil
}
swap, err = os.OpenFile(swap.Name(), os.O_APPEND | os.O_RDWR, 0644)
if err != nil {
return nil
}
}
return &Buffer{
mem: mem,
swap: swap,
}
}
func (buffer *Buffer) Finalize() error {
buffer.mem.Reset()
if buffer.swap != nil {
err := buffer.swap.Close()
if err != nil {
return err
}
return os.Remove(buffer.swap.Name())
}
return nil
}
func (buffer *Buffer) Write(p []byte) (n int, err error) {
if buffer.swap != nil {
return buffer.swap.Write(p[:])
}
return buffer.mem.Write(p[:])
}
func (buffer *Buffer) Read(p []byte) (n int, err error) {
if buffer.swap != nil {
return buffer.swap.Read(p[:])
}
return buffer.mem.Read(p[:])
}
func (buffer *Buffer) Seek(offset int64, whence int) (ret int64, err error) {
if buffer.swap != nil {
return buffer.swap.Seek(offset, whence)
}
return 0, nil
}