01: /*
02: * ByteBuffer.java
03: *
04: * Copyright (C) 2000-2002 Peter Graves
05: * $Id: ByteBuffer.java,v 1.1.1.1 2002/09/24 16:08:12 piso Exp $
06: *
07: * This program is free software; you can redistribute it and/or
08: * modify it under the terms of the GNU General Public License
09: * as published by the Free Software Foundation; either version 2
10: * of the License, or (at your option) any later version.
11: *
12: * This program is distributed in the hope that it will be useful,
13: * but WITHOUT ANY WARRANTY; without even the implied warranty of
14: * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15: * GNU General Public License for more details.
16: *
17: * You should have received a copy of the GNU General Public License
18: * along with this program; if not, write to the Free Software
19: * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
20: */
21:
22: package org.armedbear.j;
23:
24: public final class ByteBuffer {
25: private byte[] buffer;
26: private int used;
27: private final static int DEFAULT_CAPACITY = 16;
28:
29: public ByteBuffer() {
30: buffer = new byte[DEFAULT_CAPACITY];
31: }
32:
33: public ByteBuffer(int length) throws NegativeArraySizeException {
34: if (length < 0)
35: throw new NegativeArraySizeException();
36: buffer = new byte[length];
37: }
38:
39: public int length() {
40: return used;
41: }
42:
43: public int capacity() {
44: return buffer.length;
45: }
46:
47: public void ensureCapacity(int minimumCapacity) {
48: if (minimumCapacity <= 0 || buffer.length >= minimumCapacity)
49: return;
50: int newCapacity = buffer.length * 2 + 2;
51: if (newCapacity < minimumCapacity)
52: newCapacity = minimumCapacity;
53: byte newBuffer[] = new byte[newCapacity];
54: System.arraycopy(buffer, 0, newBuffer, 0, used);
55: buffer = newBuffer;
56: }
57:
58: public void append(byte[] bytes) {
59: if (used + bytes.length > buffer.length)
60: ensureCapacity(used + bytes.length);
61: System.arraycopy(bytes, 0, buffer, used, bytes.length);
62: used += bytes.length;
63: }
64:
65: public void append(byte b) {
66: if (used + 1 > buffer.length)
67: ensureCapacity(used + 1);
68: buffer[used++] = b;
69: }
70:
71: public void setLength(int newLength)
72: throws IndexOutOfBoundsException {
73: if (newLength < 0)
74: throw new ArrayIndexOutOfBoundsException(newLength);
75: ensureCapacity(newLength);
76: used = newLength;
77: }
78:
79: public byte[] getBytes() {
80: return buffer;
81: }
82: }
|