/*
_____       _    _    Corso   Italia,  178
(_|__   .  (_   |_|_  56125           Pisa
(_|_) |)|(()_)()| |   tel.  +39  050 46380
  |   |               picosoft@picosoft.it

 picocpp - basic objects library for picoSQL 

 Copyright (C) Picosoft s.r.l. 1994-2002

 This library is free software; you can redistribute it and/or
 modify it under the terms of the GNU Lesser General Public
 License as published by the Free Software Foundation; either
 version 2.1 of the License, or (at your option) any later version.

 This library 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
 Lesser General Public License for more details.

 You should have received a copy of the GNU Lesser General Public
 License along with this library; if not, write to the Free Software
 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/
# include "pmemman.h"
static char rcsid[] = "$Id: pmemman.cpp 1.3 96/09/16 15:46:56 picoSoft Exp $";
static char rcsidh[] = pmemman_h;
# include "perror.h"

extern "C" {
# include <string.h>
}

PCLASSID (PMemManObj)

void
PMemManObj::Unlock()
{
}  

void
PMemManObj::init (PBool lock)
{
   data = NULL;
   size = 0;
   IsLocked = lock;
}

PMemManObj::PMemManObj (PMemManObj & m)
{
   init(m.IsLocked);
   Alloc (m.size);
   if (size == m.size) {
      memcpy ((char *) *this, (char *) m, size);
      Unlock();
      m.Unlock();
   }
}

PMemManObj::PMemManObj (unsigned long n, PBool lock, char ini)
{
   init(lock);
   Alloc (n);
   if (ini >= 0) {
      memset ((char *) *this, ini, size);
      Unlock();
   }
}

PMemManObj::~PMemManObj()
{
   Alloc (0);
}


PMemManObj &
PMemManObj::operator= (PMemManObj & m)
{
   if (this == &m)
      return *this;
   if (size != m.size)
      Alloc(m.size);
   if (size == m.size) {
      memcpy ((char *) *this,(char *) m, size);
      Unlock();
      m.Unlock();
   }
   return *this;
}

PBool
PMemManObj::operator==(PMemManObj & m)
{
   PBool Return = PFalse;

   if (size == m.size &&
       memcmp((char *) *this,(char *) m, size) == 0) {
      Return = PTrue;
      Unlock();
      m.Unlock();
   }
   return Return;
} 
static const unsigned long MinBlk = 1;
void
PMemManObj::Alloc(unsigned long n)
{
   if (size != n)
      if (size > 0 && size <= MinBlk && n > 0 && n <= MinBlk)
         size = n;
      else {
         if (size > 0) {
            delete data;
            size = 0;
            data = NULL;
         }
         if (n > 0) { 
            data = new char[n > MinBlk ? n : MinBlk];
            if (data != NULL)
               size = n;
            else {
               size = 0;
               PError::InternalError ("Memory Allocation Failure");
            }
         }
      }
}

char *
PMemManObj::gets()
{
   char *Return = "";
   if (size > 0)
      Return = (char *) data;
   return Return;
}
