Skip to content

Commit 32e39e4

Browse files
committed
Defer allocation of write buffer in sync writer until needed.
1 parent a94fe8a commit 32e39e4

File tree

1 file changed

+19
-7
lines changed

1 file changed

+19
-7
lines changed

internal/pkg/sync/writer.go

Lines changed: 19 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -25,24 +25,20 @@ type syncWriterT struct {
2525
state error
2626
opts *OptsT
2727
srcHash *xxh32.XXHZero
28+
closed bool
2829
}
2930

3031
func NewSyncWriter(wr io.Writer, opts *OptsT) *syncWriterT {
3132

3233
var (
3334
bsz = opts.BlockSizeIdx.Size()
34-
srcBlk = blk.BorrowBlk(bsz)
3535
factory = opts.NewCompressorFactory()
3636
)
3737

38-
// Scope it down to our block size
39-
srcBlk.Trim(bsz)
40-
4138
w := &syncWriterT{
4239
wr: wr,
4340
cmp: factory.NewCompressor(),
4441
bsz: bsz,
45-
srcBlk: srcBlk,
4642
srcOff: -1,
4743
opts: opts,
4844
}
@@ -88,6 +84,8 @@ func (w *syncWriterT) _write(src []byte) (nConsumed int, err error) {
8884
return
8985
}
9086

87+
blk.ReturnBlk(w.srcBlk)
88+
w.srcBlk = nil
9189
w.srcOff = 0
9290
}
9391

@@ -108,6 +106,10 @@ func (w *syncWriterT) _write(src []byte) (nConsumed int, err error) {
108106

109107
src = src[w.bsz:]
110108
} else {
109+
110+
w.srcBlk = blk.BorrowBlk(w.bsz)
111+
w.srcBlk.Trim(w.bsz)
112+
111113
// Cache the data in w.srcBlk for the next spin
112114
n := copy(w.srcBlk.Data(), src)
113115
nConsumed += n
@@ -122,8 +124,7 @@ func (w *syncWriterT) _write(src []byte) (nConsumed int, err error) {
122124
// Close finishes
123125
func (w *syncWriterT) Close() error {
124126

125-
// If s.srcBlk is nil, close has already been called
126-
if w.srcBlk == nil {
127+
if w.closed {
127128
return w.state
128129
}
129130

@@ -143,6 +144,9 @@ func (w *syncWriterT) Close() error {
143144
w.srcBlk = nil
144145
w.srcOff = 0
145146

147+
// Flag that we are closed
148+
w.closed = true
149+
146150
switch {
147151
case w.state != nil:
148152
// Close should succeed even if we are in an error state,
@@ -190,6 +194,8 @@ func (w *syncWriterT) _flush() error {
190194
return err
191195
}
192196

197+
blk.ReturnBlk(w.srcBlk)
198+
w.srcBlk = nil
193199
w.srcOff = 0
194200
return nil
195201
}
@@ -213,6 +219,12 @@ func (w *syncWriterT) _readFrom(r io.Reader) (nConsumed int64, err error) {
213219
}
214220
}
215221

222+
if w.srcBlk == nil {
223+
w.srcBlk = blk.BorrowBlk(w.bsz)
224+
w.srcBlk.Trim(w.bsz)
225+
w.srcOff = 0 // Should be NOOP
226+
}
227+
216228
LOOP:
217229
for {
218230
n, rerr := io.ReadFull(r, w.srcBlk.Suffix(w.srcOff))

0 commit comments

Comments
 (0)