From: Alexey Vetlov Date: Thu, 30 Sep 2021 19:11:14 +0000 (+0400) Subject: ICU-21768 Fixed (u_snprintf improperly counts the required buffer size). Modified... X-Git-Tag: release-71-rc~31 X-Git-Url: https://granicus.if.org/sourcecode?a=commitdiff_plain;h=1393face12f7205a133a63f13bb592f561b4abfb;p=icu ICU-21768 Fixed (u_snprintf improperly counts the required buffer size). Modified TestSnprintf to test the null buffer case. --- diff --git a/icu4c/source/io/sprintf.cpp b/icu4c/source/io/sprintf.cpp index 3a593abb480..ede31e91517 100644 --- a/icu4c/source/io/sprintf.cpp +++ b/icu4c/source/io/sprintf.cpp @@ -41,6 +41,12 @@ u_sprintf_write(void *context, int32_t count) { u_localized_print_string *output = (u_localized_print_string *)context; + + /* just calculating buffer size */ + if (output->str == 0) { + return count; + } + int32_t size = ufmt_min(count, output->available); u_strncpy(output->str + (output->len - output->available), str, size); @@ -58,6 +64,12 @@ u_sprintf_pad_and_justify(void *context, int32_t written = 0; int32_t lengthOfResult = resultLen; + /* just calculating buffer size */ + if (output->str == 0 && + info->fWidth != -1 && resultLen < info->fWidth) { + return info->fWidth; + } + resultLen = ufmt_min(resultLen, output->available); /* pad and justify, if needed */ diff --git a/icu4c/source/test/iotest/strtst.c b/icu4c/source/test/iotest/strtst.c index ee67b4c3ab1..3ffec2b25dc 100644 --- a/icu4c/source/test/iotest/strtst.c +++ b/icu4c/source/test/iotest/strtst.c @@ -315,9 +315,10 @@ static void TestLocalizedString(void) { #if !UCONFIG_NO_FORMATTING #define Test_u_snprintf(limit, format, value, expectedSize, expectedStr) UPRV_BLOCK_MACRO_BEGIN { \ u_uastrncpy(testStr, "xxxxxxxxxxxxxx", UPRV_LENGTHOF(testStr));\ - size = u_snprintf(testStr, limit, format, value);\ + size = u_snprintf(0, 0, format, value);\ + written = u_snprintf(testStr, limit, format, value);\ u_austrncpy(cTestResult, testStr, UPRV_LENGTHOF(cTestResult));\ - if (size != expectedSize || strcmp(cTestResult, expectedStr) != 0) {\ + if (size != written || size != expectedSize || strcmp(cTestResult, expectedStr) != 0) {\ log_err("Unexpected formatting. size=%d expectedSize=%d cTestResult=%s expectedStr=%s\n",\ size, expectedSize, cTestResult, expectedStr);\ }\ @@ -332,7 +333,7 @@ static void TestSnprintf(void) { #if !UCONFIG_NO_FORMATTING UChar testStr[256]; char cTestResult[256]; - int32_t size; + int32_t size, written; Test_u_snprintf(0, "%d", 123, 3, "xxxxxxxxxxxxxx"); Test_u_snprintf(2, "%d", 123, 3, "12xxxxxxxxxxxx");