FileDocCategorySizeDatePackage
ByteChunk.javaAPI DocApache Tomcat 6.0.1421972Fri Jul 20 04:20:32 BST 2007org.apache.tomcat.util.buf

ByteChunk

public final class ByteChunk extends Object implements Serializable, Cloneable
This class is used to represent a chunk of bytes, and utilities to manipulate byte[]. The buffer can be modified and used for both input and output. There are 2 modes: The chunk can be associated with a sink - ByteInputChannel or ByteOutputChannel, which will be used when the buffer is empty ( on input ) or filled ( on output ). For output, it can also grow. This operating mode is selected by calling setLimit() or allocate(initial, limit) with limit != -1. Various search and append method are defined - similar with String and StringBuffer, but operating on bytes. This is important because it allows processing the http headers directly on the received bytes, without converting to chars and Strings until the strings are needed. In addition, the charset is determined later, from headers or user code.
author
dac@sun.com
author
James Todd [gonzo@sun.com]
author
Costin Manolache
author
Remy Maucherat

Fields Summary
public static final String
DEFAULT_CHARACTER_ENCODING
Default encoding used to convert to strings. It should be UTF8, as most standards seem to converge, but the servlet API requires 8859_1, and this object is used mostly for servlets.
private byte[]
buff
private int
start
private int
end
private String
enc
private boolean
isSet
private int
limit
private ByteInputChannel
in
private ByteOutputChannel
out
private boolean
isOutput
private boolean
optimizedWrite
Constructors Summary
public ByteChunk()
Creates a new, uninitialized ByteChunk object.

    
               
      
    
public ByteChunk(int initial)

	allocate( initial, -1 );
    
Methods Summary
public voidallocate(int initial, int limit)

	isOutput=true;
	if( buff==null || buff.length < initial ) {
	    buff=new byte[initial];
	}    
	this.limit=limit;
	start=0;
	end=0;
	isSet=true;
    
public voidappend(char c)
Append a char, by casting it to byte. This IS NOT intended for unicode.

param
c
throws
IOException

	append( (byte)c);
    
public voidappend(byte b)

	makeSpace( 1 );

	// couldn't make space
	if( limit >0 && end >= limit ) {
	    flushBuffer();
	}
	buff[end++]=b;
    
public voidappend(org.apache.tomcat.util.buf.ByteChunk src)

	append( src.getBytes(), src.getStart(), src.getLength());
    
public voidappend(byte[] src, int off, int len)
Add data to the buffer

	// will grow, up to limit
	makeSpace( len );

	// if we don't have limit: makeSpace can grow as it wants
	if( limit < 0 ) {
	    // assert: makeSpace made enough space
	    System.arraycopy( src, off, buff, end, len );
	    end+=len;
	    return;
	}

        // Optimize on a common case.
        // If the buffer is empty and the source is going to fill up all the
        // space in buffer, may as well write it directly to the output,
        // and avoid an extra copy
        if ( optimizedWrite && len == limit && end == start && out != null ) {
            out.realWriteBytes( src, off, len );
            return;
        }
	// if we have limit and we're below
	if( len <= limit - end ) {
	    // makeSpace will grow the buffer to the limit,
	    // so we have space
	    System.arraycopy( src, off, buff, end, len );
	    end+=len;
	    return;
	}

	// need more space than we can afford, need to flush
	// buffer

	// the buffer is already at ( or bigger than ) limit

        // We chunk the data into slices fitting in the buffer limit, although
        // if the data is written directly if it doesn't fit

        int avail=limit-end;
        System.arraycopy(src, off, buff, end, avail);
        end += avail;

        flushBuffer();

        int remain = len - avail;

        while (remain > (limit - end)) {
            out.realWriteBytes( src, (off + len) - remain, limit - end );
            remain = remain - (limit - end);
        }

        System.arraycopy(src, (off + len) - remain, buff, end, remain);
        end += remain;

    
public static final byte[]convertToBytes(java.lang.String value)
Convert specified String to a byte array. This ONLY WORKS for ascii, UTF chars will be truncated.

param
value to convert to byte array
return
the byte array value

        byte[] result = new byte[value.length()];
        for (int i = 0; i < value.length(); i++) {
            result[i] = (byte) value.charAt(i);
        }
        return result;
    
