-
Notifications
You must be signed in to change notification settings - Fork 0
/
writer.go
68 lines (59 loc) · 1.21 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
package buf
import (
"io"
"sync"
)
// BufferToBytesWriter is a Writer that writes alloc.Buffer into underlying writer.
type BufferToBytesWriter struct {
writer io.Writer
}
// Write implements Writer.Write(). Write() takes ownership of the given buffer.
func (v *BufferToBytesWriter) Write(buffer *Buffer) error {
defer buffer.Release()
for {
nBytes, err := v.writer.Write(buffer.Bytes())
if err != nil {
return err
}
if nBytes == buffer.Len() {
break
}
buffer.SliceFrom(nBytes)
}
return nil
}
// Release implements Releasable.Release().
func (v *BufferToBytesWriter) Release() {
v.writer = nil
}
type BytesToBufferWriter struct {
sync.Mutex
writer Writer
}
func (v *BytesToBufferWriter) Write(payload []byte) (int, error) {
v.Lock()
defer v.Unlock()
if v.writer == nil {
return 0, io.ErrClosedPipe
}
bytesWritten := 0
size := len(payload)
for size > 0 {
buffer := New()
nBytes, _ := buffer.Write(payload)
size -= nBytes
payload = payload[nBytes:]
bytesWritten += nBytes
err := v.writer.Write(buffer)
if err != nil {
return bytesWritten, err
}
}
return bytesWritten, nil
}
func (v *BytesToBufferWriter) Release() {
v.Lock()
v.writer.Release()
v.writer = nil
v.Unlock()
}