
#include "base/at_objects.h"
#include "base/at_objptr.h"

static uint32 _t_size;
static uint32 _ref_buf_dim;

refBuf::refBuf
  () :
    t_size(_t_size),
    dim(_ref_buf_dim),
    refs(1),
    touched(false)
{
}

void* refBuf::operator new
  (size_t thisSize,
   uint TSize,
   uint bufDim)
{
  _ref_buf_dim = bufDim;
  _t_size = TSize;

  uint32 size =
#   ifndef NDEBUG // satisfy CodeGuard
    4 +
#   endif
    thisSize + _ref_buf_dim * _t_size;

  return new byte[size]; //GlobalAllocPtr(GMEM_MOVEABLE, size);
}

void* refBuf::operator new
  (size_t thisSize,
   const refBuf *const sameSize)
{
  return refBuf::operator new(thisSize, sameSize->t_size, sameSize->dim);
}

void refBuf::operator delete
  (void *p)
{
  delete [] p; //GlobalFreePtr(p);
}

bool refBuf::shared
  ()
  const
{
  return (refs > 2); // one ref for an object and another one for a pointer
}

void* refBuf::lock
  ()
{
  touched = true;
  ++refs;
  return (void*) buf;
}

void* refBuf::unlock
  ()
{
  return (--refs == 0)
    ? buf // signal that obj should be deleted
    : 0;
}

void refBuf::ref
  ()
  const
{
  ++refs;
}

void *refBuf::unref
  ()
{
  return (--refs == 0)
    ? buf // signal that obj should be deleted
    : 0;
}

