package org.maachang.util;

/**
 * バイナリ配列.
 * 
 * @version 2008/03/25
 * @author masahito suzuki
 * @since MaachangProxy 1.00
 */
public class ArrayBinary {
    private static final int BUFFER = 4096 ;
    private byte[] binary = null ;
    private int length = 0 ;
    
    public ArrayBinary() {
        this.binary = new byte[ BUFFER ] ;
        this.length = 0 ;
    }
    
    protected void finalize() throws Exception {
        this.destroy() ;
    }
    
    public void destroy() {
        this.binary = null ;
        this.length = 0 ;
    }
    
    public void reset() {
        if( this.binary.length == BUFFER ) {
            this.length = 0 ;
        }
        else {
            this.binary = new byte[ BUFFER ] ;
            this.length = 0 ;
        }
    }
    
    public void write( int b ) throws Exception {
        if( binary.length <= length ) {
            byte[] t = binary ;
            int iLen = t.length * 2 ;
            binary = new byte[ iLen ] ;
            System.arraycopy( t,0,binary,0,t.length ) ;
            t = null ;
        }
        binary[ length ] = ( byte )( b & 0x000000ff ) ;
        length ++ ;
    }
    
    public void write( byte[] binary ) throws Exception {
        if( binary == null || binary.length <= 0 ) {
            return ;
        }
        int len = binary.length ;
        for( int i = 0 ; i < len ; i ++ ) {
            write( ( int )( binary[ i ] & 0x000000ff ) ) ;
        }
    }
    
    public byte getByte( int no ) {
        return binary[ no ] ;
    }
    
    public byte[] getRawBinary() {
        return binary ;
    }
    
    public byte[] getBinary() {
        return getBinary( 0 ) ;
    }
    
    public byte[] getBinary( int length ) {
        if( length <= 0 ) {
            length = this.length ;
        }
        if( this.length < length ) {
            length = this.length ;
        }
        byte[] ret = new byte[ length ] ;
        System.arraycopy( this.binary,0,ret,0,length ) ;
        return ret ;
    }
    
    public int length() {
        return length ;
    }
}
