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 */ 020 package org.apache.directory.server.core.partition.impl.btree.jdbm; 021 022 023 import java.io.IOException; 024 025 import jdbm.helper.Serializer; 026 027 028 /** 029 * A custom String serializer to [de]serialize Strings. 030 * 031 * @author <a href="mailto:dev@directory.apache.org">Apache Directory Project</a> 032 * @version $Rev$, $Date$ 033 */ 034 public class StringSerializer implements Serializer 035 { 036 private static final long serialVersionUID = -173163945773783649L; 037 038 039 /* (non-Javadoc) 040 * @see jdbm.helper.Serializer#deserialize(byte[]) 041 */ 042 public Object deserialize( byte[] bites ) throws IOException 043 { 044 if ( bites.length == 0 ) 045 { 046 return ""; 047 } 048 049 char[] strchars = new char[bites.length >> 1]; 050 for ( int ii = 0, jj = 0; ii < strchars.length; ii++, jj = ii << 1 ) 051 { 052 int ch = bites[jj] << 8 & 0x0000FF00; 053 ch |= bites[jj+1] & 0x000000FF; 054 strchars[ii] = ( char ) ch; 055 } 056 return new String( strchars ); 057 } 058 059 060 private static final byte[] EMPTY_BYTE_ARRAY = new byte[0]; 061 062 /* (non-Javadoc) 063 * @see jdbm.helper.Serializer#serialize(java.lang.Object) 064 */ 065 public byte[] serialize( Object str ) throws IOException 066 { 067 if ( ( ( String ) str ).length() == 0 ) 068 { 069 return EMPTY_BYTE_ARRAY; 070 } 071 072 char[] strchars = ( ( String ) str ).toCharArray(); 073 byte[] bites = new byte[strchars.length<<1]; 074 for ( int ii = 0, jj = 0; ii < strchars.length; ii++, jj = ii << 1 ) 075 { 076 bites[jj] = ( byte ) ( strchars[ii] >> 8 & 0x00FF ); 077 bites[jj+1] = ( byte ) ( strchars[ii] & 0x00FF ); 078 } 079 080 return bites; 081 } 082 }