001/*
002 *  Licensed to the Apache Software Foundation (ASF) under one
003 *  or more contributor license agreements.  See the NOTICE file
004 *  distributed with this work for additional information
005 *  regarding copyright ownership.  The ASF licenses this file
006 *  to you under the Apache License, Version 2.0 (the
007 *  "License"); you may not use this file except in compliance
008 *  with the License.  You may obtain a copy of the License at
009 *  
010 *    http://www.apache.org/licenses/LICENSE-2.0
011 *  
012 *  Unless required by applicable law or agreed to in writing,
013 *  software distributed under the License is distributed on an
014 *  "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 *  KIND, either express or implied.  See the License for the
016 *  specific language governing permissions and limitations
017 *  under the License. 
018 *  
019 */
020package org.apache.directory.server.core.partition.impl.btree.jdbm;
021
022
023import java.io.IOException;
024
025import jdbm.helper.Serializer;
026
027import org.apache.directory.api.util.Strings;
028
029
030/**
031 * A custom String serializer to [de]serialize Strings.
032 *
033 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a>
034 */
035public final class StringSerializer implements Serializer
036{
037    private static final long serialVersionUID = -173163945773783649L;
038
039    /** A static instance of a StringSerializer */
040    public static final StringSerializer INSTANCE = new StringSerializer();
041
042
043    /**
044     * Default private constructor
045     */
046    private StringSerializer()
047    {
048    }
049
050
051    /* (non-Javadoc)
052     * @see jdbm.helper.Serializer#deserialize(byte[])
053     */
054    public Object deserialize( byte[] bytes ) throws IOException
055    {
056        if ( bytes.length == 0 )
057        {
058            return "";
059        }
060
061        char[] strchars = new char[bytes.length >> 1];
062        int pos = 0;
063
064        for ( int i = 0; i < bytes.length; i += 2 )
065        {
066            strchars[pos++] = ( char ) ( ( ( bytes[i] << 8 ) & 0x0000FF00 ) | ( bytes[i + 1] & 0x000000FF ) );
067        }
068
069        return new String( strchars );
070    }
071
072
073    /* (non-Javadoc)
074     * @see jdbm.helper.Serializer#serialize(java.lang.Object)
075     */
076    public byte[] serialize( Object str ) throws IOException
077    {
078        if ( ( ( String ) str ).length() == 0 )
079        {
080            return Strings.EMPTY_BYTES;
081        }
082
083        char[] strchars = ( ( String ) str ).toCharArray();
084        byte[] bites = new byte[strchars.length << 1];
085        int pos = 0;
086
087        for ( char c : strchars )
088        {
089            bites[pos++] = ( byte ) ( c >> 8 & 0x00FF );
090            bites[pos++] = ( byte ) ( c & 0x00FF );
091        }
092
093        return bites;
094    }
095}