public booleanequals(java.lang.String s)
Compares the message bytes to the specified String object.

param
s the String to compare
return
true if the comparison succeeded, false otherwise

	// XXX ENCODING - this only works if encoding is UTF8-compat
	// ( ok for tomcat, where we compare ascii - header names, etc )!!!
	
	byte[] b = buff;
	int blen = end-start;
	if (b == null || blen != s.length()) {
	    return false;
	}
	int boff = start;
	for (int i = 0; i < blen; i++) {
	    if (b[boff++] != s.charAt(i)) {
		return false;
	    }
	}
	return true;
    
public booleanequals(org.apache.tomcat.util.buf.ByteChunk bb)

	return equals( bb.getBytes(), bb.getStart(), bb.getLength());
    
public booleanequals(byte[] b2, int off2, int len2)

	byte b1[]=buff;
	if( b1==null && b2==null ) return true;

	int len=end-start;
	if ( len2 != len || b1==null || b2==null ) 
	    return false;
		
	int off1 = start;

	while ( len-- > 0) {
	    if (b1[off1++] != b2[off2++]) {
		return false;
	    }
	}
	return true;
    
public booleanequals(CharChunk cc)

	return equals( cc.getChars(), cc.getStart(), cc.getLength());
    
public booleanequals(char[] c2, int off2, int len2)

	// XXX works only for enc compatible with ASCII/UTF !!!
	byte b1[]=buff;
	if( c2==null && b1==null ) return true;
	
	if (b1== null || c2==null || end-start != len2 ) {
	    return false;
	}
	int off1 = start;
	int len=end-start;
	
	while ( len-- > 0) {
	    if ( (char)b1[off1++] != c2[off2++]) {
		return false;
	    }
	}
	return true;
    
public booleanequalsIgnoreCase(java.lang.String s)
Compares the message bytes to the specified String object.

param
s the String to compare
return
true if the comparison succeeded, false otherwise

	byte[] b = buff;
	int blen = end-start;
	if (b == null || blen != s.length()) {
	    return false;
	}
	int boff = start;
	for (int i = 0; i < blen; i++) {
	    if (Ascii.toLower(b[boff++]) != Ascii.toLower(s.charAt(i))) {
		return false;
	    }
	}
	return true;
    
public static intfindChar(byte[] buf, int start, int end, char c)
Find a character, no side effects.

return
index of char if found, -1 if not

	byte b=(byte)c;
	int offset = start;
	while (offset < end) {
	    if (buf[offset] == b) {
		return offset;
	    }
	    offset++;
	}
	return -1;
    
public static intfindChars(byte[] buf, int start, int end, byte[] c)
Find a character, no side effects.

return
index of char if found, -1 if not

	int clen=c.length;
	int offset = start;
	while (offset < end) {
	    for( int i=0; i<clen; i++ ) 
		if (buf[offset] == c[i]) {
		    return offset;
		}
	    offset++;
	}
	return -1;
    
public static intfindNotChars(byte[] buf, int start, int end, byte[] c)
Find the first character != c

return
index of char if found, -1 if not

	int clen=c.length;
	int offset = start;
	boolean found;
		
	while (offset < end) {
	    found=true;
	    for( int i=0; i<clen; i++ ) {
		if (buf[offset] == c[i]) {
		    found=false;
		    break;
		}
	    }
	    if( found ) { // buf[offset] != c[0..len]
		return offset;
	    }
	    offset++;
	}
	return -1;
    
public voidflushBuffer()
Send the buffer to the sink. Called by append() when the limit is reached. You can also call it explicitely to force the data to be written.

throws
IOException

	//assert out!=null
	if( out==null ) {
	    throw new IOException( "Buffer overflow, no sink " + limit + " " +
				   buff.length  );
	}
	out.realWriteBytes( buff, start, end-start );
	end=start;
    
public byte[]getBuffer()
Returns the message bytes.

	return buff;
    
public byte[]getBytes()
Returns the message bytes.

	return getBuffer();
    
public org.apache.tomcat.util.buf.ByteChunkgetClone()

	try {
	    return (ByteChunk)this.clone();
	} catch( Exception ex) {
	    return null;
	}
    
