package org.bouncycastle.util.io;

import java.io.IOException;
import java.io.OutputStream;
import org.bouncycastle.asn1.cmp.PKIFailureInfo;
import org.bouncycastle.util.Arrays;

/* JADX INFO: loaded from: classes.dex */
public class BufferingOutputStream extends OutputStream {
    private final byte[] buf;
    private int bufOff;
    private final OutputStream other;

    public BufferingOutputStream(OutputStream outputStream) {
        this.other = outputStream;
        this.buf = new byte[PKIFailureInfo.certConfirmed];
    }

    public BufferingOutputStream(OutputStream outputStream, int i) {
        this.other = outputStream;
        this.buf = new byte[i];
    }

    @Override // java.io.OutputStream, java.io.Closeable, java.lang.AutoCloseable
    public void close() throws IOException {
        flush();
        this.other.close();
    }

    @Override // java.io.OutputStream, java.io.Flushable
    public void flush() throws IOException {
        this.other.write(this.buf, 0, this.bufOff);
        this.bufOff = 0;
        Arrays.fill(this.buf, (byte) 0);
    }

    @Override // java.io.OutputStream
    public void write(int i) throws IOException {
        byte[] bArr = this.buf;
        int i2 = this.bufOff;
        this.bufOff = i2 + 1;
        bArr[i2] = (byte) i;
        if (this.bufOff == this.buf.length) {
            flush();
        }
    }

    @Override // java.io.OutputStream
    public void write(byte[] bArr, int i, int i2) throws IOException {
        int length = this.buf.length - this.bufOff;
        byte[] bArr2 = this.buf;
        if (i2 < length) {
            System.arraycopy(bArr, i, bArr2, this.bufOff, i2);
        } else {
            int length2 = bArr2.length - this.bufOff;
            System.arraycopy(bArr, i, this.buf, this.bufOff, length2);
            this.bufOff += length2;
            flush();
            int length3 = i + length2;
            while (true) {
                i2 -= length2;
                if (i2 < this.buf.length) {
                    break;
                }
                this.other.write(bArr, length3, this.buf.length);
                length3 += this.buf.length;
                length2 = this.buf.length;
            }
            if (i2 <= 0) {
                return;
            } else {
                System.arraycopy(bArr, length3, this.buf, this.bufOff, i2);
            }
        }
        this.bufOff += i2;
    }
}
