// Copyright 1996, Marimba Inc. All Rights Reserved.


// Confidential and Proprietary Information of Marimba, Inc.


// @(#)ByteString.java, 1.5, 12/15/96





package marimba.text;





/**


 * This class implements a byte string object, which is similar to a


 * string.  It's a way to efficiently create substrings (sub byte


 * arrays) into existing arrays of bytes.


 *


 * @author	Jonathan Payne


 * @version 1.5, 12/15/96


 */


public class ByteString {


    public byte data[];


    public int off;


    public int length;





    public ByteString() {


	data = new byte[16];


    }





    public ByteString(byte data[], int off, int length) {


	set(data, off, length);


    }





    public ByteString(String s) {


	length = s.length();


	data = new byte[length];


	s.getBytes(0, length, data, 0);


    }





    public void set(byte data[], int off, int length) {


	this.data = data;


	this.off = off;


	this.length = length;


    }





    public int hashCode() {


	int off = this.off;


	int limit = this.length;


	byte data[] = this.data;


	int hashCode = 0;





	while (--limit >= 0)


	    hashCode = (hashCode << 2) + data[off++];


	return hashCode;


    }





    public boolean equals(Object other) {


	if (other == this)


	    return true;


	if (other instanceof ByteString) {


	    ByteString o = (ByteString) other;





	    if (o.length != length)


		return false;


	    int off = this.off;


	    byte data[] = this.data;


	    int ooff = o.off;


	    byte odata[] = o.data;


	    for (int i = length; --i >= 0; )


		if (data[off++] != odata[ooff++])


		    return false;


	    return true;


	}


	return false;


    }





    public int rindex(int c) {


	int i = off + length;


	int limit = off;


	byte data[] = this.data;





	while (--i >= limit)


	    if (data[i] == c)


		return i - off;


	return -1;


    }





    public ByteString append(String s) {


	byte b[] = new byte[length + s.length()];


	System.arraycopy(data, off, b, 0, length);


	s.getBytes(0, s.length(), b, length);


	return new ByteString(b, 0, b.length);


    }





    public String toString() {


	return this.getClass().getName()


	    + "[off=" + off + ", length = " + length


		+ ", value = " + new String(data, 0, off, length)


		    + "]";


    }


}


