KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > armedbear > j > ByteBuffer


1 /*
2  * ByteBuffer.java
3  *
4  * Copyright (C) 2000-2002 Peter Graves
5  * $Id: ByteBuffer.java,v 1.1.1.1 2002/09/24 16:08:12 piso Exp $
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * 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 {
26     private byte[] buffer;
27     private int used;
28     private final static int DEFAULT_CAPACITY = 16;
29
30     public ByteBuffer()
31     {
32         buffer = new byte[DEFAULT_CAPACITY];
33     }
34
35     public ByteBuffer(int length) throws NegativeArraySizeException JavaDoc
36     {
37         if (length < 0)
38             throw new NegativeArraySizeException JavaDoc();
39         buffer = new byte[length];
40     }
41
42     public int length()
43     {
44         return used;
45     }
46
47     public int capacity()
48     {
49         return buffer.length;
50     }
51
52     public void ensureCapacity(int minimumCapacity)
53     {
54         if (minimumCapacity <= 0 || buffer.length >= minimumCapacity)
55             return;
56         int newCapacity = buffer.length * 2 + 2;
57         if (newCapacity < minimumCapacity)
58             newCapacity = minimumCapacity;
59         byte newBuffer[] = new byte[newCapacity];
60         System.arraycopy(buffer, 0, newBuffer, 0, used);
61         buffer = newBuffer;
62     }
63
64     public void append(byte[] bytes)
65     {
66         if (used + bytes.length > buffer.length)
67             ensureCapacity(used + bytes.length);
68         System.arraycopy(bytes, 0, buffer, used, bytes.length);
69         used += bytes.length;
70     }
71
72     public void append(byte b)
73     {
74         if (used + 1 > buffer.length)
75             ensureCapacity(used + 1);
76         buffer[used++] = b;
77     }
78
79     public void setLength(int newLength) throws IndexOutOfBoundsException JavaDoc
80     {
81         if (newLength < 0)
82             throw new ArrayIndexOutOfBoundsException JavaDoc(newLength);
83         ensureCapacity(newLength);
84         used = newLength;
85     }
86
87     public byte[] getBytes()
88     {
89         return buffer;
90     }
91 }
92
Popular Tags