/*
 * util/Persist.cc:
 *
 * Copyright (C) 2000 John Watson, jwatson@tempusmud.com
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * 
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * 
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
 * 
 */

#include "Persist.h"
        
/**
 * len must be even
 */

inline static void swab( unsigned char * p, int len ) {
        for ( int i = 0; i < len; i+=2 ) {
                unsigned char tmp = p[i];
                p[i] = p[i+1];
                p[i+1] = tmp;
        }
}

inline static void swab( float * f ) {
        swab( (unsigned char *) f, sizeof( float ) );
}

inline static void swab( short * s ) {
        unsigned char c = *( (unsigned char *) s );
        *( ( (unsigned char *) s ) ) = *( ( (unsigned char *) s ) + 1 );
        *( ( (unsigned char *) s ) + 1 ) = c;
}

char * Persist::readString( istream & is, char * buf, int len ) {
        short thelen = readShort( is );
        thelen = thelen < len ? thelen : ( len - 1 );
        is.read( buf, thelen );
        buf[ thelen ] = 0;
        return *buf ? buf : 0;
};

void Persist::writeString( ostream & os, const char * buf, int len = -1 ) {
        if ( buf ) {
                if ( len < 0 )
                        len = strlen( buf ); 
                writeShort( os, len );
                os.write( buf, len );
        }
        else
                writeShort( os, 0 );
}
short Persist::readShort( istream & is ) {
        short s;
        is.read( &s, 2 );
        swab( &s );
        return s;
}

void Persist::writeShort( ostream & os, short s ) {
        swab( &s );
        os.write( &s, 2 );
}

void Persist::writeFloat( ostream & os, float f ) {
        swab( &f );
        os.write( &f, sizeof( float ) );
}

float Persist::readFloat( istream & is ) {
        float f;
        is.read( &f, sizeof( float ) );
        swab( &f );
        return f;
}
                 
