-
Notifications
You must be signed in to change notification settings - Fork 3
/
buffer.go
458 lines (370 loc) · 9.64 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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
package buffer
import (
"bytes"
"crypto/rand"
"io"
"io/ioutil"
"os"
"path/filepath"
"unicode/utf8"
"github.com/minio/sio"
"github.com/pkg/errors"
)
const (
// DefaultMaxMemorySize is used when Buffer is created with NewBuffer() or NewBufferString()
DefaultMaxMemorySize = 2 << 20 // 2 MB
)
var (
// ErrBufferFinished is used when Buffer.Write() method is called after Buffer.Read()
ErrBufferFinished = errors.New("buffer is finished")
)
// Buffer is a buffer which can store data on a disk. It isn't thread-safe!
type Buffer struct {
maxInMemorySize int
writingFinished bool
readingFinished bool
size int
offset int
// tempFileDir is a directory for temp files. It is empty by default (so, "ioutil.TempFile" uses os.TempDir)
tempFileDir string
encrypt bool
encryptionKey [32]byte
// buff is used to store data in memory
buff bytes.Buffer
// writeFile is used to write the data on a disk
writeFile io.WriteCloser
// readFile is used to read the data from a disk
readFile io.ReadCloser
useFile bool
filename string
}
// NewBufferWithMaxMemorySize creates a new Buffer with passed maxInMemorySize
func NewBufferWithMaxMemorySize(maxInMemorySize int) *Buffer {
b := &Buffer{
maxInMemorySize: maxInMemorySize,
}
// Grow the internal buffer
// TODO: should we use just maxInMemorySize?
b.buff.Grow(maxInMemorySize / 2)
return b
}
// NewBuffer creates a new Buffer with DefaultMaxMemorySize and calls Write(buf).
// If an error occurred, it panics
func NewBuffer(buf []byte) *Buffer {
b := NewBufferWithMaxMemorySize(DefaultMaxMemorySize)
if buf == nil || len(buf) == 0 {
// A special case
return b
}
_, err := b.Write(buf)
if err != nil {
panic(err)
}
return b
}
// NewBufferString calls NewBuffer([]byte(s))
func NewBufferString(s string) *Buffer {
return NewBuffer([]byte(s))
}
// ChangeTempDir changes directory for temp files
func (b *Buffer) ChangeTempDir(dir string) error {
f, err := os.Open(dir)
if err != nil {
return errors.Wrapf(err, "can't open directory '%s'", dir)
}
defer f.Close()
stats, err := f.Stat()
if err != nil {
return errors.Wrapf(err, "can't get stats of the directory '%s'", dir)
}
if !stats.IsDir() {
return errors.Errorf("'%s' is not a directory", dir)
}
path, err := filepath.Abs(dir)
if err != nil {
return errors.New("can't get an absolute path")
}
// Change
b.tempFileDir = path
return nil
}
// EnableEncryption enables encryption and generates an encryption key
func (b *Buffer) EnableEncryption() error {
b.encrypt = true
key := make([]byte, len(b.encryptionKey))
_, err := rand.Read(key)
if err != nil {
return errors.Wrap(err, "can't read random data")
}
for i := range key {
b.encryptionKey[i] = key[i]
}
return nil
}
// Write writes data into bytes.Buffer while size of the Buffer is less than maxInMemorySize, when size of Buffer is equal to maxInMemorySize, Write creates a temporary file and writes remaining data into this one.
// Write returns ErrBufferFinished after the call of Buffer.Read(), Buffer.ReadByte() or Buffer.Next()
//
func (b *Buffer) Write(data []byte) (n int, err error) {
if b.writingFinished {
return 0, ErrBufferFinished
}
defer func() {
b.size += n
}()
if !b.useFile {
if b.buff.Len()+len(data) <= b.maxInMemorySize {
// Just write data into the buffer
n, err = b.buff.Write(data)
return
}
// We have to use a file. But fill the buffer at first
bound := b.maxInMemorySize - b.buff.Len()
n, err = b.buff.Write(data[:bound])
if err != nil {
return
}
// Trim written bytes
data = data[bound:]
b.useFile = true
// Create a temporary file
file, err := ioutil.TempFile(b.tempFileDir, "go-disk-buffer-*.tmp")
if err != nil {
return n, errors.Wrap(err, "can't create a temp file")
}
var writeFile io.WriteCloser = file
if b.encrypt {
writeFile, err = sio.EncryptWriter(file, sio.Config{Key: b.encryptionKey[:]})
if err != nil {
return n, errors.Wrap(err, "can't create an encryption stream")
}
}
b.writeFile = writeFile
b.filename = file.Name()
// fallthrough
}
// Write data into the file
n1, err := b.writeFile.Write(data)
n += n1
return
}
// WriteByte writes a single byte.
//
// It uses Buffer.Write underhood
func (b *Buffer) WriteByte(c byte) error {
slice := []byte{c}
_, err := b.Write(slice)
return err
}
// WriteRune writes a rune.
//
// It uses bytes.Buffer and Buffer.Write underhood.
func (b *Buffer) WriteRune(r rune) (n int, err error) {
tmp := bytes.Buffer{}
n, err = tmp.WriteRune(r)
if err != nil {
return n, err
}
return b.Write(tmp.Bytes())
}
// WriteString writes a string
func (b *Buffer) WriteString(s string) (n int, err error) {
return b.Write([]byte(s))
}
// ReadFrom reads data from r until EOF and writes it into the Buffer.
func (b *Buffer) ReadFrom(r io.Reader) (int64, error) {
var n int64
var data = make([]byte, 512)
for {
rN, rErr := r.Read(data)
if rErr != nil && rErr != io.EOF {
return n, errors.Wrap(rErr, "can't read data from passed io.Reader")
}
data = data[:rN]
wN, wErr := b.Write(data)
if wErr != nil {
return n + int64(wN), errors.Wrap(wErr, "can't write data")
}
n += int64(rN)
if rErr == io.EOF {
return n, nil
}
data = data[:cap(data)]
}
}
// Read reads data from bytes.Buffer or from a file. A temp file is deleted when Read() encounter n == 0
func (b *Buffer) Read(data []byte) (n int, err error) {
if b.readingFinished {
return 0, io.EOF
}
if !b.writingFinished {
// Finish writing and close Write&Read file if needed
if b.writeFile != nil {
b.writeFile.Close()
b.writeFile = nil
}
b.writingFinished = true
}
// Check if reading is finished
defer func() {
b.offset += n
// If n is less than size of data slice, reading is finished
if n < len(data) {
b.readingFinished = true
}
if b.readingFinished && b.readFile != nil {
// Can close the file
b.readFile.Close()
os.Remove(b.filename)
b.readFile = nil
b.filename = ""
}
}()
if b.buff.Len() != 0 {
// Use the buffer
n, err = b.readFromBuffer(data)
if err != nil || n == len(data) || !b.useFile {
// Return if got an error, we filled the slice with data from buffer or we don't use a file
return
}
// Can use the file to fill the slice
var n1 int
temp := make([]byte, len(data)-n)
n1, err = b.readFromFile(temp)
temp = temp[:n1]
copy(data[n:], temp)
n += n1
return
}
if b.useFile {
// Use the file
n, err = b.readFromFile(data)
return
}
// Reaching this code means that we buffer is empty and we don't use a file. So, reading is finished
n = 0
err = io.EOF
return
}
func (b *Buffer) readFromBuffer(data []byte) (n int, err error) {
return b.buff.Read(data)
}
func (b *Buffer) readFromFile(data []byte) (n int, err error) {
if b.readFile == nil {
file, err := os.Open(b.filename)
if err != nil {
return 0, errors.Wrapf(err, "can't open a temp file '%s'", b.filename)
}
var readFile io.ReadCloser = file
if b.encrypt {
reader, err := sio.DecryptReader(file, sio.Config{Key: b.encryptionKey[:]})
if err != nil {
return 0, errors.Wrap(err, "can't create a decryption stream")
}
readFile = newSioDecryptReaderWrapper(reader, file)
}
b.readFile = readFile
}
return b.readFile.Read(data)
}
// ReadByte reads a single byte.
//
// It uses Buffer.Read underhood
func (b *Buffer) ReadByte() (byte, error) {
c := make([]byte, 1)
_, err := b.Read(c)
return c[0], err
}
// TODO: help wanted.
// What should we do with invalid runes (like 0xff)?
func (b *Buffer) readRune() (r rune, size int, err error) {
var p []byte
for {
c, err := b.ReadByte()
if err != nil {
return r, 0, err
}
p = append(p, c)
if utf8.FullRune(p) {
r, size = utf8.DecodeRune(p)
return r, size, nil
}
}
}
// Next returns a slice containing the next n bytes from the buffer.
// If an error occurred, it panics
func (b *Buffer) Next(n int) []byte {
slice := make([]byte, n)
n, err := b.buff.Read(slice)
if err != nil {
panic(err)
}
slice = slice[:n]
return slice
}
// WriteTo writes data to w until the buffer is drained or an error occurs.
func (b *Buffer) WriteTo(w io.Writer) (int64, error) {
var n int64
data := make([]byte, 512)
for {
rN, rErr := b.Read(data)
if rErr != nil && rErr != io.EOF {
return n, errors.Wrap(rErr, "can't read data from Buffer")
}
data = data[:rN]
wN, wErr := w.Write(data)
if wErr != nil {
return n + int64(wN), errors.Wrap(wErr, "can't write data into io.Writer")
}
n += int64(rN)
if rErr == io.EOF {
return n, nil
}
data = data[:cap(data)]
}
}
// Len returns the number of bytes of the unread portion of the buffer
func (b *Buffer) Len() int {
return b.size - b.offset
}
// Cap is equal to Buffer.Len()
func (b *Buffer) Cap() int {
return b.Len()
}
// Reset resets buffer and remove file if needed
func (b *Buffer) Reset() {
b.buff.Reset()
if b.writeFile != nil {
b.writeFile.Close()
}
if b.readFile != nil {
b.readFile.Close()
}
if b.filename != "" {
os.Remove(b.filename)
}
b.writingFinished = false
b.readingFinished = false
b.writeFile = nil
b.readFile = nil
b.useFile = false
b.filename = ""
}
// sioDecryptReaderWrapper is a wrapper for sio.DecryptReader() function
// that satisfy io.ReadCloser.
// It reads from passed io.Reader and closes the original file
type sioDecryptReaderWrapper struct {
r io.Reader
originalFile *os.File
}
func newSioDecryptReaderWrapper(r io.Reader, file *os.File) *sioDecryptReaderWrapper {
return &sioDecryptReaderWrapper{
r: r,
originalFile: file,
}
}
func (rw *sioDecryptReaderWrapper) Read(p []byte) (int, error) {
return rw.r.Read(p)
}
func (rw *sioDecryptReaderWrapper) Close() error {
return rw.originalFile.Close()
}