]> granicus.if.org Git - icu/commitdiff
ICU-21768 Fixed (u_snprintf improperly counts the required buffer size). Modified...
authorAlexey Vetlov <avetlov@riverlogic.com>
Thu, 30 Sep 2021 19:11:14 +0000 (23:11 +0400)
committerMarkus Scherer <markus.icu@gmail.com>
Tue, 8 Mar 2022 23:09:54 +0000 (23:09 +0000)
icu4c/source/io/sprintf.cpp
icu4c/source/test/iotest/strtst.c

index 3a593abb4805268940d55a9087d07b21b4e3ef39..ede31e9151782f4fa720c67db1e0df0cc7f532ea 100644 (file)
@@ -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 */
index ee67b4c3ab1c185079df9adc81a5f96a466e41f5..3ffec2b25dca79550cb2ade72c239c21ba3d2e78 100644 (file)
@@ -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");