1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.directory.api.util;
21
22
23 import org.apache.directory.api.i18n.I18n;
24
25
26
27
28
29
30
31 public class ExpansibleByteBuffer
32 {
33
34 private static final int DEFAULT_INITIAL_SIZE = 10;
35
36
37 private final int initialSize;
38
39
40 private int pos = 0;
41
42
43 private byte[] buf;
44
45
46
47
48
49 public ExpansibleByteBuffer()
50 {
51 this( DEFAULT_INITIAL_SIZE );
52 }
53
54
55
56
57
58
59
60 public ExpansibleByteBuffer( int initialSize )
61 {
62 if ( initialSize <= 0 )
63 {
64 throw new IllegalArgumentException( I18n.err( I18n.ERR_17042_INITIAL_SIZE_ABOVE_ZERO ) );
65 }
66
67 this.initialSize = initialSize;
68 this.buf = new byte[initialSize];
69 }
70
71
72
73
74
75
76
77 public final void clear()
78 {
79 pos = 0;
80 }
81
82
83
84
85
86 public final int position()
87 {
88 return pos;
89 }
90
91
92
93
94
95
96
97 public final void position( int pos )
98 {
99 this.pos = pos;
100 }
101
102
103
104
105
106 public final int capacity()
107 {
108 return buf.length;
109 }
110
111
112
113
114
115
116
117
118
119 public final byte get( int i )
120 {
121 return buf[i];
122 }
123
124
125
126
127
128
129
130
131
132 public final byte[] buffer()
133 {
134 return buf;
135 }
136
137
138
139
140
141
142
143 public final byte[] copyOfUsedBytes()
144 {
145 byte[] copy = new byte[pos];
146 System.arraycopy( buf, 0, copy, 0, pos );
147 return copy;
148 }
149
150
151
152
153
154
155
156 public final void append( byte[] bytes )
157 {
158 if ( pos + bytes.length > buf.length )
159 {
160 growBuffer( bytes.length );
161 }
162
163 System.arraycopy( bytes, 0, buf, pos, bytes.length );
164 pos += bytes.length;
165 }
166
167
168
169
170
171
172
173 public final void append( byte b )
174 {
175 if ( pos >= buf.length )
176 {
177 growBuffer();
178 }
179
180 buf[pos] = b;
181 pos++;
182 }
183
184
185
186
187
188
189
190
191 public final void append( int val )
192 {
193 if ( pos >= buf.length )
194 {
195 growBuffer();
196 }
197
198 buf[pos] = ( byte ) val;
199 pos++;
200 }
201
202
203 private void growBuffer( int size )
204 {
205 if ( size > initialSize )
206 {
207 byte[] copy = new byte[buf.length + size];
208 System.arraycopy( buf, 0, copy, 0, pos );
209 this.buf = copy;
210 }
211 else
212 {
213 byte[] copy = new byte[buf.length + initialSize];
214 System.arraycopy( buf, 0, copy, 0, pos );
215 this.buf = copy;
216 }
217 }
218
219
220 private void growBuffer()
221 {
222 byte[] copy = new byte[buf.length + initialSize];
223 System.arraycopy( buf, 0, copy, 0, pos );
224 this.buf = copy;
225 }
226 }