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.CharComparator;
27 import org.apache.directory.mavibot.btree.exception.SerializerCreationException;
28
29
30
31
32
33
34
35 public class CharSerializer extends AbstractElementSerializer<Character>
36 {
37
38 public static final CharSerializer INSTANCE = new CharSerializer();
39
40
41
42
43 private CharSerializer()
44 {
45 super( CharComparator.INSTANCE );
46 }
47
48
49
50
51
52 public byte[] serialize( Character element )
53 {
54 byte[] bytes = new byte[2];
55
56 return serialize( bytes, 0, element );
57 }
58
59
60
61
62
63
64
65
66 public static byte[] serialize( char value )
67 {
68 byte[] bytes = new byte[2];
69
70 return serialize( bytes, 0, value );
71 }
72
73
74
75
76
77
78
79
80
81
82 public static byte[] serialize( byte[] buffer, int start, char value )
83 {
84 buffer[start] = ( byte ) ( value >>> 8 );
85 buffer[start + 1] = ( byte ) ( value );
86
87 return buffer;
88 }
89
90
91
92
93
94
95
96 public static Character deserialize( byte[] in )
97 {
98 return deserialize( in, 0 );
99 }
100
101
102
103
104
105
106
107
108 public static Character deserialize( byte[] in, int start )
109 {
110 if ( ( in == null ) || ( in.length < 2 + start ) )
111 {
112 throw new SerializerCreationException( "Cannot extract a Character from a buffer with not enough bytes" );
113 }
114
115 return Character.valueOf( ( char ) ( ( in[start] << 8 ) +
116 ( in[start + 1] & 0xFF ) ) );
117 }
118
119
120
121
122
123
124
125 public Character fromBytes( byte[] in )
126 {
127 return deserialize( in, 0 );
128 }
129
130
131
132
133
134
135
136
137 public Character fromBytes( byte[] in, int start )
138 {
139 if ( ( in == null ) || ( in.length < 2 + start ) )
140 {
141 throw new SerializerCreationException( "Cannot extract a Character from a buffer with not enough bytes" );
142 }
143
144 return Character.valueOf( ( char ) ( ( in[start] << 8 ) +
145 ( in[start + 1] & 0xFF ) ) );
146 }
147
148
149
150
151
152 public Character deserialize( ByteBuffer buffer ) throws IOException
153 {
154 return buffer.getChar();
155 }
156
157
158
159
160
161 public Character deserialize( BufferHandler bufferHandler ) throws IOException
162 {
163 byte[] in = bufferHandler.read( 2 );
164
165 return deserialize( in );
166 }
167 }