mirror of
https://github.com/apple/swift-nio
synced 2026-11-26 04:57:49 +00:00
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:
1 parent
e4102aecb5
commit
82fd942745
2 files changed
+25
-3
No files matched your search
@@ -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
|
||||
}
|
||||
|
||||
Reference in new issue
Block a user