Skip to content

Commit 2f7a0d0

Browse files
authored
[bug] - Ensure BufferedFileWriter Flushes Buffer Contents to File Correctly (#2943)
* flush butter before writing to file * revert * remove redundant Reset * add test case
1 parent 3a029ea commit 2f7a0d0

File tree

2 files changed

+21
-4
lines changed

2 files changed

+21
-4
lines changed

pkg/writers/buffered_file_writer/bufferedfilewriter.go

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -205,7 +205,13 @@ func (w *BufferedFileWriter) Write(data []byte) (int, error) {
205205
}
206206
return 0, err
207207
}
208-
w.buf.Reset()
208+
}
209+
}
210+
211+
// Write any remaining data in the buffer to the file before writing new data.
212+
if w.buf.Len() > 0 {
213+
if _, err := w.buf.WriteTo(w.file); err != nil {
214+
return 0, fmt.Errorf("error flushing buffer to file: %w", err)
209215
}
210216
}
211217

@@ -273,8 +279,7 @@ func (w *BufferedFileWriter) CloseForWriting() error {
273279
defer w.bufPool.Put(w.buf)
274280

275281
if w.buf.Len() > 0 {
276-
_, err := w.buf.WriteTo(w.file)
277-
if err != nil {
282+
if _, err := w.buf.WriteTo(w.file); err != nil {
278283
return err
279284
}
280285
}

pkg/writers/buffered_file_writer/bufferedfilewriter_test.go

Lines changed: 13 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -650,11 +650,19 @@ func TestBufferedFileWriter_ReadFrom(t *testing.T) {
650650
expectedSize: 1 << 20,
651651
},
652652
{
653-
name: "Input greater than threshold",
653+
name: "Input slightly greater than threshold",
654654
input: string(make([]byte, defaultThreshold+1)),
655655
expectedOutput: string(make([]byte, defaultThreshold+1)),
656656
expectedSize: defaultThreshold + 1,
657657
},
658+
// Test to ensure that anytime the buffer exceeds the threshold, the data is written to a file
659+
// and the buffer is cleared.
660+
{
661+
name: "Input much greater than threshold",
662+
input: string(make([]byte, (2*defaultThreshold)+largeBufferSize+1)),
663+
expectedOutput: string(make([]byte, (2*defaultThreshold)+largeBufferSize+1)),
664+
expectedSize: (2 * defaultThreshold) + largeBufferSize + 1,
665+
},
658666
}
659667

660668
for _, tc := range tests {
@@ -668,6 +676,10 @@ func TestBufferedFileWriter_ReadFrom(t *testing.T) {
668676
size, err := writer.ReadFrom(reader)
669677
assert.NoError(t, err)
670678

679+
if writer.buf != nil && writer.file != nil {
680+
assert.Len(t, writer.buf.Bytes(), 0)
681+
}
682+
671683
err = writer.CloseForWriting()
672684
assert.NoError(t, err)
673685

0 commit comments

Comments
 (0)