Relax CHECK condition in stringAppendfImpl
authorSarang Masti <mssarang@fb.com>
Sat, 14 Mar 2015 17:24:15 +0000 (10:24 -0700)
committerNoam Lerner <noamler@fb.com>
Wed, 25 Mar 2015 22:36:19 +0000 (15:36 -0700)
Summary:
vsnprintf can return fewer bytes and bytes_used if
we print a string containing '\0' using a width
specifier.

Test Plan: -- ran all tests

Reviewed By: andrei.alexandrescu@fb.com

Subscribers: folly-diffs@, yfeldblum

FB internal diff: D1915035

Signature: t1:1915035:1426799341:4aaea928c4bdde1998bf66cf9e2732a53572c6e3

folly/String.cpp

index cc261d81adc999ade460e1e90dbfcb2d15618428..a3fa43f415c305e20f762ea317801bed84917cfc 100644 (file)
@@ -73,12 +73,13 @@ void stringAppendfImpl(std::string& output, const char* format, va_list args) {
   std::unique_ptr<char[]> heap_buffer(new char[bytes_used + 1]);
   int final_bytes_used =
       stringAppendfImplHelper(heap_buffer.get(), bytes_used + 1, format, args);
-  // The second call should require the same length, which is 1 less
-  // than the buffer size (we don't keep the trailing \0 byte in our
-  // output string).
-  CHECK(bytes_used == final_bytes_used);
+  // The second call can take fewer bytes if, for example, we were printing a
+  // string buffer with null-terminating char using a width specifier -
+  // vsnprintf("%.*s", buf.size(), buf)
+  CHECK(bytes_used >= final_bytes_used);
 
-  output.append(heap_buffer.get(), bytes_used);
+  // We don't keep the trailing '\0' in our output string
+  output.append(heap_buffer.get(), final_bytes_used);
 }
 
 } // anon namespace