package okhttp3.internal.ws;

import java.io.Closeable;
import java.io.IOException;
import java.util.zip.Deflater;
import kotlin.jvm.internal.l;
import okio.C;
import okio.C0688f;
import okio.i;
import okio.j;
import w1.b;

/* JADX INFO: loaded from: classes2.dex */
public final class MessageDeflater implements Closeable {
    private final C0688f deflatedBytes;
    private final Deflater deflater;
    private final j deflaterSink;
    private final boolean noContextTakeover;

    public MessageDeflater(boolean z2) {
        this.noContextTakeover = z2;
        C0688f c0688f = new C0688f();
        this.deflatedBytes = c0688f;
        Deflater deflater = new Deflater(-1, true);
        this.deflater = deflater;
        this.deflaterSink = new j((C) c0688f, deflater);
    }

    private final boolean endsWith(C0688f c0688f, i iVar) {
        return c0688f.x(c0688f.G() - ((long) iVar.s()), iVar);
    }

    @Override // java.io.Closeable, java.lang.AutoCloseable
    public void close() throws Throwable {
        this.deflaterSink.close();
    }

    public final void deflate(C0688f buffer) throws IOException {
        l.e(buffer, "buffer");
        if (!(this.deflatedBytes.G() == 0)) {
            throw new IllegalArgumentException("Failed requirement.");
        }
        if (this.noContextTakeover) {
            this.deflater.reset();
        }
        this.deflaterSink.write(buffer, buffer.G());
        this.deflaterSink.flush();
        if (endsWith(this.deflatedBytes, MessageDeflaterKt.EMPTY_DEFLATE_BLOCK)) {
            long jG = this.deflatedBytes.G() - ((long) 4);
            C0688f.a aVarV = C0688f.v(this.deflatedBytes, null, 1, null);
            try {
                aVarV.b(jG);
                b.a(aVarV, null);
            } finally {
            }
        } else {
            this.deflatedBytes.writeByte(0);
        }
        C0688f c0688f = this.deflatedBytes;
        buffer.write(c0688f, c0688f.G());
    }
}
