1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19 package org.apache.directory.api.util;
20
21
22
23
24
25
26
27 public class Serialize
28 {
29 public final static byte TRUE = 0x01;
30 public final static byte FALSE = 0x00;
31
32
33
34
35
36
37
38
39
40 public static int serialize( int value, byte[] buffer, int pos )
41 {
42 if ( buffer.length - pos < 4 )
43 {
44 throw new ArrayIndexOutOfBoundsException();
45 }
46
47 buffer[pos++] = ( byte ) ( ( value >>> 24 ) & 0xFF );
48 buffer[pos++] = ( byte ) ( ( value >>> 16 ) & 0xFF );
49 buffer[pos++] = ( byte ) ( ( value >>> 8 ) & 0xFF );
50 buffer[pos++] = ( byte ) ( ( value >>> 0 ) & 0xFF );
51
52 return pos;
53 }
54
55
56
57
58
59
60
61
62
63 public static int serialize( byte[] value, byte[] buffer, int pos )
64 {
65 if ( buffer.length - pos < 4 + value.length )
66 {
67 throw new ArrayIndexOutOfBoundsException();
68 }
69
70 buffer[pos++] = ( byte ) ( ( value.length >>> 24 ) & 0xFF );
71 buffer[pos++] = ( byte ) ( ( value.length >>> 16 ) & 0xFF );
72 buffer[pos++] = ( byte ) ( ( value.length >>> 8 ) & 0xFF );
73 buffer[pos++] = ( byte ) ( ( value.length >>> 0 ) & 0xFF );
74
75 System.arraycopy( value, 0, buffer, pos, value.length );
76
77 return pos + value.length;
78 }
79
80
81
82
83
84
85
86
87
88 public static int deserializeInt( byte[] buffer, int pos )
89 {
90 if ( buffer.length - pos < 4 )
91 {
92 throw new ArrayIndexOutOfBoundsException();
93 }
94
95 return ( buffer[pos] << 24 ) + ( buffer[pos + 1] << 16 ) + ( buffer[pos + 2] << 8 ) + ( buffer[pos + 3] << 0 );
96 }
97
98
99
100
101
102
103
104
105
106 public static byte[] deserializeBytes( byte[] buffer, int pos )
107 {
108 if ( buffer.length - pos < 4 )
109 {
110 throw new ArrayIndexOutOfBoundsException();
111 }
112
113 int len = deserializeInt( buffer, pos );
114 pos += 4;
115
116 if ( len > 0 )
117 {
118 if ( buffer.length - pos < len )
119 {
120 throw new ArrayIndexOutOfBoundsException();
121 }
122
123 byte[] result = new byte[len];
124
125 System.arraycopy( buffer, pos, result, 0, len );
126
127 return result;
128 }
129 else
130 {
131 return Strings.EMPTY_BYTES;
132 }
133 }
134
135
136
137
138
139
140
141
142
143 public static boolean deserializeBoolean( byte[] buffer, int pos )
144 {
145 if ( buffer.length - pos < 1 )
146 {
147 throw new ArrayIndexOutOfBoundsException();
148 }
149
150 byte value = buffer[pos];
151
152 return ( value != 0x00 );
153 }
154 }