1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package org.apache.directory.mavibot.btree.serializer;
21
22
23 import java.io.IOException;
24 import java.nio.ByteBuffer;
25
26 import org.apache.directory.mavibot.btree.comparator.CharArrayComparator;
27
28
29
30
31
32
33
34 public class CharArraySerializer extends AbstractElementSerializer<char[]>
35 {
36
37
38
39 public CharArraySerializer()
40 {
41 super( new CharArrayComparator() );
42 }
43
44
45
46
47
48 public byte[] serialize( char[] element )
49 {
50 int len = -1;
51
52 if ( element != null )
53 {
54 len = element.length;
55 }
56
57 byte[] bytes = null;
58
59 switch ( len )
60 {
61 case 0:
62 bytes = new byte[4];
63
64 bytes[0] = 0x00;
65 bytes[1] = 0x00;
66 bytes[2] = 0x00;
67 bytes[3] = 0x00;
68
69 break;
70
71 case -1:
72 bytes = new byte[4];
73
74 bytes[0] = ( byte ) 0xFF;
75 bytes[1] = ( byte ) 0xFF;
76 bytes[2] = ( byte ) 0xFF;
77 bytes[3] = ( byte ) 0xFF;
78
79 break;
80
81 default:
82 bytes = new byte[len * 2 + 4];
83 int pos = 4;
84
85 bytes[0] = ( byte ) ( len >>> 24 );
86 bytes[1] = ( byte ) ( len >>> 16 );
87 bytes[2] = ( byte ) ( len >>> 8 );
88 bytes[3] = ( byte ) ( len );
89
90 for ( char c : element )
91 {
92 bytes[pos++] = ( byte ) ( c >>> 8 );
93 bytes[pos++] = ( byte ) ( c );
94 }
95 }
96
97 return bytes;
98 }
99
100
101
102
103
104
105
106
107 public static char[] deserialize( byte[] in )
108 {
109 if ( ( in == null ) || ( in.length < 4 ) )
110 {
111 throw new RuntimeException( "Cannot extract a byte[] from a buffer with not enough bytes" );
112 }
113
114 int len = IntSerializer.deserialize( in );
115
116 switch ( len )
117 {
118 case 0:
119 return new char[]
120 {};
121
122 case -1:
123 return null;
124
125 default:
126 char[] result = new char[len];
127
128 for ( int i = 4; i < len * 2 + 4; i += 2 )
129 {
130 result[i] = Character.valueOf( ( char ) ( ( in[i] << 8 ) +
131 ( in[i + 1] & 0xFF ) ) );
132 }
133
134 return result;
135 }
136 }
137
138
139
140
141
142 public char[] deserialize( BufferHandler bufferHandler ) throws IOException
143 {
144 byte[] in = bufferHandler.read( 4 );
145
146 int len = IntSerializer.deserialize( in );
147
148 switch ( len )
149 {
150 case 0:
151 return new char[]
152 {};
153
154 case -1:
155 return null;
156
157 default:
158 char[] result = new char[len];
159 byte[] buffer = bufferHandler.read( len * 2 );
160
161 for ( int i = 0; i < len * 2; i += 2 )
162 {
163 result[i] = Character.valueOf( ( char ) ( ( buffer[i] << 8 ) +
164 ( buffer[i + 1] & 0xFF ) ) );
165 }
166
167 return result;
168 }
169 }
170
171
172
173
174
175 public char[] deserialize( ByteBuffer buffer ) throws IOException
176 {
177 int len = buffer.getInt();
178
179 switch ( len )
180 {
181 case 0:
182 return new char[]
183 {};
184
185 case -1:
186 return null;
187
188 default:
189 char[] result = new char[len];
190
191 for ( int i = 0; i < len; i++ )
192 {
193 result[i] = buffer.getChar();
194 }
195
196 return result;
197 }
198 }
199 }