Using the stringbuffer class

The stringbuffer class can be used to store strings of arbitrary length.

Internally, the class stores this data in a series of extents which are coalesced when getString() or detachString() are called. The size of the initial and incremental extents may be defined in the constructor, if desired.

When cleared, all extents are freed except for the initial extent.

It is generally more efficient to reuse the same stringbuffer over and over than to allocate a new one for each operation.

The stringbuffer class provides methods for appending data, writing to arbitrary locations, clearing and truncating the buffer, getting the data stored in the buffer as a C-style string, getting the length of the string, and detaching the data from the buffer as a C-style string.

When data is detached, it is no longer associated with the buffer and must be freed by the calling program.

#include <rudiments/stringbuffer.h>
#include <rudiments/stdio.h>

int main(int argc, const char **argv) {

        stringbuffer    strb;

        // append strings, numbers, and characters...
        strb.append("hello, ")->append("goodbye, ");
        strb.append((uint64_t)1)->append(", ");

        stdoutput.write("after initial append:\n");
        stdoutput.printf("  contents: \"%s\"\n",strb.getString());
        stdoutput.printf("    length: %d\n",strb.getStringLength());

        // clear the buffer and append more data to it
        strb.append("1 2 3 4 5 6 7 8 9 0");

        // overwrite the first 5 numbers...
        strb.write("0 9 8 7 6");

        stdoutput.write("after overwrite:\n");
        stdoutput.printf("  contents: \"%s\"\n",strb.getString());
        stdoutput.printf("    length: %d\n",strb.getStringLength());

        // truncate the string after the first 2 numbers

        stdoutput.write("after truncate:\n");
        stdoutput.printf("  contents: \"%s\"\n",strb.getString());
        stdoutput.printf("    length: %d\n",strb.getStringLength());

        // detach the string
        char    *str=strb.detachString();

        stdoutput.write("after detach:\n");
        stdoutput.printf("         contents: \"%s\"\n",strb.getString());
        stdoutput.printf("           length: %d\n",strb.getStringLength());
        stdoutput.printf("  detached string: \"%s\"\n",str);

        delete[] str;