// 
// Decompiled by Procyon v0.6.0
// 

package org.bouncycastle.asn1;

import java.io.IOException;
import java.io.InputStream;

@Deprecated
public class DLBitStringParser implements ASN1BitStringParser
{
    private final DefiniteLengthInputStream stream;
    private int padBits;
    
    DLBitStringParser(final DefiniteLengthInputStream stream) {
        this.padBits = 0;
        this.stream = stream;
    }
    
    @Override
    public InputStream getBitStream() throws IOException {
        return this.getBitStream(false);
    }
    
    @Override
    public InputStream getOctetStream() throws IOException {
        return this.getBitStream(true);
    }
    
    @Override
    public int getPadBits() {
        return this.padBits;
    }
    
    @Override
    public ASN1Primitive getLoadedObject() throws IOException {
        return ASN1BitString.createPrimitive(this.stream.toByteArray());
    }
    
    @Override
    public ASN1Primitive toASN1Primitive() {
        try {
            return this.getLoadedObject();
        }
        catch (final IOException ex) {
            throw new ASN1ParsingException("IOException converting stream to byte array: " + ex.getMessage(), ex);
        }
    }
    
    private InputStream getBitStream(final boolean b) throws IOException {
        final int remaining = this.stream.getRemaining();
        if (remaining < 1) {
            throw new IllegalStateException("content octets cannot be empty");
        }
        this.padBits = this.stream.read();
        if (this.padBits > 0) {
            if (remaining < 2) {
                throw new IllegalStateException("zero length data with non-zero pad bits");
            }
            if (this.padBits > 7) {
                throw new IllegalStateException("pad bits cannot be greater than 7 or less than 0");
            }
            if (b) {
                throw new IOException("expected octet-aligned bitstring, but found padBits: " + this.padBits);
            }
        }
        return this.stream;
    }
}
