diff --git a/Sources/NIOFileSystem/BufferedReader.swift b/Sources/NIOFileSystem/BufferedReader.swift index 3b29253b1..7b567c56a 100644 --- a/Sources/NIOFileSystem/BufferedReader.swift +++ b/Sources/NIOFileSystem/BufferedReader.swift @@ -86,15 +86,21 @@ public struct BufferedReader { 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 } diff --git a/Tests/NIOFileSystemIntegrationTests/BufferedReaderTests.swift b/Tests/NIOFileSystemIntegrationTests/BufferedReaderTests.swift index 362aed212..8404e1596 100644 --- a/Tests/NIOFileSystemIntegrationTests/BufferedReaderTests.swift +++ b/Tests/NIOFileSystemIntegrationTests/BufferedReaderTests.swift @@ -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()