[haiku-development] printf-convention BString filler

  • From: "Jonas Sundström" <jonas@xxxxxxxxxxx>
  • To: haiku-development@xxxxxxxxxxxxx
  • Date: Wed, 23 Feb 2011 16:20:18 +0100

I've made a function which can be used like this:
vbprintf(string, B_TRANSLATE("%s finds %ld %s!"), person, number, item);

It follows printf formatting convention.
(This probably applies: http://linux.die.net/man/3/printf )

status_t
vbprintf(BString& string, const char *format, ...)
{
        char* buffer = NULL;
        int32 result = -1;
        int32 bufSize = 10;
        buffer = new char[bufSize];

        // step 1: figure out the size of the needed buffer
        va_list arg;
        va_start(arg, format);
        result = vsnprintf(buffer, bufSize, format, arg);
        va_end(arg);

        delete[] buffer;
        bufSize = result + 1;
        buffer = new char[bufSize];

        // step 2: try a large enough buffer
        va_list arg2;
        va_start(arg2, format);
        result = vsnprintf(buffer, bufSize, format, arg2);
        va_end(arg2);

        string = buffer;
        delete[] buffer;

        if (result > 0 && result == bufSize - 1) {
                return B_OK;
        } else {
                string.Truncate(0);
                return B_ERROR;
        }
}

What do you think? Is it correct? Can it be improved?

Should it be included, and if so how/where?

(The outcome of previous discussion may have slipped my mind.
So if this is an unwanted rehash, please do tell.)

/Jonas.


Other related posts: