-
Notifications
You must be signed in to change notification settings - Fork 1
/
buffer.go
108 lines (94 loc) · 2.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
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
package writer
import (
"bufio"
"io"
"os"
"github.com/3JoB/unsafeConvert"
"github.com/3JoB/ulib/fsutil"
)
type nn struct {
buffer int
maxbuffer int
os *os.File
writer *bufio.Writer
}
// Higher performance sustainable file write operations.
//
// Example Files: `writer_test.go`
func NewWriter(path string) (*nn, error) {
n := &nn{}
var err error
n.os, err = fsutil.OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return nil, err
}
n.writer = bufio.NewWriter(n.os)
return n, nil
}
func (n *nn) CopyTo(to io.Reader) (written int64, err error) {
return fsutil.IoCopy(n.writer, to)
}
func (n *nn) CopyIn(in io.Writer) (written int64, err error) {
n.Flush()
return fsutil.IoCopy(in, n.os)
}
// Write data of type `any` to the buffer (automatically checked)
func (n *nn) Add(w any) (err error) {
switch s := w.(type) {
case string:
err = n.AddString(s)
case []byte:
err = n.AddBytes(s)
default:
_, err = n.writer.Write(unsafeConvert.BytePointer(w.(string)))
}
if err == nil {
if n.maxbuffer == 0 {
return
}
if n.Buffered() > n.maxbuffer {
err = n.Flush()
}
}
return
}
// Set the maximum buffer size, default (unlimited buffer)
//
// Reasonable settings can greatly improve performance.
func (n *nn) MaxBuffer(max int) {
n.maxbuffer = max
}
// Buffered returns the number of bytes that have been written into the current buffer.
func (n *nn) Buffered() int {
n.buffer = n.writer.Buffered()
return n.buffer
}
// Write data of type `[]byte` to the buffer
func (n *nn) AddBytes(w []byte) error {
_, err := n.writer.Write(w)
return err
}
// Write data of type `String` to the buffer
func (n *nn) AddString(w string) error {
_, err := n.writer.Write(unsafeConvert.BytePointer(w))
return err
}
// Flush writes any buffered data to the underlying io.Writer.
func (n *nn) Flush() error {
if n.Buffered() == 0 {
return nil
}
return n.writer.Flush()
}
// Write the data in the buffer to the file and close the IO channel.
//
// Tips: After this operation, please do not continue to operate on the previous pointer!
func (n *nn) Close() error {
if err := n.Flush(); err != nil {
return err
}
if err := n.os.Close(); err != nil {
return err
}
return nil
}