1 //===-- VASPrintf.cpp -------------------------------------------*- C++ -*-===//
2 //
3 //                     The LLVM Compiler Infrastructure
4 //
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
7 //
8 //===----------------------------------------------------------------------===//
9 
10 #include "lldb/Utility/VASPrintf.h"
11 
12 #include "llvm/ADT/SmallString.h"
13 
14 using namespace lldb_private;
15 
16 bool lldb_private::VASprintf(llvm::SmallVectorImpl<char> &buf, const char *fmt,
17                              va_list args) {
18   llvm::SmallString<16> error("<Encoding error>");
19   bool result = true;
20 
21   // Copy in case our first call to vsnprintf doesn't fit into our buffer
22   va_list copy_args;
23   va_copy(copy_args, args);
24 
25   buf.resize(buf.capacity());
26   // Write up to `capacity` bytes, ignoring the current size.
27   int length = ::vsnprintf(buf.data(), buf.size(), fmt, args);
28   if (length < 0) {
29     buf = error;
30     result = false;
31     goto finish;
32   }
33 
34   if (size_t(length) >= buf.size()) {
35     // The error formatted string didn't fit into our buffer, resize it
36     // to the exact needed size, and retry
37     buf.resize(length + 1);
38     length = ::vsnprintf(buf.data(), buf.size(), fmt, copy_args);
39     if (length < 0) {
40       buf = error;
41       result = false;
42       goto finish;
43     }
44     assert(size_t(length) < buf.size());
45   }
46   buf.resize(length);
47 
48 finish:
49   va_end(args);
50   va_end(copy_args);
51   return result;
52 }
53