package ants; public class ByteArray { byte[] buf; int offset; int len; public ByteArray(int len) { buf = new byte[len]; offset = 0; this.len = len; } public ByteArray(byte[] buf) { this.buf = buf; this.offset = 0; this.len = buf.length; } public ByteArray(byte[] buf, int offset) { this(buf, offset, buf.length-offset); } public ByteArray(byte[] buf, int offset, int len) throws IndexOutOfBoundsException { if (offset + len > buf.length || offset < 0 || len < 0) throw new IndexOutOfBoundsException(); this.buf = buf; this.offset = offset; this.len = len; } public ByteArray(ByteArray parent, int offset) { this(parent, offset, parent.len-offset); } public ByteArray(ByteArray parent, int offset, int len) throws IndexOutOfBoundsException { if (offset < 0 || offset + len > parent.len || len < 0) throw new IndexOutOfBoundsException(); buf = parent.buf; this.offset = parent.offset + offset; this.len = len; } public final int length() { return len; } public final byte getByte(int index) throws IndexOutOfBoundsException { if (index >= len || index < 0) throw new IndexOutOfBoundsException(); return buf[offset + index]; } public final void setByte(int index, byte val) throws IndexOutOfBoundsException { if (index >= len || index < 0) throw new IndexOutOfBoundsException(); buf[offset+index] = val; } public final void getBytes(int srcBegin, byte[] dst, int dstBegin, int length) { System.arraycopy(buf, offset + srcBegin, dst, dstBegin, length); } public final void setBytes(int dstBegin, byte[] src, int srcBegin, int length) { System.arraycopy(src, srcBegin, buf, offset + dstBegin, length); } public final void setBytes(int dstBegin, ByteArray src, int srcBegin, int length) { System.arraycopy(src.buf, src.offset + srcBegin, buf, offset + dstBegin, length); } public final void setBytes(int dstBegin, String src, int srcBegin, int length) { src.getBytes(srcBegin, srcBegin + length, buf, offset + dstBegin); } public final String getString(int hibyte, int offset, int count) { return new String(buf, hibyte, this.offset + offset, count); } public final byte[] toBytes() { if (offset == 0 && len == buf.length) return buf; else { byte[] newbuf = new byte[len]; System.arraycopy(buf, offset, newbuf, 0, len); this.buf = newbuf; this.offset = 0; return buf; } } }