-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbytes.go
49 lines (41 loc) · 983 Bytes
/
bytes.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
package tapedeck
import (
"bufio"
"bytes"
"fmt"
)
// A [Writer] that will lazy initialize itself upon first Write
// and is backed by a [bytes.Buffer].
type LazyBytesWriter struct {
initialized bool
buffer *bytes.Buffer
writer *bufio.Writer
// total bytes written
totalBytes int
// the last error
lastError error
}
func (sw *LazyBytesWriter) Bytes() (b []byte, e error) {
if !sw.initialized {
return b, fmt.Errorf("not initialized")
}
if sw.lastError != nil {
return b, fmt.Errorf("last write erorr: %w", sw.lastError)
}
flushErr := sw.writer.Flush()
if flushErr != nil {
return b, fmt.Errorf("failed to flush internal writer: %w", flushErr)
}
return sw.buffer.Bytes(), nil
}
func (sw *LazyBytesWriter) Write(p []byte) (n int, err error) {
if !sw.initialized {
sw.buffer = new(bytes.Buffer)
sw.writer = bufio.NewWriter(sw.buffer)
sw.initialized = true
}
n, err = sw.writer.Write(p)
sw.totalBytes += n
sw.lastError = err
return
}