...
1 package jwriter
2
3 import (
4 "bytes"
5 "io"
6 )
7
8 type streamableBuffer struct {
9 buf bytes.Buffer
10 dest io.Writer
11 destErr error
12 chunkSize int
13 }
14
15 func (b *streamableBuffer) Bytes() []byte {
16 return b.buf.Bytes()
17 }
18
19 func (b *streamableBuffer) Grow(n int) {
20 b.buf.Grow(n)
21 }
22
23 func (b *streamableBuffer) SetStreamingWriter(w io.Writer, chunkSize int) {
24 b.dest = w
25 b.chunkSize = chunkSize
26 }
27
28 func (b *streamableBuffer) Flush() error {
29 if b.dest != nil {
30 if b.buf.Len() > 0 {
31 if b.destErr == nil {
32 data := b.buf.Bytes()
33 _, b.destErr = b.dest.Write(data)
34 }
35 b.buf.Reset()
36 return b.destErr
37 }
38 }
39 return nil
40 }
41
42 func (b *streamableBuffer) maybeFlush() {
43 if b.dest != nil && b.buf.Len() >= b.chunkSize {
44 _ = b.Flush()
45 }
46 }
47
48 func (b *streamableBuffer) GetWriterError() error {
49 return b.destErr
50 }
51
52 func (b *streamableBuffer) Write(data []byte) {
53 _, _ = b.buf.Write(data)
54 b.maybeFlush()
55 }
56
57 func (b *streamableBuffer) WriteByte(data byte) {
58 _ = b.buf.WriteByte(data)
59 b.maybeFlush()
60 }
61
62 func (b *streamableBuffer) WriteRune(ch rune) {
63 _, _ = b.buf.WriteRune(ch)
64 b.maybeFlush()
65 }
66
67 func (b *streamableBuffer) WriteString(s string) {
68 _, _ = b.buf.WriteString(s)
69 b.maybeFlush()
70 }
71
View as plain text