How to allocate buffers

Explains the functions to create and allocate flat and segmented buffers.

Allocating buffers is simple: use the desired class’s static NewL() function. You must specify a granularity, whose meaning is particular to the buffer type.

Flat buffer

To allocate a flat buffer, use CFlatBuf::NewL(). The granularity in this case means the number of bytes by which the buffer will be re-allocated, whenever expansion is necessary. If expansion by a greater amount than this is required, the next highest multiple of the granularity will be used.

In this example, the buffer pointer is pushed to the cleanup stack for the lifetime of the buffer. If any operation involving the buffer should leave, the buffer will be destroyed. In real use, the buffer pointer would be stored as member data, and care should be taken to ensure that the consequences of a leave are not fatal to the application. For example, if the buffer is being used to store a word processor document, an attempt to add a character may fail due to lack of memory. This should never cause the entire document to be destroyed! Instead, the editing code should function in such a way that the update is either implemented successfully, or no change is made to the document.

The function StandardBufferStuffL() is one which takes a CBufBase type.

 // do flat buffer tests
 CBufFlat* flatBuf=CBufFlat::NewL(4);
 CleanupStack::PushL(flatBuf);
 StandardBufferStuffL(flatBuf);
 CleanupStack::PopAndDestroy();

Segmented buffer

A segmented buffer is allocated in a similar way to a flat buffer. The granularity in this case specifies the size of each segment. During buffer operations, each segment may contain less data than the granularity. After a compress, data is optimally distributed to segments, so that all segments except possibly the last one are full.

During their lifetime, all standard buffer operations can be performed on either flat or segmented buffers. This is shown in the examples above by calling standardBufferStuffL() with both a flat and a segmented buffer pointer. The argument to this function is a CBufBase*.

The granularities chosen for these examples are much smaller than would be used in most real applications.

 // do segmented buffer tests
 CBufSeg* segBuf=CBufSeg::NewL(4);
 CleanupStack::PushL(segBuf);
 standardBufferStuffL(segBuf);
 CleanupStack::PopAndDestroy();

Related concepts