-
Notifications
You must be signed in to change notification settings - Fork 1
/
writer.go
94 lines (79 loc) · 1.65 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
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
package sqlitefs
import (
"mime"
"path/filepath"
)
const fragmentSize = 16 * 1024 // 16 КБ
type SQLiteWriter struct {
fs *SQLiteFS
path string
buffer []byte
fragmentSize int
fragmentIndex int
fileCreated bool
}
func NewSQLiteWriter(fs *SQLiteFS, path string) *SQLiteWriter {
return &SQLiteWriter{
fs: fs,
path: path,
fragmentSize: fragmentSize,
buffer: make([]byte, 0, fragmentSize),
}
}
func (w *SQLiteWriter) Write(p []byte) (n int, err error) {
n = len(p)
w.buffer = append(w.buffer, p...)
for len(w.buffer) >= w.fragmentSize {
err = w.writeFragment()
if err != nil {
return len(p) - len(w.buffer), err
}
}
return n, nil
}
func (w *SQLiteWriter) writeFragment() error {
if !w.fileCreated {
err := w.createFileRecord()
if err != nil {
return err
}
w.fileCreated = true
}
writeSize := min(len(w.buffer), w.fragmentSize)
respCh := make(chan error)
w.fs.writeCh <- writeRequest{
path: w.path,
data: w.buffer[:writeSize],
index: w.fragmentIndex,
respCh: respCh,
}
err := <-respCh
if err == nil {
w.buffer = w.buffer[writeSize:]
w.fragmentIndex++
}
return err
}
func (w *SQLiteWriter) createFileRecord() error {
ext := filepath.Ext(w.path)
mimeType := mime.TypeByExtension(ext)
if mimeType == "" {
mimeType = "application/octet-stream"
}
respCh := make(chan error)
w.fs.writeCh <- writeRequest{
path: w.path,
mimeType: mimeType,
respCh: respCh,
}
return <-respCh
}
func (w *SQLiteWriter) Close() error {
for len(w.buffer) > 0 || !w.fileCreated {
err := w.writeFragment()
if err != nil {
return err
}
}
return nil
}