package io.netty.handler.codec.compression;

import io.netty.buffer.ByteBuf;

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

    Bzip2BitWriter() {
    }

    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)));
            } else if (i2 <= 24) {
                byteBuf.writeMedium((int) ((j2 >>> i3) << (24 - i2)));
            } else {
                byteBuf.writeInt((int) ((j2 >>> i3) << (32 - i2)));
            }
        }
    }

    void writeBits(ByteBuf byteBuf, int i2, long j2) {
        if (i2 < 0 || i2 > 32) {
            throw new IllegalArgumentException("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;
    }

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

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

    void writeUnary(ByteBuf byteBuf, int i2) {
        if (i2 < 0) {
            throw new IllegalArgumentException("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;
            }
        }
    }
}
