Skip to content

Commit

Permalink
Take no action if transferring zero bytes.
Browse files Browse the repository at this point in the history
This removes the logic from inside the loop for much better readability.
  • Loading branch information
JakeWharton committed Jan 5, 2015
1 parent ddbf236 commit 9d4b4d9
Showing 1 changed file with 14 additions and 14 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -684,30 +684,30 @@ private void sleepIfDelayed(MockResponse response) {
}

/**
* Transfer bytes from {@code in} to {@code out} until either {@code length}
* bytes have been transferred or {@code in} is exhausted. The transfer is
* Transfer bytes from {@code source} to {@code sink} until either {@code byteCount}
* bytes have been transferred or {@code source} is exhausted. The transfer is
* throttled according to {@code throttlePolicy}.
*/
private void throttledTransfer(MockResponse throttlePolicy, Socket socket, BufferedSource source,
BufferedSink sink, long limit) throws IOException {
BufferedSink sink, long byteCount) throws IOException {
if (byteCount == 0) return;

Buffer buffer = new Buffer();
int bytesPerPeriod = throttlePolicy.getThrottleBytesPerPeriod();
long delayMs = throttlePolicy.getThrottleUnit().toMillis(throttlePolicy.getThrottlePeriod());

while (!socket.isClosed()) {
for (int b = 0; b < bytesPerPeriod; ) {
long toRead = Math.min(Math.min(2048, limit), bytesPerPeriod - b);
if (toRead > 0) {
long read = source.read(buffer, toRead);
if (read == -1) return;

sink.write(buffer, read);
sink.flush();
b += read;
limit -= read;
}
long toRead = Math.min(Math.min(2048, byteCount), bytesPerPeriod - b);
long read = source.read(buffer, toRead);
if (read == -1) return;

sink.write(buffer, read);
sink.flush();
b += read;
byteCount -= read;

if (limit == 0) return;
if (byteCount == 0) return;
}

if (delayMs != 0) {
Expand Down

0 comments on commit 9d4b4d9

Please sign in to comment.