package okhttp3.internal.cache2;

import h.c;
import java.io.EOFException;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/* JADX INFO: loaded from: classes.dex */
final class FileOperator {
    private static final int BUFFER_SIZE = 8192;
    private final byte[] byteArray;
    private final ByteBuffer byteBuffer;
    private final FileChannel fileChannel;

    FileOperator(FileChannel fileChannel) {
        byte[] bArr = new byte[8192];
        this.byteArray = bArr;
        this.byteBuffer = ByteBuffer.wrap(bArr);
        this.fileChannel = fileChannel;
    }

    public void read(long j2, c cVar, long j3) throws IOException {
        if (j3 < 0) {
            throw new IndexOutOfBoundsException();
        }
        while (j3 > 0) {
            try {
                this.byteBuffer.limit((int) Math.min(8192L, j3));
                if (this.fileChannel.read(this.byteBuffer, j2) == -1) {
                    throw new EOFException();
                }
                int iPosition = this.byteBuffer.position();
                cVar.M(this.byteArray, 0, iPosition);
                long j4 = iPosition;
                j2 += j4;
                j3 -= j4;
            } finally {
                this.byteBuffer.clear();
            }
        }
    }

    public void write(long j2, c cVar, long j3) throws IOException {
        if (j3 < 0 || j3 > cVar.B()) {
            throw new IndexOutOfBoundsException();
        }
        while (j3 > 0) {
            try {
                int iMin = (int) Math.min(8192L, j3);
                cVar.read(this.byteArray, 0, iMin);
                this.byteBuffer.limit(iMin);
                do {
                    j2 += (long) this.fileChannel.write(this.byteBuffer, j2);
                } while (this.byteBuffer.hasRemaining());
                j3 -= (long) iMin;
            } finally {
                this.byteBuffer.clear();
            }
        }
    }
}
