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

package org.bouncycastle.asn1;

import java.io.IOException;
import java.io.OutputStream;

public class BEROctetStringGenerator extends BERGenerator
{
    public BEROctetStringGenerator(final OutputStream outputStream) throws IOException {
        super(outputStream);
        this.writeBERHeader(36);
    }
    
    public BEROctetStringGenerator(final OutputStream outputStream, final int n, final boolean b) throws IOException {
        super(outputStream, n, b);
        this.writeBERHeader(36);
    }
    
    public OutputStream getOctetOutputStream() {
        return this.getOctetOutputStream(new byte[1000]);
    }
    
    public OutputStream getOctetOutputStream(final byte[] array) {
        return new BufferedBEROctetStream(array);
    }
    
    private class BufferedBEROctetStream extends OutputStream
    {
        private byte[] _buf;
        private int _off;
        private DEROutputStream _derOut;
        
        BufferedBEROctetStream(final byte[] buf) {
            this._buf = buf;
            this._off = 0;
            this._derOut = new DEROutputStream(BEROctetStringGenerator.this._out);
        }
        
        @Override
        public void write(final int n) throws IOException {
            this._buf[this._off++] = (byte)n;
            if (this._off == this._buf.length) {
                DEROctetString.encode(this._derOut, true, this._buf, 0, this._buf.length);
                this._off = 0;
            }
        }
        
        @Override
        public void write(final byte[] array, final int n, final int n2) throws IOException {
            final int length = this._buf.length;
            final int n3 = length - this._off;
            if (n2 < n3) {
                System.arraycopy(array, n, this._buf, this._off, n2);
                this._off += n2;
                return;
            }
            int n4 = 0;
            if (this._off > 0) {
                System.arraycopy(array, n, this._buf, this._off, n3);
                n4 += n3;
                DEROctetString.encode(this._derOut, true, this._buf, 0, length);
            }
            int off;
            while ((off = n2 - n4) >= length) {
                DEROctetString.encode(this._derOut, true, array, n + n4, length);
                n4 += length;
            }
            System.arraycopy(array, n + n4, this._buf, 0, off);
            this._off = off;
        }
        
        @Override
        public void close() throws IOException {
            if (this._off != 0) {
                DEROctetString.encode(this._derOut, true, this._buf, 0, this._off);
            }
            this._derOut.flushInternal();
            BEROctetStringGenerator.this.writeBEREnd();
        }
    }
}