public java.lang.StringgetEncoding()

        if (enc == null)
            enc=DEFAULT_CHARACTER_ENCODING;
        return enc;
    
public intgetEnd()

	return end;
    
public intgetInt()

	return Ascii.parseInt(buff, start,end-start);
    
public intgetLength()
Returns the length of the bytes. XXX need to clean this up

	return end-start;
    
public intgetLimit()

	return limit;
    
public longgetLong()

        return Ascii.parseLong(buff, start,end-start);
    
public intgetOffset()

	return start;
    
public intgetStart()
Returns the start offset of the bytes. For output this is the end of the buffer.

	return start;
    
public inthash()

	return hashBytes( buff, start, end-start);
    
private static inthashBytes(byte[] buff, int start, int bytesLen)

	int max=start+bytesLen;
	byte bb[]=buff;
	int code=0;
	for (int i = start; i < max ; i++) {
	    code = code * 37 + bb[i];
	}
	return code;
    
private static inthashBytesIC(byte[] bytes, int start, int bytesLen)

	int max=start+bytesLen;
	byte bb[]=bytes;
	int code=0;
	for (int i = start; i < max ; i++) {
	    code = code * 37 + Ascii.toLower(bb[i]);
	}
	return code;
    
public inthashIgnoreCase()

	return hashBytesIC( buff, start, end-start );
    
public intindexOf(java.lang.String src, int srcOff, int srcLen, int myOff)

	char first=src.charAt( srcOff );

	// Look for first char 
	int srcEnd = srcOff + srcLen;
        
	for( int i=myOff+start; i <= (end - srcLen); i++ ) {
	    if( buff[i] != first ) continue;
	    // found first char, now look for a match
            int myPos=i+1;
	    for( int srcPos=srcOff + 1; srcPos< srcEnd; ) {
                if( buff[myPos++] != src.charAt( srcPos++ ))
		    break;
                if( srcPos==srcEnd ) return i-start; // found it
	    }
	}
	return -1;
    
public intindexOf(char c, int starting)
Returns true if the message bytes starts with the specified string.

param
c the character
param
starting The start position

	int ret = indexOf( buff, start+starting, end, c);
	return (ret >= start) ? ret - start : -1;
    
public static intindexOf(byte[] bytes, int off, int end, char qq)

	// Works only for UTF 
	while( off < end ) {
	    byte b=bytes[off];
	    if( b==qq )
		return off;
	    off++;
	}
	return -1;
    
public booleanisNull()

	return ! isSet; // buff==null;
    
private voidmakeSpace(int count)
Make space for len chars. If len is small, allocate a reserve space too. Never grow bigger than limit.

	byte[] tmp = null;

	int newSize;
	int desiredSize=end + count;

	// Can't grow above the limit
	if( limit > 0 &&
	    desiredSize > limit) {
	    desiredSize=limit;
	}

	if( buff==null ) {
	    if( desiredSize < 256 ) desiredSize=256; // take a minimum
	    buff=new byte[desiredSize];
	}
	
	// limit < buf.length ( the buffer is already big )
	// or we already have space XXX
	if( desiredSize <= buff.length ) {
	    return;
	}
	// grow in larger chunks
	if( desiredSize < 2 * buff.length ) {
	    newSize= buff.length * 2;
	    if( limit >0 &&
		newSize > limit ) newSize=limit;
	    tmp=new byte[newSize];
	} else {
	    newSize= buff.length * 2 + count ;
	    if( limit > 0 &&
		newSize > limit ) newSize=limit;
	    tmp=new byte[newSize];
	}
	
	System.arraycopy(buff, start, tmp, 0, end-start);
	buff = tmp;
	tmp = null;
	end=end-start;
	start=0;
    
public voidrecycle()
Resets the message buff to an uninitialized state.

	//	buff = null;
	enc=null;
	start=0;
	end=0;
	isSet=false;
    
public voidreset()

	buff=null;
    
public voidsetByteInputChannel(org.apache.tomcat.util.buf.ByteChunk$ByteInputChannel in)
When the buffer is empty, read the data from the input channel.

        this.in = in;
    
public voidsetByteOutputChannel(org.apache.tomcat.util.buf.ByteChunk$ByteOutputChannel out)
When the buffer is full, write the data to the output channel. Also used when large amount of data is appended. If not set, the buffer will grow to the limit.

	this.out=out;
    
