-
Notifications
You must be signed in to change notification settings - Fork 1
/
writer.go
71 lines (62 loc) · 1.44 KB
/
writer.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
package fsutil
import (
"bufio"
"os"
"github.com/3JoB/unsafeConvert"
)
type nn struct {
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 = OpenFile(path, os.O_WRONLY|os.O_CREATE, 0666)
if err != nil {
return nil, err
}
n.writer = bufio.NewWriter(n.os)
return n, nil
}
// 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.BytesReflect(w.(string)))
}
return
}
// 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.BytesReflect(w))
return err
}
// Flush writes any buffered data to the underlying io.Writer.
func (n *nn) Flush() error {
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
}
n.os = nil
return nil
}