home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Chip 2001 Mobile
/
Chip_Mobile_2001.iso
/
palm
/
business
/
printcar
/
printcar.exe
/
src
/
Util
/
MemBuffer.cc
< prev
next >
Wrap
C/C++ Source or Header
|
2000-06-03
|
4KB
|
213 lines
//
// $Id: MemBuffer.cc,v 1.1.1.1 2000/06/02 22:23:04 sergey Exp $
//
#include <MemoryMgr.h>
#include <ErrorMgr.h>
#include "MemBuffer.h"
#include "DataOutputStream.h"
#include "DataInputStream.h"
#include "Assert.h"
#include "Error.h"
namespace Util
{
MemBuffer::MemBuffer():
_handle(0),
_lockCount(0)
{}
MemBuffer::MemBuffer(VoidHand handle):
_handle(handle),
_lockCount(0)
{}
MemBuffer::~MemBuffer()
{
free();
}
MemBuffer::MemBuffer(const MemBuffer& other):
_handle(0),
_lockCount(0)
{
operator =(other);
}
MemBuffer& MemBuffer::operator =(const MemBuffer& other)
{
free();
_handle = other._handle;
_lockCount = other._lockCount;
const_cast<MemBuffer&>(other).release();
return *this;
}
// operations
void* MemBuffer::lock()
{
if (_handle != 0)
{
++_lockCount;
return (char*)MemHandleLock(_handle);
}
return 0;
}
const void* MemBuffer::lock() const
{
const_cast<MemBuffer*>(this)->lock();
}
void* MemBuffer::lock(int lockSize)
{
if (lockSize > 0)
{
if (ensureBufferSize(lockSize))
return lock();
}
return 0;
}
const void* MemBuffer::lock(int lockSize) const
{
const_cast<MemBuffer*>(this)->lock(lockSize);
}
void MemBuffer::unlock() const
{
if (_handle != 0 && _lockCount > 0)
{
--_lockCount;
if (MemHandleUnlock(_handle) != 0)
assertf(false, "Fail to unlock memory handle (%d)", _lockCount);
}
}
bool MemBuffer::allocate(int size)
{
assert(_handle == 0);
_handle = MemHandleNew(size);
if (_handle == 0)
{
Error::memoryAllocationError(__FILE__, __LINE__);
return false;
}
return true;
}
bool MemBuffer::resize(int size)
{
assert(_handle != 0);
if (MemHandleResize(_handle, size) != 0)
{
Error::memoryAllocationError(__FILE__, __LINE__);
return false;
}
return true;
}
void MemBuffer::free()
{
if (_handle != 0)
{
unlockAll();
if (MemHandleFree(_handle) != 0)
assertf(false, "Fail to free memory", 0);
_handle = 0;
}
}
VoidHand MemBuffer::release()
{
unlockAll();
VoidHand handle = _handle;
_handle = 0;
return handle;
}
// attributes
int MemBuffer::size() const
{
return _handle != 0? MemHandleSize(_handle) : 0;
}
// serialization
void MemBuffer::serialize(DataOutputStream& stream) const
{
const void* data = lock();
if (data != 0)
{
stream.write(size());
stream.writeData(data, size());
}
else
{
stream.write(0);
}
unlock();
}
void MemBuffer::restore(const DataInputStream& stream)
{
int len = stream.readAs<int>();
if (len > 0)
{
void* data = lock(len);
if (data != 0)
{
stream.readData(data, len);
unlock();
}
}
}
// implementation
bool MemBuffer::ensureBufferSize(int newSize)
{
if (_handle == 0)
{
if (!allocate(newSize))
return false;
}
else
{
if (size() < newSize)
{
if (!resize(newSize))
return false;
}
}
return true;
}
void MemBuffer::unlockAll() const
{
while(_lockCount > 0)
unlock();
}
}
// namespace Util