1 /*
2 * Licensed to the Apache Software Foundation (ASF) under one
3 * or more contributor license agreements. See the NOTICE file
4 * distributed with this work for additional information
5 * regarding copyright ownership. The ASF licenses this file
6 * to you under the Apache License, Version 2.0 (the
7 * "License"); you may not use this file except in compliance
8 * with the License. You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing,
13 * software distributed under the License is distributed on an
14 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
15 * KIND, either express or implied. See the License for the
16 * specific language governing permissions and limitations
17 * under the License.
18 *
19 */
20 package org.apache.directory.server.core.partition.impl.btree.jdbm;
21
22
23 import java.io.IOException;
24
25 import jdbm.helper.Serializer;
26
27
28 /**
29 * A custom String serializer to [de]serialize Strings.
30 *
31 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
32 * @version $Rev$, $Date$
33 */
34 public class StringSerializer implements Serializer
35 {
36 private static final long serialVersionUID = -173163945773783649L;
37
38
39 /* (non-Javadoc)
40 * @see jdbm.helper.Serializer#deserialize(byte[])
41 */
42 public Object deserialize( byte[] bites ) throws IOException
43 {
44 if ( bites.length == 0 )
45 {
46 return "";
47 }
48
49 char[] strchars = new char[bites.length >> 1];
50 for ( int ii = 0, jj = 0; ii < strchars.length; ii++, jj = ii << 1 )
51 {
52 int ch = bites[jj] << 8 & 0x0000FF00;
53 ch |= bites[jj+1] & 0x000000FF;
54 strchars[ii] = ( char ) ch;
55 }
56 return new String( strchars );
57 }
58
59
60 private static final byte[] EMPTY_BYTE_ARRAY = new byte[0];
61
62 /* (non-Javadoc)
63 * @see jdbm.helper.Serializer#serialize(java.lang.Object)
64 */
65 public byte[] serialize( Object str ) throws IOException
66 {
67 if ( ( ( String ) str ).length() == 0 )
68 {
69 return EMPTY_BYTE_ARRAY;
70 }
71
72 char[] strchars = ( ( String ) str ).toCharArray();
73 byte[] bites = new byte[strchars.length<<1];
74 for ( int ii = 0, jj = 0; ii < strchars.length; ii++, jj = ii << 1 )
75 {
76 bites[jj] = ( byte ) ( strchars[ii] >> 8 & 0x00FF );
77 bites[jj+1] = ( byte ) ( strchars[ii] & 0x00FF );
78 }
79
80 return bites;
81 }
82 }