Skip to content

Commit 0384162

Browse files
committed
Only increase read sizes when beneficial
Read.read_all increases the given read size to reduce the number of calls to Read.read. This used to be done regardless of the number of bytes read, which could result in unnecessarily large reads. To prevent this from happening, we only increase the read size if the actual number of bytes read equals the desired number of bytes. Changelog: performance
1 parent 2c3cc1f commit 0384162

File tree

1 file changed

+14
-9
lines changed

1 file changed

+14
-9
lines changed

std/src/std/io.inko

+14-9
Original file line numberDiff line numberDiff line change
@@ -324,26 +324,31 @@ trait pub Read {
324324
# available (yet).
325325
fn pub mut read(into: mut ByteArray, size: Int) -> Result[Int, Error]
326326

327-
# Reads all bytes from the stream into the `ByteArray`.
328-
#
329-
# If an error is encountered while reading, this method stops reading any more
330-
# bytes and re-throws the error.
327+
# Reads from `self` into the given `ByteArray`, returning when all input is
328+
# consumed.
331329
#
332330
# The return value is the number of bytes read.
331+
#
332+
# # Errors
333+
#
334+
# This method returns an `Error` if the underlying call to `Read.read` returns
335+
# an `Error`.
333336
fn pub mut read_all(bytes: mut ByteArray) -> Result[Int, Error] {
334337
let mut total = 0
335338
let mut read_size = INITIAL_READ_ALL_SIZE
336339

337340
loop {
338341
match read(into: bytes, size: read_size) {
339342
case Ok(0) -> return Result.Ok(total)
340-
case Ok(n) -> total += n
343+
case Ok(n) -> {
344+
total += n
345+
346+
# To reduce the number of calls to `Reader.read` when there's lots of
347+
# input to consume, we increase the read size if deemed beneficial.
348+
if read_size < MAX_READ_ALL_SIZE and n == read_size { read_size *= 2 }
349+
}
341350
case Error(e) -> throw e
342351
}
343-
344-
# To reduce the overhead of large buffer reads, we increase the buffer
345-
# size as more data is read.
346-
if read_size < MAX_READ_ALL_SIZE { read_size *= 2 }
347352
}
348353
}
349354
}

0 commit comments

Comments
 (0)