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 ByteBuffer
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 public ByteBuffer()
49 {
50 this( DEFAULT_INITIAL_SIZE );
51 }
52
53
54
55
56
57
58
59 public ByteBuffer( int initialSize )
60 {
61 if ( initialSize <= 0 )
62 {
63 throw new IllegalArgumentException( I18n.err( I18n.ERR_04354 ) );
64 }
65
66 this.initialSize = initialSize;
67 this.buf = new byte[initialSize];
68 }
69
70
71
72
73
74
75
76 public final void clear()
77 {
78 pos = 0;
79 }
80
81
82
83
84
85 public final int position()
86 {
87 return pos;
88 }
89
90
91
92
93
94 public final int capacity()
95 {
96 return buf.length;
97 }
98
99
100
101
102
103
104
105
106
107 public final byte get( int i )
108 {
109 return buf[i];
110 }
111
112
113
114
115
116
117
118
119
120 public final byte[] buffer()
121 {
122 return buf;
123 }
124
125
126
127
128
129
130
131 public final byte[] copyOfUsedBytes()
132 {
133 byte[] copy = new byte[pos];
134 System.arraycopy( buf, 0, copy, 0, pos );
135 return copy;
136 }
137
138
139
140
141
142
143
144 public final void append( byte[] bytes )
145 {
146 if ( pos + bytes.length > buf.length )
147 {
148 growBuffer( bytes.length );
149 }
150
151 System.arraycopy( bytes, 0, buf, pos, bytes.length );
152 pos += bytes.length;
153 }
154
155
156
157
158
159
160
161 public final void append( byte b )
162 {
163 if ( pos >= buf.length )
164 {
165 growBuffer();
166 }
167
168 buf[pos] = b;
169 pos++;
170 }
171
172
173
174
175
176
177
178
179 public final void append( int val )
180 {
181 if ( pos >= buf.length )
182 {
183 growBuffer();
184 }
185
186 buf[pos] = ( byte ) val;
187 pos++;
188 }
189
190
191 private void growBuffer( int size )
192 {
193 if ( size > initialSize )
194 {
195 byte[] copy = new byte[buf.length + size];
196 System.arraycopy( buf, 0, copy, 0, pos );
197 this.buf = copy;
198 }
199 else
200 {
201 byte[] copy = new byte[buf.length + initialSize];
202 System.arraycopy( buf, 0, copy, 0, pos );
203 this.buf = copy;
204 }
205 }
206
207
208 private void growBuffer()
209 {
210 byte[] copy = new byte[buf.length + initialSize];
211 System.arraycopy( buf, 0, copy, 0, pos );
212 this.buf = copy;
213 }
214 }