Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Transfer to/from FileChannel directly from Buffer. #3846

Merged
merged 1 commit into from
Feb 14, 2018
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
40 changes: 6 additions & 34 deletions okhttp/src/main/java/okhttp3/internal/cache2/FileOperator.java
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,6 @@

import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import okio.Buffer;
import okio.Okio;
Expand All @@ -35,10 +34,6 @@
* </ul>
*/
final class FileOperator {
private static final int BUFFER_SIZE = 8192;

private final byte[] byteArray = new byte[BUFFER_SIZE];
private final ByteBuffer byteBuffer = ByteBuffer.wrap(byteArray);
private final FileChannel fileChannel;

FileOperator(FileChannel fileChannel) {
Expand All @@ -50,22 +45,9 @@ public void write(long pos, Buffer source, long byteCount) throws IOException {
if (byteCount < 0 || byteCount > source.size()) throw new IndexOutOfBoundsException();

while (byteCount > 0L) {
try {
// Write bytes to the byte[], and tell the ByteBuffer wrapper about 'em.
int toWrite = (int) Math.min(BUFFER_SIZE, byteCount);
source.read(byteArray, 0, toWrite);
byteBuffer.limit(toWrite);

// Copy bytes from the ByteBuffer to the file.
do {
int bytesWritten = fileChannel.write(byteBuffer, pos);
pos += bytesWritten;
} while (byteBuffer.hasRemaining());

byteCount -= toWrite;
} finally {
byteBuffer.clear();
}
long bytesWritten = fileChannel.transferFrom(source, pos, byteCount);
pos += bytesWritten;
byteCount -= bytesWritten;
}
}

Expand All @@ -78,19 +60,9 @@ public void read(long pos, Buffer sink, long byteCount) throws IOException {
if (byteCount < 0) throw new IndexOutOfBoundsException();

while (byteCount > 0L) {
try {
// Read up to byteCount bytes.
byteBuffer.limit((int) Math.min(BUFFER_SIZE, byteCount));
if (fileChannel.read(byteBuffer, pos) == -1) throw new EOFException();
int bytesRead = byteBuffer.position();

// Write those bytes to sink.
sink.write(byteArray, 0, bytesRead);
pos += bytesRead;
byteCount -= bytesRead;
} finally {
byteBuffer.clear();
}
long bytesRead = fileChannel.transferTo(pos, byteCount, sink);
pos += bytesRead;
byteCount -= bytesRead;
}
}
}