public voidsetBytes(byte[] b, int off, int len)
Sets the message bytes to the specified subarray of bytes.

param
b the ascii bytes
param
off the start offset of the bytes
param
len the length of the bytes

        buff = b;
        start = off;
        end = start+ len;
        isSet=true;
    
public voidsetEncoding(java.lang.String enc)

	this.enc=enc;
    
public voidsetEnd(int i)

	end=i;
    
public voidsetLimit(int limit)
Maximum amount of data in this buffer. If -1 or not set, the buffer will grow undefinitely. Can be smaller than the current buffer size ( which will not shrink ). When the limit is reached, the buffer will be flushed ( if out is set ) or throw exception.

	this.limit=limit;
    
public voidsetOffset(int off)

        if (end < off ) end=off;
	start=off;
    
public voidsetOptimizedWrite(boolean optimizedWrite)

        this.optimizedWrite = optimizedWrite;
    
public booleanstartsWith(java.lang.String s)
Returns true if the message bytes starts with the specified string.

param
s the string

	// Works only if enc==UTF
	byte[] b = buff;
	int blen = s.length();
	if (b == null || blen > end-start) {
	    return false;
	}
	int boff = start;
	for (int i = 0; i < blen; i++) {
	    if (b[boff++] != s.charAt(i)) {
		return false;
	    }
	}
	return true;
    
public booleanstartsWith(byte[] b2)

        byte[] b1 = buff;
        if (b1 == null && b2 == null) {
            return true;
        }

        int len = end - start;
        if (b1 == null || b2 == null || b2.length > len) {
            return false;
        }
        for (int i = start, j = 0; i < end && j < b2.length; ) {
            if (b1[i++] != b2[j++]) 
                return false;
        }
        return true;
    
public booleanstartsWithIgnoreCase(java.lang.String s, int pos)
Returns true if the message bytes starts with the specified string.

param
s the string
param
pos The position

	byte[] b = buff;
	int len = s.length();
	if (b == null || len+pos > end-start) {
	    return false;
	}
	int off = start+pos;
	for (int i = 0; i < len; i++) {
	    if (Ascii.toLower( b[off++] ) != Ascii.toLower( s.charAt(i))) {
		return false;
	    }
	}
	return true;
    
public intsubstract()


        if ((end - start) == 0) {
            if (in == null)
                return -1;
            int n = in.realReadBytes( buff, 0, buff.length );
            if (n < 0)
                return -1;
        }

        return (buff[start++] & 0xFF);

    
public intsubstract(org.apache.tomcat.util.buf.ByteChunk src)


        if ((end - start) == 0) {
            if (in == null)
                return -1;
            int n = in.realReadBytes( buff, 0, buff.length );
            if (n < 0)
                return -1;
        }

        int len = getLength();
        src.append(buff, start, len);
        start = end;
        return len;

    
public intsubstract(byte[] src, int off, int len)


        if ((end - start) == 0) {
            if (in == null)
                return -1;
            int n = in.realReadBytes( buff, 0, buff.length );
            if (n < 0)
                return -1;
        }

        int n = len;
        if (len > getLength()) {
            n = getLength();
        }
        System.arraycopy(buff, start, src, off, n);
        start += n;
        return n;

    
public java.lang.StringtoString()

        if (null == buff) {
            return null;
        } else if (end-start == 0) {
            return "";
        }
        return StringCache.toString(this);
    
public java.lang.StringtoStringInternal()

        String strValue=null;
        try {
            if( enc==null ) enc=DEFAULT_CHARACTER_ENCODING;
            strValue = new String( buff, start, end-start, enc );
            /*
             Does not improve the speed too much on most systems,
             it's safer to use the "clasical" new String().
             
             Most overhead is in creating char[] and copying,
             the internal implementation of new String() is very close to
             what we do. The decoder is nice for large buffers and if
             we don't go to String ( so we can take advantage of reduced GC)
             
             // Method is commented out, in:
              return B2CConverter.decodeString( enc );
              */
        } catch (java.io.UnsupportedEncodingException e) {
            // Use the platform encoding in that case; the usage of a bad
            // encoding will have been logged elsewhere already
            strValue = new String(buff, start, end-start);
        }
        return strValue;