Don't drop bytes from the buffered reader when reading short (#2646)

Motivation:

When the `BufferedReader` reads short when filling its buffer during a
request for some bytes, it may avoid giving the caller all bytes
available. The bytes remain in the buffer and are available on the next
call but this appears to the caller as if the file has been read
completely as the returned bytes are less than those requested.

Modifications:

- Read the expected bytes or whatever is left in the buffer
- Add a test

Result:

Less unexpected behaviour
This commit is contained in:
George Barnett authored and GitHub committed 2024-02-13 09:51:57 +00:00
1 parent e4102aecb5
commit 82fd942745
2 files changed
+25 -3

No files matched your search

+9 -3
View File
@@ -86,15 +86,21 @@ public struct BufferedReader<Handle: ReadableFileHandleProtocol> {
var buffer = self.buffer
self.buffer = ByteBuffer()
// The bytes to read from the chunk is the difference in what the caller requested
// and is already stored in buffer. Note that if we get to the end of the file this
// number could be larger than the available number of bytes.
let bytesFromChunk = byteCount &- buffer.readableBytes
let bytesToRead = bytesFromChunk + self.capacity
// Read a chunk from the file and store it.
let chunk = try await self.readFromFile(bytesToRead)
self.buffer.writeImmutableBuffer(chunk)
if let readBytes = self.buffer.readSlice(length: bytesFromChunk) {
buffer.writeImmutableBuffer(readBytes)
}
// Finally read off the required bytes from the chunk we just read. If we read short
// then the chunk we just appended might not less than 'bytesFromChunk', that's fine,
// just take what's available.
var slice = self.buffer.readSlice(length: min(bytesFromChunk, chunk.readableBytes))!
buffer.writeBuffer(&slice)
return buffer
}
@@ -86,6 +86,22 @@ final class BufferedReaderTests: XCTestCase {
}
}
func testBufferedReaderReadingShort() async throws {
let fs = FileSystem.shared
try await fs.withFileHandle(forReadingAt: #filePath) { handle in
var reader = handle.bufferedReader(capacity: .bytes(128))
var buffer = ByteBuffer()
while true {
let chunk = try await reader.read(.bytes(128))
buffer.writeImmutableBuffer(chunk)
if chunk.readableBytes < 128 { break }
}
let info = try await handle.info()
XCTAssertEqual(Int64(buffer.readableBytes), info.size)
}
}
func testBufferedReaderReadWhile() async throws {
let fs = FileSystem.shared
let path = try await fs.temporaryFilePath()