1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.apache.directory.api.asn1.util;
22
23 import java.nio.ByteBuffer;
24
25
26
27
28
29
30
31 public class Asn1Buffer
32 {
33
34 private static final int DEFAULT_SIZE = 1024;
35
36
37 private int pos = 0;
38
39
40 private byte[] buffer;
41
42
43
44
45
46 public Asn1Buffer()
47 {
48 buffer = new byte[DEFAULT_SIZE];
49 }
50
51
52
53
54
55 public int getPos()
56 {
57 return pos;
58 }
59
60
61
62
63
64
65
66 public void setPos( int pos )
67 {
68 this.pos = pos;
69 }
70
71
72
73
74
75
76
77 public void put( byte b )
78 {
79 if ( pos == buffer.length )
80 {
81
82 extend( 1 );
83 }
84
85 pos++;
86 buffer[buffer.length - pos] = b;
87 }
88
89
90
91
92
93
94
95 public void put( byte[] bytes )
96 {
97 if ( pos + bytes.length > buffer.length )
98 {
99
100 extend( bytes.length );
101 }
102
103
104 pos += bytes.length;
105 System.arraycopy( bytes, 0, buffer, buffer.length - pos, bytes.length );
106 }
107
108
109
110
111
112
113
114 private void extend( int size )
115 {
116
117 int newSize = ( ( size + buffer.length ) / DEFAULT_SIZE ) * DEFAULT_SIZE;
118
119 if ( size % DEFAULT_SIZE != 0 )
120 {
121 newSize += DEFAULT_SIZE;
122 }
123
124 byte[] newBuffer = new byte[newSize];
125 System.arraycopy( buffer, 0, newBuffer, newSize - buffer.length, buffer.length );
126
127 buffer = newBuffer;
128 }
129
130
131
132
133
134 public ByteBuffer getBytes()
135 {
136 ByteBuffer result = ByteBuffer.allocate( pos );
137
138 result.put( buffer, buffer.length - pos, pos );
139 result.flip();
140
141 return result;
142 }
143
144
145
146
147
148
149 public int getSize()
150 {
151 return buffer.length;
152 }
153
154
155
156
157
158
159 public void clear()
160 {
161 if ( buffer.length > DEFAULT_SIZE )
162 {
163 buffer = new byte[DEFAULT_SIZE];
164 }
165
166 pos = 0;
167 }
168
169
170
171
172
173 @Override
174 public String toString()
175 {
176 return "[" + buffer.length + ", " + pos + "] '"
177 + Asn1StringUtils.dumpBytes( buffer, buffer.length - pos, pos ) + '\'';
178 }
179 }