KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > jxl > biff > ByteArray


1 /*********************************************************************
2 *
3 * Copyright (C) 2005 Andrew Khan
4 *
5 * This library is free software; you can redistribute it and/or
6 * modify it under the terms of the GNU Lesser General Public
7 * License as published by the Free Software Foundation; either
8 * version 2.1 of the License, or (at your option) any later version.
9 *
10 * This library is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 * Lesser General Public License for more details.
14 *
15 * You should have received a copy of the GNU Lesser General Public
16 * License along with this library; if not, write to the Free Software
17 * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
18 ***************************************************************************/

19
20 package jxl.biff;
21
22 /**
23  * A growable array of bytes
24  */

25 public class ByteArray
26 {
27   /**
28    * The array grow size
29    */

30   private int growSize;
31
32   /**
33    * The current array
34    */

35   private byte[] bytes;
36
37   /**
38    * The current position
39    */

40   private int pos;
41
42   // The default grow size
43
private final static int defaultGrowSize = 1024;
44
45   /**
46    * Constructor
47    */

48   public ByteArray()
49   {
50     this(defaultGrowSize);
51   }
52
53   /**
54    * Constructor
55    *
56    * @param gs
57    */

58   public ByteArray(int gs)
59   {
60     growSize = gs;
61     bytes = new byte[defaultGrowSize];
62     pos = 0;
63   }
64
65   /**
66    * Adds a byte onto the array
67    *
68    * @param b the byte
69    */

70   public void add(byte b)
71   {
72     checkSize(1);
73     bytes[pos] = b;
74     pos++;
75   }
76   
77   /**
78    * Adds an array of bytes onto the array
79    *
80    * @param b the array of bytes
81    */

82   public void add(byte[] b)
83   {
84     checkSize(b.length);
85     System.arraycopy(b, 0, bytes, pos, b.length);
86     pos += b.length;
87   }
88
89   /**
90    * Gets the complete array
91    *
92    * @return the array
93    */

94   public byte[] getBytes()
95   {
96     byte[] returnArray = new byte[pos];
97     System.arraycopy(bytes, 0, returnArray, 0, pos);
98     return returnArray;
99   }
100
101   /**
102    * Checks to see if there is sufficient space left on the array. If not,
103    * then it grows the array
104    *
105    * @param sz the amount of bytes to add
106    */

107   private void checkSize(int sz)
108   {
109     while (pos + sz >= bytes.length)
110     {
111       // Grow the array
112
byte[] newArray = new byte[bytes.length + growSize];
113       System.arraycopy(bytes, 0, newArray, 0, pos);
114       bytes = newArray;
115     }
116   }
117 }
118
Popular Tags