// ============================================================================
//	MemUtil.h
// ============================================================================
//	Copyright (c) WildPackets, Inc. 2000-2001. All rights reserved.
//	Copyright (c) AG Group, Inc. 1998-2000. All rights reserved.

#ifndef MEMUTIL_H
#define MEMUTIL_H

#include "AGTypes.h"

namespace MemUtil
{

inline UInt16 Swap16( UInt16 x )
{
	return (UInt16)((x >> 8) | (x << 8));
}

inline SInt16 Swap16( SInt16 x )
{
	return (SInt16)((x >> 8) | (x << 8));
}

inline UInt32 Swap32( UInt32 x )
{
	return (UInt32)(((x << 8) & 0x00FF0000) | (x << 24) | ((x >> 8) & 0x0000FF00) | (x >> 24));
}

inline SInt32 Swap32( SInt32 x )
{
	return (SInt32)(((x << 8) & 0x00FF0000) | (x << 24) | ((x >> 8) & 0x0000FF00) | (x >> 24));
}

inline UInt64 Swap64( UInt64 x )
{
	UInt32*	px = (UInt32*) &x;
	UInt32	y = Swap32( px[0] );
	px[0] = Swap32( px[1] );
	px[1] = y;
	return x;
}

inline SInt64 Swap64( SInt64 x )
{
	UInt32*	px = (UInt32*) &x;
	UInt32	y = Swap32( px[0] );
	px[0] = Swap32( px[1] );
	px[1] = y;
	return x;
}

inline UInt8 Reverse8( UInt8 x )
{
	UInt8	r = 0;
#define S(n)	if ( x & (1 << n ) ) { r |= 0x80 >> n; }
	S(0); S(1); S(2); S(3);
	S(4); S(5); S(6); S(7);
#undef S
	return r;
}

} /* namespace MemUtil */

#if TARGET_OS_MAC
#define BIGTOHOST16(x)		(x)
#define HOSTTOBIG16(x)		(x)
#define BIGTOHOST32(x)		(x)
#define HOSTTOBIG32(x)		(x)
#define BIGTOHOST64(x)		(x)
#define HOSTTOBIG64(x)		(x)
#define LITTLETOHOST16(x)	(MemUtil::Swap16(x))
#define HOSTTOLITTLE16(x)	(MemUtil::Swap16(x))
#define LITTLETOHOST32(x)	(MemUtil::Swap32(x))
#define HOSTTOLITTLE32(x)	(MemUtil::Swap32(x))
#define LITTLETOHOST64(x)	(MemUtil::Swap64(x))
#define HOSTTOLITTLE64(x)	(MemUtil::Swap64(x))
#elif TARGET_OS_WIN32
#define BIGTOHOST16(x)		(MemUtil::Swap16(x))
#define HOSTTOBIG16(x)		(MemUtil::Swap16(x))
#define BIGTOHOST32(x)		(MemUtil::Swap32(x))
#define HOSTTOBIG32(x)		(MemUtil::Swap32(x))
#define BIGTOHOST64(x)		(MemUtil::Swap64(x))
#define HOSTTOBIG64(x)		(MemUtil::Swap64(x))
#define LITTLETOHOST16(x)	(x)
#define HOSTTOLITTLE16(x)	(x)
#define LITTLETOHOST32(x)	(x)
#define HOSTTOLITTLE32(x)	(x)
#define LITTLETOHOST64(x)	(x)
#define HOSTTOLITTLE64(x)	(x)
#else
#pragma message("TARGET unknown!")
#endif

#define NETWORKTOHOST16(x)	BIGTOHOST16(x)
#define HOSTTONETWORK16(x)	HOSTTOBIG16(x)
#define NETWORKTOHOST32(x)	BIGTOHOST32(x)
#define HOSTTONETWORK32(x)	HOSTTOBIG32(x)
#define NETWORKTOHOST64(x)	BIGTOHOST64(x)
#define HOSTTONETWORK64(x)	HOSTTOBIG64(x)

#endif
