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