[llvm] [raw_ostream, Format] Shrink format() callback thunks (PR #206374)

Fangrui Song via llvm-commits llvm-commits at lists.llvm.org
Sun Jun 28 14:24:17 PDT 2026


================
@@ -294,45 +294,38 @@ void raw_ostream::copy_to_buffer(const char *Ptr, size_t Size) {
   OutBufCur += Size;
 }
 
-// Formatted output.
+// Formatted output. Snprint returns the snprintf-style length the output
+// needs, excluding the '\0'. A negative value is a genuine error, which a
+// larger buffer can't fix, so give up and print nothing.
 raw_ostream &
-raw_ostream::operator<<(function_ref<size_t(char *, size_t)> Print) {
+raw_ostream::operator<<(function_ref<int(char *, size_t)> Snprint) {
   // If we have more than a few bytes left in our output buffer, try
   // formatting directly onto its end.
-  size_t NextBufferSize = 127;
+  size_t Size = 128;
   size_t BufferBytesLeft = OutBufEnd - OutBufCur;
   if (BufferBytesLeft > 3) {
-    size_t BytesUsed = Print(OutBufCur, BufferBytesLeft);
-
+    int N = Snprint(OutBufCur, BufferBytesLeft);
+    if (N < 0)
+      return *this;
     // Common case is that we have plenty of space.
-    if (BytesUsed <= BufferBytesLeft) {
-      OutBufCur += BytesUsed;
+    if (size_t(N) < BufferBytesLeft) {
----------------
MaskRay wrote:

Note for reviewers: The `N == BufferBytesLeft` case means the last byte is not written - replaced by '\0'.

The old code uses the confusing  
```
if (unsigned(N) >= BufferSize)
      return N + 1;
```
in the now-deleted `print`

https://github.com/llvm/llvm-project/pull/206374


More information about the llvm-commits mailing list