ByteBuffer Class Reference

This class is used to hold a raw buffer of bytes, and is also Flattenable and RefCountable. More...

#include <ByteBuffer.h>

Inheritance diagram for ByteBuffer:

Inheritance graph
[legend]
List of all members.

Public Member Functions

 ByteBuffer (uint32 numBytes=0, const uint8 *optBuffer=NULL, IMemoryAllocationStrategy *optAllocationStrategy=NULL)
 Constructs a ByteBuffer that holds the specified bytes.
 ByteBuffer (const ByteBuffer &copyMe)
 Copy Constructor.
virtual ~ByteBuffer ()
 Destructor.
ByteBufferoperator= (const ByteBuffer &rhs)
 Assigment operator.
uint8 * GetBuffer ()
 Read/Write Accessor.
const uint8 * GetBuffer () const
 Read-only Accessor.
const uint8 * operator() () const
 Convenience synonym for GetBuffer().
uint8 * operator() ()
 Convenience synonym for GetBuffer().
uint32 GetNumBytes () const
 Returns the size of our held buffer, in bytes.
uint32 GetNumAllocatedBytes ()
 Returns the number of bytes we have allocated internally.
bool operator== (const ByteBuffer &rhs) const
 Returns true iff (rhs) is holding data that is byte-for-byte the same as our own data.
bool operator!= (const ByteBuffer &rhs) const
 Returns true iff the data (rhs) is holding is different from our own (byte-for-byte).
status_t SetBuffer (uint32 numBytes=0, const uint8 *optBuffer=NULL)
 Sets our content using the given byte buffer.
void AdoptBuffer (uint32 numBytes, uint8 *optBuffer)
 This method is similar to SetBuffer(), except that instead of copying the bytes out of (optBuffer), we simply assume ownership of (optBuffer) for ourself.
void Clear (bool releaseBuffer=false)
 Resets this ByteBuffer to its empty state, i.e.
status_t SetNumBytes (uint32 newNumBytes, bool retainData)
 Causes us to allocate/reallocate our buffer as necessary to be the given size.
