String::copyToUTF8(NULL, max) => bad count


#1

Length calculation for copying strings seems to be messed up.

Docs say, supplying a NULL buffer will return the no. of bytes required including the zero terminator. This used to be so but the new String doesn’t count the zero terminator.

The counting is done by this code from juce_CharPointer_UTF8.h

[code] template
static size_t getBytesRequiredFor (CharPointer text) noexcept
{
size_t count = 0;
juce_wchar n;

    while ((n = text.getAndAdvance()) != 0)
        count += getBytesRequiredFor (n);

    return count;
}

[/code]
which doesn’t count the terminating zero.

Version 1.52 does this:

[code]int String::copyToUTF8 (char* const buffer, const int maxBufferSizeBytes) const throw()
{
jassert (maxBufferSizeBytes >= 0); // keep this value positive, or no characters will be copied!
int num = 0, index = 0;

for (;;)
{
    const uint32 c = (uint32) text [index++];

    if (c >= 0x80)
    {
        /* handle multibyte chars */
    }
    else
    {
        if (buffer != 0)
        {
            if (num + 1 >= maxBufferSizeBytes)
            {
                buffer [num++] = 0;
                break;
            }

            buffer [num] = (uint8) c;
        }

        ++num; /* this will happen for zero terminator too */
    }

    if (c == 0)
        break;
}

return num;

}
[/code]

which correctly includes the zero terminator in the count, by placing the break test after the increment.

None of the versions allow for embedded zero chars in the text but I figure that’s by design.


#2

Thanks! Will sort that out today!


#3

Thanks - works OK now