package io.netty.handler.codec.compression;

import g.a.a.a.a;
import io.netty.buffer.ByteBuf;

/* JADX INFO: loaded from: classes.dex */
public final class Bzip2BitWriter {
    private long bitBuffer;
    private int bitCount;

    public void flush(ByteBuf byteBuf) {
        int i2 = this.bitCount;
        if (i2 > 0) {
            long j2 = this.bitBuffer;
            int i3 = 64 - i2;
            if (i2 <= 8) {
                byteBuf.writeByte((int) ((j2 >>> i3) << (8 - i2)));
                return;
            }
            if (i2 <= 16) {
                byteBuf.writeShort((int) ((j2 >>> i3) << (16 - i2)));
                return;
            }
            long j3 = j2 >>> i3;
            if (i2 <= 24) {
                byteBuf.writeMedium((int) (j3 << (24 - i2)));
            } else {
                byteBuf.writeInt((int) (j3 << (32 - i2)));
            }
        }
    }

    public void writeBits(ByteBuf byteBuf, int i2, long j2) {
        if (i2 < 0 || i2 > 32) {
            throw new IllegalArgumentException(a.n("count: ", i2, " (expected: 0-32)"));
        }
        int i3 = this.bitCount;
        long j3 = ((j2 << (64 - i2)) >>> i3) | this.bitBuffer;
        int i4 = i3 + i2;
        if (i4 >= 32) {
            byteBuf.writeInt((int) (j3 >>> 32));
            j3 <<= 32;
            i4 -= 32;
        }
        this.bitBuffer = j3;
        this.bitCount = i4;
    }

    public void writeBoolean(ByteBuf byteBuf, boolean z2) {
        int i2 = this.bitCount + 1;
        long j2 = 0;
        long j3 = this.bitBuffer | (z2 ? 1 << (64 - i2) : 0L);
        if (i2 == 32) {
            byteBuf.writeInt((int) (j3 >>> 32));
            i2 = 0;
        } else {
            j2 = j3;
        }
        this.bitBuffer = j2;
        this.bitCount = i2;
    }

    public void writeInt(ByteBuf byteBuf, int i2) {
        writeBits(byteBuf, 32, i2);
    }

    public void writeUnary(ByteBuf byteBuf, int i2) {
        if (i2 < 0) {
            throw new IllegalArgumentException(a.n("value: ", i2, " (expected 0 or more)"));
        }
        while (true) {
            int i3 = i2 - 1;
            if (i2 <= 0) {
                writeBoolean(byteBuf, false);
                return;
            } else {
                writeBoolean(byteBuf, true);
                i2 = i3;
            }
        }
    }
}