status_t FreeExtraBytes ()
 If we contain any extra bytes that are not being used to hold actual data (i.e.
const uint8 * ReleaseBuffer ()
 Causes us to forget the byte buffer we were holding, without freeing it.
void SwapContents (ByteBuffer &swapWith)
 Swaps our contents with those of the specified ByteBuffer.
virtual bool IsFixedSize () const
 Should return true iff every object of this type has a size that is known at compile time.
virtual uint32 TypeCode () const
 Should return the type code identifying this type of object.
virtual uint32 FlattenedSize () const
 Should return the number of bytes needed to store this object in its current state.
virtual void Flatten (uint8 *buffer) const
 Should store this object's state into (buffer).
virtual bool AllowsTypeCode (uint32 code) const
 Should return true iff a buffer with uint32 (code) can be used to reconstruct this object's state.
virtual status_t Unflatten (const uint8 *buf, uint32 size)
 Should attempt to restore this object's state from the given buffer.
uint32 CalculateChecksum () const
 Returns a 32-bit checksum corresponding to this ByteBuffer's contetns.
void SetMemoryAllocationStrategy (IMemoryAllocationStrategy *imas)
 Sets our allocation strategy pointer.
IMemoryAllocationStrategyGetMemoryAllocationStrategy () const
 Returns the current value of our allocation strategy pointer (may be NULL if the default strategy is in use).
void IncrementRefCount () const
 Increments the counter and returns true iff the new value is zero.
bool DecrementRefCount () const
 Decrements the counter and returns true iff the new value is zero.
void SetManager (AbstractObjectManager *manager)
 Sets the recycle-pointer for this object.
AbstractObjectManagerGetManager () const
 Returns this object's current recyler pointer.
uint32 GetRefCount () const
 Returns this object's current reference count.
status_t CopyTo (Flattenable &copyTo) const
 Causes (copyTo)'s state to set from this Flattenable, if possible.
status_t CopyFrom (const Flattenable &copyFrom)
 Causes our state to be set from (copyFrom)'s state, if possible.
status_t FlattenToByteBuffer (ByteBuffer &outBuf) const
 Convenience method.
Ref< ByteBufferFlattenToByteBuffer () const
 Convenience method.
status_t UnflattenFromByteBuffer (const ByteBuffer &buf)
 Convenience method.
status_t FlattenToDataIO (DataIO &outputStream, bool addSizeHeader) const
 Convenience method.
status_t UnflattenFromDataIO (DataIO &inputStream, int32 optReadSize, uint32 optMaxReadSize=MUSCLE_NO_LIMIT)
 Convenience method.

Static Public Member Functions

static void WriteData (uint8 *outBuf, uint32 *writeOffset, const void *copyFrom, uint32 blockSize)
 Convenience method for writing data into a byte buffer.
static status_t ReadData (const uint8 *inBuf, uint32 inputBufferBytes, uint32 *readOffset, void *copyTo, uint32 blockSize)
 Convenience method for safely reading bytes from a byte buffer.

Protected Member Functions

virtual status_t CopyFromImplementation (const Flattenable &copyFrom)
 Overridden to set our buffer directly from (copyFrom)'s Flatten() method.

Detailed Description

This class is used to hold a raw buffer of bytes, and is also Flattenable and RefCountable.

Definition at line 13 of file ByteBuffer.h.


Constructor & Destructor Documentation

ByteBuffer::ByteBuffer ( uint32  numBytes = 0,
const uint8 *  optBuffer = NULL,
IMemoryAllocationStrategy optAllocationStrategy = NULL 
) [inline]

Constructs a ByteBuffer that holds the specified bytes.

Parameters:
numBytes Number of bytes to copy in (or just allocate, if (optBuffer) is NULL). Defaults to zero bytes (i.e., don't allocate a buffer)
optBuffer May be set to point to an array of (numBytes) bytes that we should copy into our internal buffer. If NULL, this ByteBuffer will contain (numBytes) uninitialized bytes. Defaults to NULL.
optAllocationStrategy If non-NULL, this object will be used to allocate and free bytes. If left as NULL (the default), then muscleAlloc(), muscleRealloc(), and/or muscleFree() will be called as necessary.

Definition at line 23 of file ByteBuffer.h.

References SetBuffer().

ByteBuffer::ByteBuffer ( const ByteBuffer copyMe  )  [inline]

Copy Constructor.

Parameters:
copyMe The ByteBuffer to become a copy of. We will also use (copyMe)'s allocation strategy pointer.

Definition at line 28 of file ByteBuffer.h.

virtual ByteBuffer::~ByteBuffer (  )  [inline, virtual]

Destructor.

Deletes our held byte buffer.

Definition at line 31 of file ByteBuffer.h.

References Clear().


Member Function Documentation

ByteBuffer& ByteBuffer::operator= ( const ByteBuffer rhs  )  [inline]

Assigment operator.

Copies the byte buffer from (rhs). If there is an error copying (out of memory), we become an empty ByteBuffer.

Note:
We do NOT adopt (rhs)'s allocation strategy pointer!

Definition at line 36 of file ByteBuffer.h.

References Clear(), GetBuffer(), GetNumBytes(), and SetBuffer().

uint8* ByteBuffer::GetBuffer (  )  [inline]

Read/Write Accessor.

Returns a pointer to our held buffer, or NULL if we are not currently holding a buffer.

Definition at line 39 of file ByteBuffer.h.

Referenced by operator=(), operator==(), and XorDataIO::Write().

const uint8* ByteBuffer::GetBuffer (  )  const [inline]

Read-only Accessor.

Returns a pointer to our held buffer, or NULL if we are not currently holding a buffer.

Definition at line 42 of file ByteBuffer.h.

uint32 ByteBuffer::GetNumAllocatedBytes (  )  [inline]

Returns the number of bytes we have allocated internally.

Note that this number may be larger than the number of bytes we officially contain (as returned by GetNumBytes())

Definition at line 56 of file ByteBuffer.h.

status_t ByteBuffer::SetBuffer ( uint32  numBytes = 0,
const uint8 *  optBuffer = NULL 
)

Sets our content using the given byte buffer.

Parameters:
numBytes Number of bytes to copy in (or just to allocate, if (optBuffer) is NULL). Defaults to zero bytes (i.e., don't allocate a buffer)
optBuffer May be set to point to an array of bytes to copy into our internal buffer. If NULL, this ByteBuffer will contain (numBytes) uninitialized bytes. Defaults to NULL.
Returns:
B_NO_ERROR on success, or B_ERROR on failure (out of memory--there are no side effects if this occurs)

Referenced by ByteBuffer(), operator=(), and Unflatten().

void ByteBuffer::AdoptBuffer ( uint32  numBytes,
uint8 *  optBuffer 
)

This method is similar to SetBuffer(), except that instead of copying the bytes out of (optBuffer), we simply assume ownership of (optBuffer) for ourself.

This means that this ByteBuffer object will free the passed-in array-pointer later on, so you must be very careful to make sure that that is the right thing to do! If you aren't sure, call SetBuffer() instead.

Parameters:
numBytes Number of bytes that optBuffer points to.
optBuffer Pointer to an array to adopt. Note that we take ownership of this array!

void ByteBuffer::Clear ( bool  releaseBuffer = false  ) 

Resets this ByteBuffer to its empty state, i.e.

not holding any buffer.

Parameters:
releaseBuffer If true, we will immediately muscleFree() any buffer we are holding; otherwise we will keep the buffer around for potential later re-use.

Referenced by operator=(), PacketizedDataIO::Shutdown(), and ~ByteBuffer().

status_t ByteBuffer::SetNumBytes ( uint32  newNumBytes,
bool  retainData 
)

Causes us to allocate/reallocate our buffer as necessary to be the given size.

Parameters:
newNumBytes New desired length for our buffer
retainData If true, we will take steps to ensure our current data is retained (as much as possible). Otherwise, the contents of the resized buffer will be undefined.
Returns:
B_NO_ERROR on success, or B_ERROR on out-of-memory.

Referenced by XorDataIO::Write().

status_t ByteBuffer::FreeExtraBytes (  ) 

If we contain any extra bytes that are not being used to hold actual data (i.e.

if GetNumAllocatedBytes() is returning a valud greater than GetNumBytes(), this method can be called to free up the unused bytes. This method calls muscleRealloc(), so it should be quite efficient. After this method returns successfully, the number of allocated bytes will be equal to the number of used bytes.

Returns:
B_NO_ERROR on success or B_ERROR on failure (although I can't imagine why muscleRealloc() would ever fail)

const uint8* ByteBuffer::ReleaseBuffer (  )  [inline]

Causes us to forget the byte buffer we were holding, without freeing it.

Once this method is called, the calling code becomes responsible for calling muscleFree() on our (previously held) buffer.

Returns:
a pointer to our data bytes. It becomes the responsibility of the caller to muscleFree() this buffer when he is done with it!

Definition at line 107 of file ByteBuffer.h.

void ByteBuffer::SwapContents ( ByteBuffer swapWith  )  [inline]

Swaps our contents with those of the specified ByteBuffer.

This is an efficient O(1) operation.

Parameters:
swapWith ByteBuffer to swap contents with.
Note:
Allocation strategy pointers get swapped by this operation.

Definition at line 113 of file ByteBuffer.h.

References _allocStrategy, _buffer, _numAllocatedBytes, and _numValidBytes.

virtual void ByteBuffer::Flatten ( uint8 *  buffer  )  const [inline, virtual]

Should store this object's state into (buffer).

Parameters:
buffer The bytes to write this object's stat into. Buffer must be at least FlattenedSize() bytes long.

Implements Flattenable.

Definition at line 125 of file ByteBuffer.h.

virtual bool ByteBuffer::AllowsTypeCode ( uint32  code  )  const [inline, virtual]

Should return true iff a buffer with uint32 (code) can be used to reconstruct this object's state.

Defaults implementation returns true iff (code) equals TypeCode() or B_RAW_DATA.

Parameters:
code A type code constant, e.g. B_RAW_TYPE or B_STRING_TYPE, or something custom.
Returns:
True iff this object can Unflatten from a buffer of the given type, false otherwise.

Reimplemented from Flattenable.

Definition at line 126 of file ByteBuffer.h.

virtual status_t ByteBuffer::Unflatten ( const uint8 *  buf,
uint32  size 
) [inline, virtual]

Should attempt to restore this object's state from the given buffer.

Parameters:
buf The buffer of bytes to unflatten from.
size Number of bytes in the buffer.
Returns:
B_NO_ERROR if the Unflattening was successful, else B_ERROR.

Implements Flattenable.

Definition at line 127 of file ByteBuffer.h.

References SetBuffer().

uint32 ByteBuffer::CalculateChecksum (  )  const [inline]

Returns a 32-bit checksum corresponding to this ByteBuffer's contetns.

Note that this method is O(N).

Definition at line 135 of file ByteBuffer.h.

void ByteBuffer::SetMemoryAllocationStrategy ( IMemoryAllocationStrategy imas  )  [inline]

Sets our allocation strategy pointer.

Note that you should be careful when you call this, as changing strategies can lead to allocation/deallocation method mismatches.

Parameters:
imas Pointer to the new allocation strategy to use from now on.

Definition at line 142 of file ByteBuffer.h.

void RefCountable::IncrementRefCount (  )  const [inline, inherited]

Increments the counter and returns true iff the new value is zero.

Thread safe.

Definition at line 32 of file RefCount.h.

References AtomicCounter::AtomicIncrement().

bool RefCountable::DecrementRefCount (  )  const [inline, inherited]

Decrements the counter and returns true iff the new value is zero.

Thread safe.

Definition at line 35 of file RefCount.h.

References AtomicCounter::AtomicDecrement().

void RefCountable::SetManager ( AbstractObjectManager manager  )  [inline, inherited]

Sets the recycle-pointer for this object.

If set to non-NULL, this pointer is used by the ObjectPool class to recycle this object when it is no longer in use, so as to avoid the overhead of having to delete it and re-create it later on. The RefCountable class itself does nothing with this pointer. Default value is NULL.

Parameters:
manager Pointer to the new manager object to use, or NULL to use no manager.

Definition at line 44 of file RefCount.h.

uint32 RefCountable::GetRefCount (  )  const [inline, inherited]

Returns this object's current reference count.

Note that the value returned by this method is volatile in multithreaded environments, so it may already be wrong by the time it is returned. Be careful!

Definition at line 54 of file RefCount.h.

References AtomicCounter::GetCount().

status_t Flattenable::CopyTo ( Flattenable copyTo  )  const [inline, inherited]

Causes (copyTo)'s state to set from this Flattenable, if possible.

Default implementation is not very efficient, since it has to flatten this object into a byte buffer, and then unflatten the bytes back into (copyTo). However, you can override CopyFromImplementation() to provide a more efficient implementation when possible.

Parameters:
copyTo Object to make into the equivalent of this object. (copyTo) May be any subclass of Flattenable.
Returns:
B_NO_ERROR on success, or B_ERROR on failure (typecode mismatch, out-of-memory, etc)

Definition at line 76 of file Flattenable.h.

References Flattenable::AllowsTypeCode(), Flattenable::CopyFromImplementation(), and Flattenable::TypeCode().

status_t Flattenable::CopyFrom ( const Flattenable copyFrom  )  [inline, inherited]

Causes our state to be set from (copyFrom)'s state, if possible.

Default implementation is not very efficient, since it has to flatten (copyFrom) into a byte buffer, and then unflatten the bytes back into (this). However, you can override CopyFromImplementation() to provide a more efficient implementation when possible.

Parameters:
copyFrom Object to read from to set the state of this object. (copyFrom) may be any subclass of Flattenable.
Returns:
B_NO_ERROR on success, or B_ERROR on failure (typecode mismatch, out-of-memory, etc)

Definition at line 91 of file Flattenable.h.

References Flattenable::AllowsTypeCode(), Flattenable::CopyFromImplementation(), and Flattenable::TypeCode().

static void Flattenable::WriteData ( uint8 *  outBuf,
uint32 *  writeOffset,
const void *  copyFrom,
uint32  blockSize 
) [inline, static, inherited]

Convenience method for writing data into a byte buffer.

Writes data consecutively into a byte buffer. The output buffer is assumed to be large enough to hold the data.

Parameters:
outBuf Flat buffer to write to
writeOffset Offset into buffer to write to. Incremented by (blockSize) on success.
copyFrom memory location to copy bytes from
blockSize number of bytes to copy

Definition at line 105 of file Flattenable.h.

static status_t Flattenable::ReadData ( const uint8 *  inBuf,
uint32  inputBufferBytes,
uint32 *  readOffset,
void *  copyTo,
uint32  blockSize 
) [inline, static, inherited]

Convenience method for safely reading bytes from a byte buffer.

(Checks to avoid buffer overrun problems)

Parameters:
inBuf Flat buffer to read bytes from
inputBufferBytes total size of the input buffer
readOffset Offset into buffer to read from. Incremented by (blockSize) on success.
copyTo memory location to copy bytes to
blockSize number of bytes to copy
Returns:
B_NO_ERROR if the data was successfully read, B_ERROR if the data couldn't be read (because the buffer wasn't large enough)

Definition at line 120 of file Flattenable.h.

status_t Flattenable::FlattenToByteBuffer ( ByteBuffer outBuf  )  const [inherited]

Convenience method.

Flattens this object into the supplied ByteBuffer object.

Parameters:
outBuf the ByteBuffer to dump our flattened bytes into.
Returns:
B_NO_ERROR on success, or B_ERROR on failure (out of memory?)

Ref<ByteBuffer> Flattenable::FlattenToByteBuffer (  )  const [inherited]

Convenience method.

Allocated an appropriately sized ByteBuffer object via GetByteBufferFromPool(), Flatten()s this object into the byte buffer, and returns the resulting ByteBufferRef. Returns a NULL reference on failure (out of memory?)

status_t Flattenable::UnflattenFromByteBuffer ( const ByteBuffer buf  )  [inherited]

Convenience method.

Unflattens this object from the supplied ByteBuffer object.

Parameters:
buf The ByteBuffer to unflatten from.
Returns:
B_NO_ERROR on success, or B_ERROR on failure.

status_t Flattenable::FlattenToDataIO ( DataIO outputStream,
bool  addSizeHeader 
) const [inherited]

Convenience method.

Flattens this object to the given DataIO object.

Parameters:
outputStream The DataIO object to send our flattened data to. This DataIO should be in blocking I/O mode; this method won't work reliably if used with non-blocking I/O.
addSizeHeader If true, we will prefix our flattened data with a four-byte little-endian uint32 indicating the number of bytes of flattened data that we are going to write. If false, then the buffer size will need to be determined by the reading code by some other means.
Returns:
B_NO_ERROR on success, or B_ERROR on failure.

status_t Flattenable::UnflattenFromDataIO ( DataIO inputStream,
int32  optReadSize,
uint32  optMaxReadSize = MUSCLE_NO_LIMIT 
) [inherited]

Convenience method.

Flattens this object from the given DataIO object.

Parameters:
inputStream the DataIO object to read data from. This DataIO should be in blocking I/O mode; this method won't work reliably if used with non-blocking I/O.
optReadSize If non-negative, this many bytes will be read from (inputStream). If set to -1, then the first four bytes read from the stream will be used to determine how many more bytes should be read from the stream. If the data was created with Flatten(io, true), then set this parameter to -1.
optMaxReadSize An optional value indicating the largest number of bytes that should be read by this call. This value is only used if (optReadSize) is negative. If (optReadSize) is negative and the first four bytes read from (inputStream) are greater than this value, then this method will return B_ERROR instead of trying to read that many bytes. This can be useful if you want to prevent the possibility of huge buffers being allocated due to malicious or corrupted size headers. Defaults to MUSCLE_NO_LIMIT, meaning that no size limit is enforced.
Returns:
B_NO_ERROR if the data was correctly read, or B_ERROR otherwise.


The documentation for this class was generated from the following file:
Generated on Thu Jun 5 17:48:00 2008 for MUSCLE by  doxygen 1.5.1