/*------------------------------------------------------------------------------
 src/lib/dj/mem.cxx
 
 Copyright (c) 2004-2006 Darby Johnston.
 All rights reserved.
 Use is subject to license terms.
------------------------------------------------------------------------------*/

//#define DJ_DBG
#include "djMem.h"
#include <string.h>

namespace dj {

void memCopy(const void * in, void * out, int size)
{
  if (! in || ! out || size <= 0) return;
  ::memcpy(out, in, size);
}

void memSet(uint8_t in, void * out, int size)
{
  if (! out || size <= 0) return;
  ::memset(out, in, size);
}

void memZero(void * out, int size)
{
  if (! out || size <= 0) return;
  ::memset(out, 0, size);
}

int memCompare(const void * a, const void * b, int size)
{
  if (! a || ! b || size <= 0) return 0;
  return ::memcmp(a, b, size);
}

ENDIAN endian()
{
  int tmp = 1;
  uint8_t * p = reinterpret_cast<uint8_t *>(&tmp);
  return *p ? LSB : MSB;
}

void endian(void * inplace, int size, int wordSize)
{
  uint8_t * p = reinterpret_cast<uint8_t *>(inplace);
  uint8_t tmp;
  switch (wordSize) {
  
    case 2:
      while (size-- > 0) {
        tmp = p[0];
        p[0] = p[1];
        p[1] = tmp;
        p += 2;
      }
      break;
      
    case 4:
      while (size-- > 0) {
        tmp = p[0];
        p[0] = p[3];
        p[3] = tmp;
        tmp = p[1];
        p[1] = p[2];
        p[2] = tmp;
        p += 4;
      }
      break;
  }
}

void endian(const void * in, void * out, int size, int wordSize)
{
  const uint8_t * inP = reinterpret_cast<const uint8_t *>(in);
  uint8_t * outP = reinterpret_cast<uint8_t *>(out);
  switch (wordSize) {
  
    case 2:
      while (size-- > 0) {
        outP[0] = inP[1];
        outP[1] = inP[0];
        inP += 2;
        outP += 2;
      }
      break;
      
    case 4:
      while (size-- > 0) {
        outP[0] = inP[3];
        outP[1] = inP[2];
        outP[2] = inP[1];
        outP[3] = inP[0];
        inP += 4;
        outP += 4;
      }
      break;
  }
}

}
