package org.bouncycastle.bcpg;

import java.io.EOFException;
import java.io.IOException;
import java.io.InputStream;
import org.bouncycastle.bcpg.attr.ImageAttribute;

/* JADX INFO: loaded from: classes2.dex */
public class UserAttributeSubpacketInputStream extends InputStream implements UserAttributeSubpacketTags {
    InputStream in;
    private final int limit;

    public UserAttributeSubpacketInputStream(InputStream inputStream) {
        this(inputStream, StreamUtil.findLimit(inputStream));
    }

    public UserAttributeSubpacketInputStream(InputStream inputStream, int i) {
        this.in = inputStream;
        this.limit = i;
    }

    private void readFully(byte[] bArr, int i, int i2) throws IOException {
        if (i2 > 0) {
            int i3 = read();
            if (i3 < 0) {
                throw new EOFException();
            }
            bArr[i] = (byte) i3;
            i++;
            i2--;
        }
        while (i2 > 0) {
            int i4 = this.in.read(bArr, i, i2);
            if (i4 < 0) {
                throw new EOFException();
            }
            i += i4;
            i2 -= i4;
        }
    }

    @Override // java.io.InputStream
    public int available() throws IOException {
        return this.in.available();
    }

    @Override // java.io.InputStream
    public int read() throws IOException {
        return this.in.read();
    }

    public UserAttributeSubpacket readPacket() throws IOException {
        boolean[] zArr = new boolean[3];
        int bodyLen = StreamUtil.readBodyLen(this, zArr);
        if (zArr[StreamUtil.flag_eof]) {
            return null;
        }
        if (zArr[StreamUtil.flag_partial]) {
            throw new MalformedPacketException("unrecognised length reading user attribute sub packet");
        }
        if (bodyLen < 1) {
            throw new MalformedPacketException("Body length octet too small.");
        }
        if (bodyLen > this.limit) {
            throw new MalformedPacketException("Body length octet (" + bodyLen + ") exceeds limitations (" + this.limit + ").");
        }
        boolean z = zArr[StreamUtil.flag_isLongLength];
        int i = this.in.read();
        if (i < 0) {
            throw new EOFException("unexpected EOF reading user attribute sub packet");
        }
        int i2 = bodyLen - 1;
        byte[] bArr = new byte[i2];
        readFully(bArr, 0, i2);
        switch (i) {
            case 1:
                try {
                    return new ImageAttribute(z, bArr);
                } catch (IllegalArgumentException e) {
                    throw new MalformedPacketException("Malformed UserAttribute subpacket.", e);
                }
            default:
                return new UserAttributeSubpacket(i, z, bArr);
        }
    }
}
